<template>
  <a-spin :spinning="confirmLoading">
    <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="arrivalTime2"
            >
              <j-date
                placeholder="预抵时间"
                v-model="model.arrivalTime2"
                style="width: 180px"
                :allowClear="false"
                :disabled-date="disabledDate"
                @change="arrivalTimeChange"
              />
              <a-time-picker
                style="width: 80px; margin-left: 2px"
                v-model="model.arrivalTimeSpan"
                format="HH:mm"
                :allowClear="false"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="预离时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="dueOutTime2"
            >
              <j-date
                placeholder="预离时间"
                v-model="model.dueOutTime2"
                style="width: 180px"
                :allowClear="false"
                :disabled-date="disabledDate"
                @change="arrivalTimeChange2"
              />
              <a-time-picker
                style="width: 80px; margin-left: 2px"
                v-model="model.dueOutTimeSpan"
                format="HH:mm"
                :allowClear="false"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="天数"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="dayCount"
            >
              <a-input-number
                v-model="model.dayCount"
                placeholder="天数"
                :min="1"
                @change="dayCountChange"
              ></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <h4 style="color: rgba(255, 141, 26, 1); font-weight: 600">
              选择房间
            </h4>
            <a-divider />
            <p>
              <span>占房天数：{{ model.dayCount }}晚</span>
              <span style="padding-left: 10px">总价：{{ amount }}</span>
            </p>
            <a-table
              :columns="columns"
              :data-source="canUserRooms"
              :pagination="false"
              :rowKey="rowKey"
            >
              <div
                slot="expandedRowRender"
                slot-scope="record, index, indent, expanded"
                style="margin: 0"
              >
                <p>
                  已排房：
                  <template v-for="(building, bIndex) in record.buildingRooms">
                    <a-tag
                      color="blue"
                      closable
                      :visible="visible"
                      @close.stop="tagClose2(rindex, bIndex, index)"
                      v-for="(item, rindex) in building.floorRooms"
                      :key="rindex"
                      v-if="item.check && item.check == 1"
                      >{{ item.name }}</a-tag
                    >
                  </template>
                </p>
                <p>
                  未排房：{{
                    record.layout.presetNum - (record.rooms || []).length
                  }}间
                </p>
              </div>
              <template slot="favPrice" slot-scope="text, record, index">
                <!-- <editable-cell
                    :text="record.layout.favPrice"
                    @change="onCellChange('favPrice', index, $event)"
                  /> -->
                {{ record.layout.favPrice }}
              </template>
              <template slot="presetNum" slot-scope="text, record, index">
                <div>
                  <a-input-number
                    v-model="record.layout.presetNum"
                    :min="(record.rooms || []).length"
                    :max="record.layout.oldTags"
                    @change="presetNumChange($event, record)"
                  />
                </div>
              </template>
              <span slot="action" slot-scope="text, record, index">
                <a
                  :disabled="record.layout.presetNum <= 0"
                  @click="pulsRoom(index)"
                  >排房</a
                >
              </span>
            </a-table>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <select-room-form-modal
      ref="modalSelectRoomForm"
      @ok="modalFormOk"
    ></select-room-form-modal>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from "@/api/manage";
