<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="">
                                <!-- {{ model.livingData && model.livingData.livingOrder && model.livingData.livingOrder.arrivalTime || ''}} -->
                                {{ model.roomInfo && model.roomInfo.name}}
                            </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 || ''}} -->
                                {{ model.roomInfo && model.livingData.price.reduce((pre,cur)=> pre+cur.price*1,0) || 0}} / {{ model.roomInfo && model.layout.marketPrice || 0}}
                                <a-popover placement="right">
                                    <template slot="content" v-if="model.livingData">
                                        <div style="max-height:400px;overflow:auto;width:100%;">
                                            <div v-for="(item, index) in model.livingData.price" :key="index">
                                                {{item.dayTime}}
                                                <a-input-number disabled :min="0" v-model="item.price"></a-input-number>
                                            </div>
                                        </div>
                                    </template>
                                    <template slot="title">
                                    </template>
                                    <a-icon type="eye" />
                                </a-popover>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-model-item label="新房间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                                <template v-if="selectData.length>0">
                                    {{newRoom && newRoom.name}}
                                </template> <a href="#" @click="selectVisible = true">选择</a>
                            </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" /> -->
                                <template v-if="newRoom">
                                    {{ timeData.reduce((pre,cur)=> pre+cur.price*1,0) }}
                                    <a-popover placement="right">
                                        <template slot="content">
                                            <div style="max-height:400px;overflow:auto;width:100%;">
                                                <div v-for="(item, index) in timeData" :key="index">
                                                    {{item.day}}
                                                    <a-input-number :disabled="daysBetweenCopy(item.day)" :min="0" v-model="item.price"></a-input-number>
                                                </div>
                                            </div>
                                        </template>
                                        <template slot="title">
                                        </template>
                                        <a-icon type="edit" />
                                    </a-popover>
                                </template>
                                <template v-else>
                                    0
                                    <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="">
                                <!-- <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-modal :title="'选择房间'" :width="800" :visible="selectVisible" @cancel="selectVisible = false" @ok="changeSelct">
        <a-row>
            <a-col :span="24">
                <a-form-model-item label="房型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                    <a-checkbox-group v-model="checkedCesRoomLayoutList" :options="cesRoomLayoutList" @change="checkChange">
                    </a-checkbox-group>
                </a-form-model-item>
            </a-col>
            <a-col :span="24">
                <a-form-model-item label="房态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                    <a-checkbox-group v-model="checkedRoomStatusList" :options="roomStatusList" @change="checkChange">
                    </a-checkbox-group>
                </a-form-model-item>
            </a-col>
            <a-col :span="24">
                <div>
                    <div>已选择{{selectData.length}}间</div>
                    <div v-if="selectData.length>0">
                        {{selectData[0].roomInfo && selectData[0].roomInfo.name}}
                    </div>
                </div>

            </a-col>
            <a-col :span="24" v-if="dataList.length>0">
                <div style="display:flex;flex-wrap:wrap;height:400px;overflow: auto;">
                    <div v-for="(item,index) in dataList" :key="index" @click="selectRoom(item, index)" :class="{'active':index==link}" style="border:1px solid #ccc;padding: 5px 20px;margin-right:10px;margin-top:10px;border-radius:5px;height:30px">
                        {{ item && item.name}}
                    </div>
                </div>
            </a-col>
        </a-row>
    </a-modal>

