<template>
  <a-spin :spinning="confirmLoading">
    <a-tabs default-active-key="1" @change="callback">
      <a-tab-pane key="1" tab="操作">
        <!--            <j-form-container :disabled="formDisabled">-->
        <div>
          <a-table
            ref="table"
            size="middle"
            style="width: 80%;height: auto; margin-left: auto; margin-right: auto; margin-bottom: 10px"
            :pagination="false"
            rowKey="id"
            :columns="columns"
            :dataSource="tableData">
            <template slot="arrivalTime" slot-scope="text, record, index">
                <!-- {{ getSubjectTypeText(text,record) }} -->
                {{ handleDateFromat(record.arrivalTime) + '—' + handleDateFromat(record.dueOutTime) }}
              </template>
          </a-table>
          <a-form-model ref="form" :model="model" slot="detail">
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="新房间" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-top: 10px; margin-bottom: 10px" 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" style="margin-bottom: 10px" prop="">
                  {{ newRoom && newRoom.layoutName ? newRoom.layoutName : '--' }}
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="方案" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 10px" prop="">
                  <a-radio-group v-model="roomScheme" name="radioGroup" @change="roomSchemeChange">
                    <a-radio :value="1" :checked="true">原房价</a-radio>
                    <a-radio :value="2" :disabled="!newRoom">新房价</a-radio>
                    <a-radio :value="3">自定义房价</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="新房价" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 10px" prop="">
                  <!-- <a-input-number :min="0" v-model="dayNum" placeholder="请输入续住天数" style="width: 40%" @change="dayChange" /> -->
                  <template>
                    {{ timeData.length > 0 ? timeData[0].price : 0 }}元/总房价{{ newRoomPrice }}元
                    <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) || roomScheme!==3" :min="0" v-model="item.price"></a-input-number>
                          </div>
                        </div>
                      </template>
                      <template slot="title">
                        <a-input-number :min="0" @change="batchPrice" placeholder="批量改价" v-if="roomScheme===3"></a-input-number>
                      </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" style="margin-bottom: 10px" 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-col :span="24" v-if="differPrice > 0">
                <a-form-model-item label="差价付款" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-bottom: 10px" prop="">
                  {{ differPrice }} 元
                  <div v-for="(item, index) in payList" :key="index">
                    <a-row>
                      <a-col :span="6">
                        <a-select v-model="item.payType">
                          <a-select-option
                            :value="item.id"
                            v-for="item in payTypeList"
                            :key="item.id"
                            :disabled="item.disable"
                          >
                            {{ item.name }}
                          </a-select-option>
                        </a-select>
                      </a-col>
                      <a-col :span="6">
                        <a-input-number v-model="item.money" style="margin-left: 20px;"></a-input-number>
                      </a-col>
                      <a-col :span="6">
                        <a-icon
                          v-if="index == payList.length - 1"
                          type="plus-circle"
                          class="dynamic-delete-button"
                          @click="plus()" />
                        <a-icon
                          v-if="payList.length > 1"
                          type="minus-circle"
                          style="color: #f56c6c"
                          class="dynamic-delete-button"
                          @click="() => remove(index)"
                        /></a-col>
                    </a-row>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="24" style="text-align: end">
                <a-checkbox style="margin-top: 20px; margin-right: 10px" default-checked>打印换房单</a-checkbox>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
        <!--            </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="height:300px;overflow: scroll;">
            <div style="display:flex;flex-wrap:wrap;">
              <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>
          </div>
        </a-col>
      </a-row>
    </a-modal>

  </a-spin>
</template>

<script>
import {
    httpAction,
    getAction
} from '@/api/manage'
import {
    validateDuplicateValue
} from '@/utils/util'
import moment from 'moment'
const columns = [
  {
    title: '房间号',
    dataIndex: 'roomName',
    width: 80,
    align: 'center'
    // scopedSlots: { customRender: 'roomId' }
  },
  {
    title: '房型',
    dataIndex: 'layoutName',
    width: 80,
    align: 'center'
    // scopedSlots: { customRender: 'roomId' }
  },
  {
    title: '房价',
    dataIndex: 'marketPrice',
    width: 80,
    align: 'center'
    // scopedSlots: { customRender: 'roomId' }
  },
  {
    title: '客人',
    dataIndex: 'customerName',
    width: 80,
    align: 'center'
    // scopedSlots: { customRender: 'roomId' }
  },
  {
    title: '抵离时间',
    dataIndex: 'arrivalTime',
    width: 180,
    align: 'center',
    scopedSlots: { customRender: 'arrivalTime' }
  }
]

