<template>
<a-spin :spinning="confirmLoading">
    <a-tabs default-active-key="1" @change="callback">
        <a-tab-pane key="1" tab="操作">
            <j-form-container :disabled="formDisabled">
                <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
                    <a-row>
                        <a-col :span="24">
                            <a-form-model-item label="续住总价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                                <!-- <a-input v-model="model.name" placeholder="请输入餐桌名称"></a-input> -->
                                {{PriceData.reduce((pre,cur)=> pre+cur.price*1,0 ) || 0}}
                                <a-popover placement="right" v-if="dayNum>0">
                                    <template slot="content">
                                        <div style="max-height:400px;overflow:auto;width:100%;">
                                            <div v-for="(item, index) in PriceData" :key="index">
                                                {{item.day}}
                                                <a-input-number :min="0" v-model="item.price"></a-input-number>
                                            </div>
                                        </div>
                                    </template>
                                    <template slot="title">
                                        <a-input-number :min="0" @change="batchPrice" placeholder="批量改价"></a-input-number>
                                    </template>
                                    <a-icon type="edit" />
                                </a-popover>
                                <template v-else>
                                    <a-icon type="edit" />
                                </template>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-model-item label="入住时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                                {{ model.livingData && model.livingData.livingOrder && model.livingData.livingOrder.arrivalTime || ''}}
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-model-item label="预离时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                                {{ model.livingData && model.livingData.livingOrder && model.livingData.livingOrder.dueOutTime || ''}}
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-model-item label="预离变更" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                                <!-- <a-select v-model="model.posRegionId" placeholder="请选择pos类型">
                                    <a-select-option :value="item.id" v-for="item in regionList" :key="item.id">
                                        {{ item.name }}
                                    </a-select-option>
                                </a-select> -->
                                <a-date-picker :disabled-date="disabledStartDate" v-model="model.startValue" show-time format="YYYY-MM-DD HH:mm:ss" :placeholder=" model.livingData && model.livingData.livingOrder && model.livingData.livingOrder.dueOutTime" @change="handleStartOpenChange" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-model-item label="续住天数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                                <a-input-number :min="0" v-model="dayNum" placeholder="请输入续住天数" style="width: 40%" @change="dayChange" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-model-item label="收款方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                                <a-select v-model="model.payType" placeholder="收款方式" style="width: 40%">
                                    <a-select-option :value="item.id" v-for="item in payTypeList" :key="item.id">
                                        {{ item.name }}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-model-item label="金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="num">
                                <a-input-number v-model="model.num" placeholder="请输入金额" style="width: 40%" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                                <!-- <a-input-number v-model="model.num" placeholder="请输入座位数" style="width: 100%" /> -->
                                <a-input v-model="model.remarks"></a-input>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </j-form-container>
        </a-tab-pane>
        <!-- <a-tab-pane key="2" tab="续住记录"></a-tab-pane> -->
    </a-tabs>

</a-spin>
</template>

<script>
import {
    httpAction,
    getAction
} from "@/api/manage";
import {
    validateDuplicateValue
} from "@/utils/util";