</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 {
            link: -1,
            customerSourceList: [],
            checkedCustomerSourceList: [],
            roomStatusList: [],
            checkedRoomStatusList: ['1', '2'],
            cesRoomLayoutList: [],
            checkedCesRoomLayoutList: [],
            roomList: [],
            selectVisible: false,
            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: [],
            oldRoomList: [],
            dataList: [],
            selectData: [],
            newRoom: null,
            timeData: [],
        };
    },
    watch: {
        roomList(val) {
            // this.roomList.forEach(ele => {
            //     this.dataList.push(...ele.rooms)
            // })
        }
    },
    computed: {
        formDisabled() {
            return this.disabled;
        },
    },
    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("/rooms/cesRoomLayout/list", {
            pageSize: 99999,
            pageNo: 1,
        }).then((res) => {
            if (res.success) {
                var list = [];
                res.result.records.forEach((item) => {
                    list.push({
                        label: item.name,
                        value: item.id
                    });
                });
                this.cesRoomLayoutList = list;
            }
        });
        getAction("/rooms/cesRooms/room-status-color", {}).then((res) => {
            if (res.success) {
                this.roomStatusColorList = res.result;
                var list = [];
                res.result.forEach((item) => {
                    list.push({
                        label: item.title,
                        value: item.value
                    });
                });
                list = list.filter(item => item.label == '空净' || item.label == '空脏')
                console.log(list);
                this.roomStatusList = list;
            }
        });
    },
    methods: {
        changeSelct() {
            if (this.selectData[0].id == this.model.id) {
                this.$message.warning("不能选择相同的房间");
                return
            }
            this.newRoom = this.selectData[0]
            this.timeData.forEach(ele => {
                ele.price = this.newRoom.marketPrice
            })
            this.selectVisible = false;
        },
        /**
         * 根据传入的数字将日期加上对应的天数
         * @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;
            }
            console.log(time);
            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));
            if (diffDays < 0) {
                diffDays = 1
            }
            return diffDays;
        },
        //比较两个日期大小
        daysBetweenCopy(date1) {
            const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
            const firstDate = new Date(date1);
            const secondDate = new Date();
            // const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
            if (firstDate.getFullYear() >= secondDate.getFullYear()) {
                return false;
            } else if (firstDate.getFullYear() < secondDate.getFullYear()) {
                return true;
            } else {
                if (firstDate.getMonth() >= secondDate.getMonth()) {
                    return false;
                } else if (firstDate.getMonth() < secondDate.getMonth()) {
                    return true;
                } else {
                    if (firstDate.getDate() >= secondDate.getDate()) {
                        return false;
                    } else if (firstDate.getDate() < secondDate.getDate()) {
                        return true;
                    }
                }
            }
            // return diffDays < 0 ? true : false;
        },
        selectRoom(e, idx) {
            console.log(e);
            this.link = idx
            this.selectData[0] = e
        },
        batchPrice(e) {
            console.log(e);
            this.PriceData.forEach(item => {
                item.price = e;
            })
        },
        checkChange(e) {
            console.log("e", e);
            console.log(
                "checkedroomBuildingFloorList",
                this.checkedroomBuildingFloorList
            );
            var list = this.oldRoomList;
            if (this.checkedCesRoomLayoutList.length > 0) {
                list = this.oldRoomList.reduce((acc, curr) => {
                    const floorRooms = curr.floorRooms.filter((room) =>
                        this.checkedCesRoomLayoutList.includes(room.layoutId)
                    );
                    acc.push({
                        ...curr,
                        floorRooms
                    });
                    return acc;
                }, []);
            }
            if (this.checkedRoomStatusList.length > 0) {
                list = list.reduce((acc, curr) => {
                    const floorRooms = curr.floorRooms.filter((room) =>
                        this.checkedRoomStatusList.includes(
                            room.roomStatus.toString()
                        )
                    );
                    acc.push({
                        ...curr,
                        floorRooms
                    });
                    return acc;
                }, []);
            }
            console.log("list2", list);
            this.roomList = list;
            let arr = [];
            this.roomList.forEach(ele => {
                ele.floorRooms.forEach(item => {
                    if (item) {
                        if (arr.some(i => i.id == item.id)) {} else {
                            arr.push(item)
                        }
                    }
                })

            })
            this.dataList = arr
        },
        loadData() {
            // this.checkInBtnDis = false;
            // this.scheduleBtnDis = false;
            // getAction("/rooms/cesRooms/realtime-rooms", {}).then((res) => {
            //     if (res.success) {
            //         res.result.forEach((row) => {
            //             this.$set(row, "collapse", 1);
            //         });
            //         this.roomList = res.result;
            //         this.oldRoomList = JSON.parse(JSON.stringify(res.result));
            //         this.checkChange()
            //     }
            // });
            getAction("/rooms/cesRooms/can-user-rooms", {
                startOf: this.model.livingData.livingOrder.arrivalTime,
                endOf: this.model.livingData.livingOrder.dueOutTime,
                bookingType: 1,
                hourRoomRuleId: '',
                cancelLayout: true,
            }).then((res) => {
                if (res.success) {
                    this.roomList = res.result[0].buildingRooms;
                    this.oldRoomList = JSON.parse(JSON.stringify(res.result[0].buildingRooms));
                    this.checkChange()
                }
            });
        },
        add() {
            this.edit(this.modelDefault);
        },
        edit(record) {
            this.model = Object.assign({}, record);
            this.loadData();
            // this.model.startValue = record.livingData.livingOrder.dueOutTime
            let arr = []
            arr.length = this.daysBetween(record.livingData.livingOrder.dueOutTime, record.livingData.livingOrder.arrivalTime)
            for (let i = 0; i < arr.length; i++) {
                arr[i] = {
                    day: this.addDate(record.livingData.livingOrder.arrivalTime, i),
                    // price: this.model.layout.marketPrice,
                    price: 0
                };
            }
            console.log(arr);
            this.timeData = arr
            this.visible = true;
        },
        submitForm() {
            const that = this;
            // 触发表单验证
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (!this.newRoom) {
                        this.$message.warning("请选择新房间");
                        return
                    }
                    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 prices = this.timeData.map(item => {
                        return {
                            dayTime: item.day,
                            price: item.price,
                            roomId: this.newRoom.id
                        }
                    })
                    // return
                    httpAction(`/business/busRoomBookingOrders/change-living-room?livingOrderId=${this.model.roomInfo.livingOrderId}&changeRoomId=${this.newRoom.id}`, prices, '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>

<style scoped>
.active {
    border: 1px solid red !important;
}
</style>