export default {
    name: 'ExchangeHousesForm',
    components: {},
    props: {
        // 表单禁用
        disabled: {
            type: Boolean,
            default: false,
            required: false
        }
    },
    data() {
        return {
            tableData: [],
            columns: columns,
            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,
            url: {
                add: '/pos/posTable/add',
                edit: '/pos/posTable/edit',
                queryById: '/pos/posTable/queryById'
            },
            payTypeList: [],
            payList: [],
            tableTypeList: [],
            regionList: [],
            PriceData: [],
            oldRoomList: [],
            dataList: [],
            selectData: [],
            newRoom: null,
            timeData: [],
            oldTimeData: [],
            roomScheme: 1,
            differPrice: 0 // 新旧房间总差价
        }
    },
    watch: {
        roomList(val) {
            // this.roomList.forEach(ele => {
            //     this.dataList.push(...ele.rooms)
            // })
        },
        newRoomPrice(value) {
            this.differPrice = value - this.oldTimeData.reduce((pre, cur) => pre + cur.price * 1, 0)
            this.$forceUpdate()
        }
    },
    computed: {
        formDisabled() {
            return this.disabled
        },
        newRoomPrice() {
          return this.timeData.reduce((pre, cur) => pre + cur.price * 1, 0)
        }
    },
    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
            }
        })
        // 获取支付方式
        getAction('/business/busRoomPayType/list', {
          pageSize: 99999,
          pageNo: 1
        }).then((res) => {
          console.log(this.model, '9999s')
          console.log(res.result.records, '9999s')
            if (res.success && res.result.records.length > 0) {
                this.payTypeList = res.result.records
                var vipIndex = this.payTypeList.findIndex((t) => t.name.includes('会员'))
                var danweiIndex = this.payTypeList.findIndex((t) => t.name.includes('单位'))
                if (vipIndex !== -1) {
                  console.log(this.model.livingData.livingOrder)
                  console.log(this.model.livingData.livingOrder.vipCustomerId)
                  this.$set(this.payTypeList[vipIndex], 'disable', this.model.livingData.livingOrder.vipCustomerId == null || this.model.livingData.livingOrder.vipCustomerId === '')
                }
                if (danweiIndex !== -1) {
                  this.$set(this.payTypeList[danweiIndex], 'disable', this.model.livingData.livingOrder.contractTeamId == null)
                }
            }
            this.plus()
        })
    },
    methods: {
      // 处理日期
        handleDateFromat(val) {
          let str  = val.substr(5, 5)
          console.log(str);
          return str
        },
        plus() {
          // var sum = this.payList.reduce(function (total, item) {
          //   return total + item.money
          // }, 0)
          // var money = this.realityAmount - sum
          // if (money < 0) {
          //   money = 0
          // }
          this.payList.push({
            money: 0,
            payType: this.payTypeList[0].id
          })
          this.$forceUpdate()
        },
        remove(index) {
          this.payList.splice(index, 1)
        },
        changeSelct() {
            if (this.selectData[0].id == this.model.id) {
                this.$message.warning('不能选择相同的房间')
                return
            }
            this.newRoom = this.selectData[0]
            let find = this.cesRoomLayoutList.find(e => e.value === this.newRoom.layoutId)
            if (find != null) {
              console.log(find, 'find')
              this.$set(this.newRoom, 'layoutName', find.label)
            }
            if (this.roomScheme === 2) {
              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.timeData.forEach(item => {
                item.price = e
            })
        },
        roomSchemeChange(e) {
          
          console.log(this.oldTimeData)
          if (this.roomScheme === 1) {
            this.timeData = JSON.parse(JSON.stringify(this.oldTimeData))
            this.$forceUpdate()
          } else if (this.roomScheme === 2) {
            this.timeData.forEach(ele => {
              ele.price = this.newRoom.marketPrice
            })
          }
        },
        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 !== '7' ? room.roomStatus.toString() : room.lastRoomStatus.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))
                  console.log(this.roomList)
                    this.checkChange()
                }
            })
        },
        add() {
            this.edit(this.modelDefault)
        },
        edit(record) {
          
          console.log(record)
            this.tableData = [{
              roomName: record.roomInfo.name,
              marketPrice: record.layout.marketPrice,
              layoutName: record.layout.name,
              customerName: record.livingData.livingCustomers.customerName,
              arrivalTime: record.livingData.livingOrder.arrivalTime,
              dueOutTime: record.livingData.livingOrder.dueOutTime
            }]
            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: this.model.livingData.price[i].price
                }
            }
            let nowDate = new moment().format('yyyy-MM-DD')
             arr = arr.filter(e => e.day > nowDate)
            this.timeData = arr
            // 用于改回原房价时
            this.oldTimeData = JSON.parse(JSON.stringify(arr))
            console.log('arr', 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
                        }
                    })
                    let feeList = []
                    if (this.differPrice > 0) {
                        feeList = this.payList.map((item) => {
                            return {
                              livingOrderId: this.model.roomInfo.livingOrderId,
                              roomId: this.newRoom.id,
                              hotelId: this.model.hotelId,
                              feeType: 2,
                              subjectType: 2,
                              money: item.money.toFixed(2),
                              preferentialStatus: 1,
                              payType: item.payType,
                              remark: '换房差价',
                              vipCardId: this.model.livingData.livingOrder.vipCustomerId,
                              agreementUnitId: this.model.livingData.livingOrder.contractTeamId
                            }
                        })
                    }
                    let param = { layoutDayPriceList: prices, orderFeeList: feeList, roomId: this.newRoom.id, id: this.model.roomInfo.livingOrderId }
                    // return
                    httpAction('/business/busRoomBookingOrders/change-living-room', param, 'post')
                        .then((res) => {
                            if (res.success) {
                                that.$message.success(res.message)
                                let obj = {
                                  ...this.newRoom,
                                  layoutName: this.model.layout.name,
                                  customerName: this.model.livingData.livingCustomers.customerName,
                                  phone: this.model.livingData.livingCustomers.phone
                                }
                                that.$emit('ok', [obj])
                            } 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;
}
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  /* top: 4px; */
  margin-left: 5px;
  font-size: 18px;
  color: #1890ff;
  transition: all 0.3s;
}
</style>