import { validateDuplicateValue } from "@/utils/util";
import SelectRoomFormModal from "./SelectRoomFormModal.vue";
import moment from "moment";
export default {
  name: "SelectRoomForm",
  components: { SelectRoomFormModal },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    orderInfo: {
      type: Object,
      default: {},
    },
    batchRoomsTypeList: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      visible: true,
      columns: [
        // {
        //     title: "",
        //     dataIndex: "key",
        //     width: 20,
        //   },
        {
          title: "房型",
          dataIndex: "name",
          width: 150,
          customRender: function (text, record) {
            return record.layout.name;
          },
        },
        {
          title: "门市价",
          dataIndex: "marketPrice",
          width: 100,
          customRender: function (text, record) {
            return record.layout.marketPrice;
          },
        },
        {
          title: "优惠价",
          dataIndex: "favPrice",
          width: 120,
          scopedSlots: { customRender: "favPrice" },
        },
        {
          title: "可订数/可超数",
          dataIndex: "canUseCount",
          width: 170,
          customRender: function (text, record) {
            return record.layout.canUseCount + "/0";
          },
        },
        {
          title: "预定间数",
          dataIndex: "presetNum",
          width: 100,
          scopedSlots: { customRender: "presetNum" },
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          fixed: "right",
          width: 70,
          scopedSlots: { customRender: "action" },
        },
      ],
      model: {
        arrivalTime2: this.orderInfo.arrivalTime2,
        dueOutTime2: this.orderInfo.dueOutTime2,
        arrivalTimeSpan: this.orderInfo.arrivalTimeSpan,
        dueOutTimeSpan: this.orderInfo.dueOutTimeSpan,
        dayCount: this.orderInfo.dayCount,
        bookingType: this.orderInfo.bookingType,
        hourRoomId: this.orderInfo.hourRoomId,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        dateRange: [{ required: true, message: "请选择维修时间!" }],
        remark: [{ required: true, message: "请输入维修原因!" }],
      },
      url: {
        add: "/business/busMeetingRoom/add",
        edit: "/business/busMeetingRoom/edit",
        queryById: "/business/busMeetingRoom/queryById",
      },
      layoutName: "",
      presetNum: 0,
      canUserRooms: [],
    };
  },
  computed: {
    formDisabled() {
      return this.disabled;
    },
    amount() {
      var sum = 0;
      this.canUserRooms.forEach((t) => {
        sum += t.layout.favPrice * t.layout.presetNum * this.model.dayCount;
      });
      return sum.toFixed(2);
    },
  },
  created() {
    var _info = JSON.parse(localStorage.getItem("storeInfo"));
    if (_info) {
      this.model.hotelId = _info.id;
    }
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    this.loadRooms();
  },
  methods: {
    tagClose2(rindex, bindex, index) {
      this.canUserRooms[index].rooms.splice(rindex, 1);

      this.$set(
        this.canUserRooms[index].buildingRooms[bindex].floorRooms[rindex],
        "check",
        0
      );
      console.log(this.canUserRooms);
    },
    modalFormOk(e) {
      this.$set(this.canUserRooms[this.selectIndex], "rooms", e);
      console.log(this.canUserRooms[this.selectIndex]);
    },
    pulsRoom(index) {
      this.selectIndex = index;
      this.$refs.modalSelectRoomForm.add(this.canUserRooms[this.selectIndex]);
      this.$refs.modalSelectRoomForm.title = "排房";
      this.$refs.modalSelectRoomForm.disableSubmit = false;
    },
    rowKey(record) {
      return record.layout.id;
    },
    dayCountChange(e) {
      this.model.dueOutTime2 = moment(this.model.arrivalTime2)
        .add(e, "days")
        .format("YYYY-MM-DD");
      this.loadRooms();
    },
    disabledDate(current) {
      return current && current < moment().add(-1, "days").endOf("day");
    },
    arrivalTimeChange(e) {
      this.model.dueOutTime2 = moment(this.model.arrivalTime2)
        .add(this.model.dayCount, "days")
        .format("YYYY-MM-DD");
      this.model.dayCount = Math.abs(
        parseInt(
          (new Date(this.model.arrivalTime2).getTime() -
            new Date(this.model.dueOutTime2).getTime()) /
            (1000 * 60 * 60 * 24)
        )
      );
      this.loadRooms();
    },
    arrivalTimeChange2(e) {
      this.model.dayCount = Math.abs(
        parseInt(
          (new Date(this.model.arrivalTime2).getTime() -
            new Date(this.model.dueOutTime2).getTime()) /
            (1000 * 60 * 60 * 24)
        )
      );
      this.loadRooms();
    },
    isDateIntersection(start1, end1, start2, end2) {
      var startdate1 = new Date(start1.replace("-", "/").replace("-", "/"));
      var enddate1 = new Date(end1.replace("-", "/").replace("-", "/"));

      var startdate2 = new Date(start2.replace("-", "/").replace("-", "/"));
      var enddate2 = new Date(end2.replace("-", "/").replace("-", "/"));

      if (startdate1 >= startdate2 && startdate1 <= enddate2) {
        return true;
      }

      if (enddate1 >= startdate2 && enddate1 <= enddate2) {
        return true;
      }

      if (startdate1 <= startdate2 && enddate1 >= enddate2) {
        return true;
      }
      return false;
    },
    presetNumChange(e, record) {
      console.log(e);
      record.layout.canUseCount = record.layout.oldTags - e;
    },
    loadRooms() {
      var startOf =
        this.model.arrivalTime2 +
        " " +
        moment(this.model.arrivalTimeSpan).format("HH:mm");
      var endOf =
        this.model.dueOutTime2 +
        " " +
        moment(this.model.dueOutTimeSpan).format("HH:mm");

      getAction("/rooms/cesRooms/can-user-rooms", {
        startOf: startOf,
        endOf: endOf,
        bookingType: this.model.bookingType,
        hourRoomRuleId: this.model.hourRoomId,
      }).then((res) => {
        if (res.success) {
          if (this.batchRoomsTypeList.length > 0) {
            this.batchRoomsTypeList.forEach((bt) => {
              var dateArr = bt.key.split(",");
              var startOf2 = dateArr[0];
              var endOf2 = dateArr[1];
              //判断日期段是否有交集，有交集的情况下可订数量动态计算,动态排除已选排房
              var isDateSection = this.isDateIntersection(
                startOf,
                endOf,
                startOf2,
                endOf2
              );
              console.log("isDateSection", isDateSection);
              if (isDateSection) {
                res.result.forEach((t) => {
                  this.$set(t, "rooms", []);
                  var find = bt.data.find(
                    (ibt) => ibt.layout.id === t.layout.id
                  );

                  t.layout = Object.assign({}, t.layout, {
                    presetNum: find ? find.layout.presetNum : 0,
                    canUseCount:
                      t.layout.canUseCount - (find ? find.layout.presetNum : 0),
                    // oldTags:
                    //   t.layout.canUseCount - (find ? find.layout.presetNum : 0),
                    oldTags: t.layout.canUseCount,
                  });
                  t.buildingRooms.forEach((b) => {
                    if (find && find.buildingRooms) {
                      find.buildingRooms.forEach((fbr) => {
                        fbr.floorRooms.forEach((fbrfloorRoom) => {
                          if (fbrfloorRoom.check && fbrfloorRoom.check == 1) {
                            var findIndex = b.floorRooms.findIndex(
                              (floorRoom) => floorRoom.id === fbrfloorRoom.id
                            );
                            if (findIndex >= 0) {
                              // b.floorRooms.splice(findIndex, 1);
                              this.$set(b.floorRooms[findIndex], "check", 1);
                              t.rooms.push(b)
                            }
                          }
                        });
                      });
                    }
                    b.floorRooms.forEach((f) => {
                      if (!f.check) {
                        this.$set(f, "check", 0);
                      }
                    });
                  });
                });
              } else {
                res.result.forEach((t) => {
                  t.layout = Object.assign({}, t.layout, {
                    presetNum: 0,
                    oldTags: t.layout.canUseCount,
                  });
                  t.buildingRooms.forEach((b) => {
                    b.floorRooms.forEach((f) => {
                      this.$set(f, "check", 0);
                    });
                  });
                });
              }
            });
            this.canUserRooms = res.result;
          } else {
            res.result.forEach((t) => {
              t.layout = Object.assign({}, t.layout, {
                presetNum: 0,
                oldTags: t.layout.canUseCount,
              });
              t.buildingRooms.forEach((b) => {
                b.floorRooms.forEach((f) => {
                  this.$set(f, "check", 0);
                });
              });
            });
            this.canUserRooms = res.result;
          }
        }
      });
    },
    moment,
    add(row) {
      // console.log("buildingRooms", row);
      // this.layoutName = row.layout.name;
      // this.presetNum = row.layout.presetNum;
      // this.roomList = row.buildingRooms;
      this.edit(this.modelDefault);
    },
    edit(record) {
      this.model = Object.assign({}, record);
      this.visible = true;
    },
    submitForm() {
      const that = this;
      var data = that.canUserRooms.filter((it) => it.layout.presetNum > 0);
      if (data.length <= 0) {
        that.$message.warning("请先添加房间");
        return;
      }
      that.$emit("ok", {
        key:
          this.model.arrivalTime2 +
          " " +
          moment(this.model.arrivalTimeSpan).format("HH:mm") +
          "," +
          this.model.dueOutTime2 +
          " " +
          moment(this.model.dueOutTimeSpan).format("HH:mm"),
        arrivalTime2: this.model.arrivalTime2,
        dueOutTime2: this.model.dueOutTime2,
        arrivalTimeSpan: this.model.arrivalTimeSpan,
        dueOutTimeSpan: this.model.dueOutTimeSpan,
        dayCount: this.model.dayCount,
        amount: this.amount,
        data: data,
      });
    },
  },
};
</script>
<style scoped>
#components-grid-demo-playground [class~="ant-col"] {
  background: transparent;
  border: 0;
}
#components-grid-demo-playground [class~="ant-col"] > div {
  /* background: #00a0e9; */
  height: 28px;
  line-height: 28px;
  font-size: 13px;
  text-align: center;
  cursor: pointer;
  border-radius: 5px;
}
#components-grid-demo-playground .check {
  border: 1px solid #00a0e9;
}
#components-grid-demo-playground .kz {
  background: rgba(166, 166, 166, 1);
}
#components-grid-demo-playground pre {
  background: #f9f9f9;
  border-radius: 6px;
  font-size: 13px;
  padding: 8px 16px;
}
</style>