export default {
    name: "PosTableForm",
    components: {},
    props: {
        //表单禁用
        disabled: {
            type: Boolean,
            default: false,
            required: false,
        },
    },
    data() {
        return {
            model: {
                day: 0
            },
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 5
                },
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 16
                },
            },
            confirmLoading: false,
            validatorRules: {
                tenantId: [{
                    required: true,
                    message: "请输入关联租户!"
                }],
                hotelId: [{
                    required: true,
                    message: "请输入关联酒店!"
                }],
                name: [{
                    required: true,
                    message: "请输入餐桌名称!"
                }],
                posTypeId: [{
                    required: true,
                    message: "请输入pos类型id!"
                }],
                posTableTypeId: [{
                    required: true,
                    message: "请输入pos桌型id!"
                }],
                posRegionId: [{
                    required: true,
                    message: "请输入pos餐桌区域id!"
                }],
                num: [{
                    required: true,
                    message: "请输入金额!"
                }],
                tableNo: [{
                    required: true,
                    message: "请输入餐桌序号!"
                }],
                state: [{
                    required: true,
                    message: "请输入状态!"
                }],
            },
            url: {
                add: "/pos/posTable/add",
                edit: "/pos/posTable/edit",
                queryById: "/pos/posTable/queryById",
            },
            payTypeList: [],
            tableTypeList: [],
            regionList: [],
            PriceData: [],
            dayNum:0
        };
    },
    watch:{
        dayNum(val){
            let arr = [];
            console.log(this.dayNum);
            if (this.dayNum && this.dayNum > 0) {
                arr.length = this.dayNum;
                for (let i = 0; i < arr.length; i++) {
                    arr[i] = {
                        day: this.addDate(this.model.livingData.livingOrder.dueOutTime, i),
                        price: this.model.layout.marketPrice,
                    };
                }
                this.PriceData = arr;
            } else {
                return [];
            }
        }
    },
    computed: {
        formDisabled() {
            return this.disabled;
        },
        dayDataArr() {
            let arr = [];
            console.log(this.dayNum);
            if (this.dayNum && this.dayNum > 0) {
                arr.length = this.dayNum;
                for (let i = 0; i < arr.length; i++) {
                    arr[i] = {
                        day: this.addDate(this.model.livingData.livingOrder.dueOutTime, i),
                        price: this.model.layout.marketPrice,
                    };
                }
                this.PriceData = arr;
            } else {
                return [];
            }

            return arr;
        }
    },
    created() {
        var _info = JSON.parse(localStorage.getItem("storeInfo"));
        if (_info) {
            this.model.hotelId = _info.id;
        }
        //备份model原始值
        this.modelDefault = JSON.parse(JSON.stringify(this.model));
        // getAction("/pos/posType/list", {
        //     hotelId: _info.id,
        //     pageNo: 1,
        //     pageSize: 100,
        // }).then((res) => {
        //     if (res.success) {
        //         this.posTypeList = res.result.records;
        //     }
        // });
        // getAction("/pos/posTableType/list", {
        //     hotelId: _info.id,
        //     pageNo: 1,
        //     pageSize: 100,
        // }).then((res) => {
        //     if (res.success) {
        //         this.tableTypeList = res.result.records;
        //     }
        // });
        // getAction("/pos/posRegion/list", {
        //     hotelId: _info.id,
        //     pageNo: 1,
        //     pageSize: 100,
        // }).then((res) => {
        //     if (res.success) {
        //         this.regionList = res.result.records;
        //     }
        // });
        getAction("/business/busRoomPayType/list", {
            pageSize: 99999,
            pageNo: 1,
        }).then((res) => {
            if (res.success) {
                this.payTypeList = res.result.records;
            }
        });
    },
    methods: {
        /**
         * 根据传入的数字将日期加上对应的天数
         * @param {String} date 日期
         * @param {Number} days 天数
         * @return {String} 返回日期
         */
        addDate(date, days) {
            console.log(date, days);
            let time = new Date(date);
            time.setDate(time.getDate() + days);
            let m = time.getMonth() + 1;
            let d = time.getDate();
            if (m < 10) {
                m = "0" + m;
            }
            if (d < 10) {
                d = "0" + d;
            }
            return time.getFullYear() + '-' + m + '-' + d + ' ' + time.getHours() + ':' + (time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes()) + ':' + (time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds())
        },

        //计算两个日期之间相隔多少天
        daysBetween(date1, date2) {
            const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
            const firstDate = new Date(date1);
            const secondDate = new Date(date2);
            if (secondDate<firstDate) {
                this.$message.warning("离开时间不能小于预离时间");
                return
            }
            const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
            return diffDays;
        },
        batchPrice(e){
            console.log(e);
            this.PriceData.forEach(item=>{
                item.price = e;
            })
        },

        add() {
            this.edit(this.modelDefault);
        },
        edit(record) {
            this.model = Object.assign({}, record);
            // this.model.startValue = record.livingData.livingOrder.dueOutTime
            this.visible = true;
        },
        submitForm() {
            const that = this;
            // 触发表单验证
            this.$refs.form.validate((valid) => {
                if (valid) {
                    that.confirmLoading = true;
                    let httpurl = "";
                    let method = "";
                    // if (!this.model.id) {
                    //     httpurl += this.url.add;
                    //     method = "post";
                    // } else {
                    //     httpurl += this.url.edit;
                    //     method = "put";
                    // }
                    let obj = {
                        // livingOrderId:this.model.roomInfo.livingOrderId,
                        payType:this.model.payType,
                        remark:this.model.remarks,
                        roomId:this.model.roomInfo.id,
                        money:this.model.num,
                        prices:this.PriceData.map(item=>({
                            livingOrderId:this.model.roomInfo.livingOrderId,
                            dayTime:item.day,
                            price:item.price,
                        }))
                    }
                    // console.log(this.model.startValue);
                    // return
                    httpAction(`/business/busRoomBookingOrders/continue-living?livingOrderId=${this.model.roomInfo.livingOrderId}&dueOutTime=${this.model.startValue}`, obj, 'post')
                        .then((res) => {
                            if (res.success) {
                                that.$message.success(res.message);
                                that.$emit("ok");
                            } else {
                                that.$message.warning(res.message);
                            }
                        })
                        .finally(() => {
                            that.confirmLoading = false;
                        });
                }
            });
        },

        callback(key) {
            console.log(key)
        },
        handleStartOpenChange(e) {
            console.log(e)
            this.dayNum = this.daysBetween(this.model.livingData.livingOrder.dueOutTime, e._d)
            // this.model.startValue = e._i;
        },
        dayChange(e) {
            console.log(e);
            this.model.startValue = this.addDate(this.model.livingData.livingOrder.dueOutTime, e);
        },

        disabledStartDate(endValue) {
            // const endValue = 
            const startValue = this.model.livingData.livingOrder.dueOutTime
            if (!endValue || !startValue) {
                return false;
            }
            return startValue.valueOf() >= endValue.valueOf();
        },
    },
};
</script>
