<style lang="scss" scoped>
.select-day {
  background: var(--q-color-primary);
  color: #fff !important;
  border-radius: 8px;
}
.date-table {
  width: 100%;
  padding: 5px;
  border-collapse: separate;
  table-layout: fixed;
}
.cell-day {
  padding: 10px 0 20px;
  text-align: center;
  color: #666;
  font-weight: 700;
}
.cell-date.selectable {
  cursor: pointer;
}
.cell-date {
  position: relative;
  padding: 8px 4px;
  border-radius: 6px;
  text-align: center;
  vertical-align: baseline;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
// .cell-date .date-num {
//   font-size: 1.6rem;
//   font-weight: 700;
// }
// .disabled {
//   color: #666;
// }
// .option-booking .cell-date .price {
//   min-height: 20px;
//   color: #666;
//   font-size: 1.2rem;
// }
// .cell-date.selected.selected-end {
//   border-top-right-radius: 6px;
//   border-bottom-right-radius: 6px;
//   position: relative;
// }
// .cell-date.selected.selected-start {
//   border-top-left-radius: 6px;
//   border-bottom-left-radius: 6px;
// }
// .cell-date.selected.selected-end,
// .cell-date.selected.selected-start {
//   color: #fff;
//   background-color: #26bdc9;
// }
</style>
<template>
    <div>
          <div class="flex justify-between">
            <div class="f20 flex item-center">
              {{detail.Name}}
              <!-- <span class="cancel">3天前可免费取消</span> -->
            </div>
            <div>
              <div class="f20 text-right">
                CNY {{ moneyFormat(minPrice, 0)
                }}<span class="f14">起</span>
              </div>
              <div>最早可预订日<span class="q-ml-sm">{{startDate}}</span></div>
            </div>
          </div>
          <!-- <div class="flex bold mr about">
            关于此方案
            <div class="flex normal ml">
              <div class="ml">3天前可免费取消</div>
            </div>
          </div> -->
          <div>
            <div class="mt mb bold f18">选择日期、选项</div>
            <div class="flex">
              <div style="width: 50%">
                <!-- <div>请选择出发日期</div> -->
                <div>
                  <div class="flex justify-between f20 bold padding">
                    <span>{{ currentYM.str }}</span>
                    <div>
                      <q-btn
            color="primary"
            round
            icon="iconfont iconpreviewleft"
            flat
            @click="handleMinus"
            class="q-mr-sm"
            :disable="isCurrent"
          />
          <q-btn
            color="primary"
            round
            icon="iconfont iconpreviewright"
            flat
            @click="handlePlus"
            :disable="isLast"
          />
                    </div>
                  </div>
                  <table class="date-table">
                    <thead>
                      <tr class="row-day">
                        <th v-for="item in ['日','一','二','三','四','五','六']" :key="item" class="col text-weight-bold text-center">{{item}}</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr
                        class="row-date"
                        v-for="(item, index) in daysList"
                        :key="index"
                      >
                        <td
                          class="text-center text-weight-bold cell-date selectable"
                          v-for="(el, index) in item"
                          :key="index"
                        >
                          <div style="padding: 8px 4px;" v-if="el && el.disabled">
                            <div v-if="el" class="text-grey-6 disabled">
                              {{ el.day }}
                            </div>
                          </div>
                          <div style="padding: 8px 4px;" class=" text-grey-9" v-else-if="el" @click="handleSelectDay(el)" :class="{'select-day': selectDateStr === el.DateStr}">
                            <div>{{ el.day }}</div>
                            <div class="q-mt-sm f12">
                              {{ el.price }} 起
                            </div>
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <div style="width: 40%; margin-left: 10%">
                <div class="mt mb">房间选择</div>
                <div>注意：以下计费与报价均是按照人数进行计费</div>
                <!-- <div class="mt mb">选择辆数</div> -->
                <div class="mt pt" v-for="item in roomList" :key="item.id">
                  <div class="flex justify-between bold f18 mt mb items-center">
                  <span>{{item.RoomName}}</span>
                  <div class="flex items-center">
                    <span>CNY{{item.UPriceFormat}}</span>
                    <number-input-step :defaultValue="item.value" @input="handleValueChange(item, $event)"></number-input-step>
                    <span class="ml f14 normal">预计<span class="primary">{{item.Number}}</span>间房</span>
                  </div>
                  </div>
                  <div v-if="item.Tips" class="f12 mb grey">{{item.Tips}}</div>
                </div>
                <q-separator />
                <div class="flex justify-between mt mb">
                  <span>总金额</span>
                  <span class="f20">CNY {{allPrice}}</span>
                </div>
                <div>
                <div>仅剩 {{hotelInfor.RemainingInventory}} 间已选 {{sumPeople}} 人 {{total}} 间</div>
                <div v-if="total > hotelInfor.RemainingInventory">超出现有的库存预定，我们会即时与酒店协商，请保证收讯通畅</div>
                </div>
                <div class="flex flex-end">
                  <!-- <q-btn
          color="primary"
          unelevated class="mr" label="加入购物车"></q-btn> -->
                  <q-btn 
          color="primary"
          unelevated label="立即订购"></q-btn>
                </div>
              </div>
            </div>
            <div></div>
          </div>
          </div>
</template>
<script>
import numberInputStep from 'src/components/numberInputStep.vue';
import * as dayjs from "dayjs";
export default {
    props: {
        detail: {
            type: Object,
            default: () => ({})
        }
    },
    components: {numberInputStep},
    data() {
        return {
          minPrice: 0,
          startDate: '',
          total: 0, // 总的房间数
          sumPeople: 0, //总的人
          allPrice: 0, // 总价
          allNumber: 0, // 剩余房间数
          hotelInfor: {},
          selectDateStr: '',
      daysList: [],
      isLast: false,
      isCurrent: false,
          roomList: [],
      currentYM: { year: 2023, month: 2, str: "2023-02" }, // 当前年月
      }
    },
    mounted() {
    this.getPriceData();
    },
    methods: {
      handleSelectDay(day) {
        this.selectDateStr = day.DateStr
        this.hotelInfor = day
        console.log('DateStr handleSelectDay', day)
        this.setList()
      },
      handleValueChange(item, event) {
        console.log('handleValueChange', item, event)
        item.PeopleNumber = event
        this.calculateNum()
      },
    handleMinus() {
      if (this.isCurrent) return;
      const { str, year, month } = this.currentYM;
      if (month === 1) {
        this.currentYM = {
          year: year - 1,
          month: 12,
          str: `${year - 1}-12`,
        };
      } else {
        this.currentYM = {
          year: year,
          month: month - 1,
          str: `${year}-${month - 1 > 10 ? month - 1 : "0" + (month - 1)}`,
        };
      }
      this.getPriceData();
    },
    handlePlus() {
      if (this.isLast) return;
      const { str, year, month } = this.currentYM;
      if (month === 12) {
        this.currentYM = {
          year: year + 1,
          month: 1,
          str: `${year + 1}-01`,
        };
      } else {
        this.currentYM = {
          year: year,
          month: month + 1,
          str: `${year}-${month + 1 >= 10 ? month + 1 : "0" + (month + 1)}`,
        };
      }
      this.getPriceData();
    },
    getPriceData() {
      this.$q.loading.show();
      this.apipost(
        "b2c_get_GetHotelMonthPrice",
        {
          HotelId: decodeURIComponent(this.$route.params.id),
          Month: this.currentYM.str,
        },
        (r) => {
          let list = [[]];
          let y = 0; // 元素纵向下标
          let day = 0;
          if (r.data.resultCode == 1) {
            let week = dayjs(this.currentYM.str + "-01").day();
            console.log("week", week);
            list[0].length = week;
            const isCurrent =
              this.currentYM.year === dayjs().year() &&
              this.currentYM.month === dayjs().month() + 1;
            this.isCurrent = isCurrent;
            this.isLast =
              this.currentYM.year === dayjs().year() + 1 &&
              this.currentYM.month === dayjs().month() + 1;
            let days = dayjs(r.data.data[0].Date).date();
            // 如果是当前月
            if (isCurrent) {
              day = days;
              for (let i = 1; i <= days; i++) {
                list[y].push({
                  day: i,
                  disabled: true,
                });
                week++;
                if (week === 7) {
                  week = 0;
                  y++;
                  list[y] = [];
                }
              }
            }
            r.data.data.forEach((item, index) => {
              if (!isCurrent || index >= days) {
                const {min, disabled} = this.getMinPrice(item)
                list[y].push({
                  ...item,
                  day: ++day,
                  price: min,
                  disabled: disabled
                });
                week++;
                if (week === 7) {
                  week = 0;
                  y++;
                  list[y] = [];
                }
              }
            });
            this.daysList = list;
            console.log("list", list);
          } else {
            this.$q.notify({
              type: "negative",
              message: r.data.message,
              position: "top",
              timeout: 2000, // 以毫秒为单位; 0意味着没有超时
            });
          }
          this.$q.loading.hide();
        },
        null
      );
    },
    getMinPrice(day) {
      let roomTyps = ['CostPrice', 'BidroomPrice', 'SingleroomPrice', 'AddBedPrice', 'GuideRoomPrice']
      let arr = []
      // console.log('day min', day.PriceList[0][roomTyps])
      roomTyps.forEach(item => {
        if(day.PriceList[0][item]) {
        arr.push(day.PriceList[0][item])
      }
      })
      if(!this.startDate && arr.length) {
        this.startDate = day.DateStr
        this.minPrice = Math.min(...arr)
        this.$emit('change', this.minPrice)
      }
      return {
        min: Math.min(...arr),
        disabled: !arr.length
      }
    },
        // 组装可选房间
        setList() {
          let detailList = []
            let roomTyps = ['CostPrice', 'BidroomPrice', 'SingleroomPrice', 'AddBedPrice', 'GuideRoomPrice']
            let roomLangs = ['标准间', '大床房', '自然单间', '三人间', '司机间']
            let tips = ['', '本房型不同的酒店入住人数限制不同，系统默认该房型只能入住一人', '', '', '']
            let limitGuestNum = [2, 1, 1, 3, 1]
            let tempPrice = this.hotelInfor.PriceList[0]
            let hotel = this.hotelInfor
            roomTyps.forEach((x, i) => {
                if (tempPrice[x] > 0) {
                    let dataMsg = {
                    HotelId: this.detail.HotelId,
                    Date: hotel.DateStr,
                    RoomType: i + 1,
                    RoomName: roomLangs[i],
                    Unit_Price: tempPrice[x],
                    UPriceFormat: this.moneyFormat(tempPrice[x]),
                    LimitGuestNum: limitGuestNum[i],
                    Tips: tips[i],
                    Number: 0,
                    PeopleNumber: 0,
                    Destription: '',
                    TaxesPrice: tempPrice.TaxesPrice,
                    PriceInTangTax: tempPrice.PriceInTangTax,
                    HotelName: this.detail.HotelName
                    }
                    detailList.push(dataMsg)
                }
            })
            console.log('detailList', detailList)
            this.roomList = detailList
        },
        // 计算房间数量
        calculateNum() {
            this.total = 0
            this.sumPeople = 0
            this.allPrice = 0
            this.roomList.forEach(item => {
                item.Number = Math.ceil(parseFloat(item.PeopleNumber) / parseFloat(item.LimitGuestNum))
                this.total += item.Number
                this.sumPeople += parseInt(item.PeopleNumber)
                this.allPrice += item.PeopleNumber * item.Unit_Price
            })
        },
    }
}
</script>