<template>
  <div class="rounded-borders bg-white row items-center q-pb-md">
    <q-field
      stack-label
      :label="
        $t('v101.scatteredDetails.ruzhuTime') +
        '/' +
        $t('v101.scatteredDetails.tuifangTime')
      "
      standout
      class="col-2"
      style="min-width: 200px"
      dense
    >
      <div class="self-center full-width no-outline" tabindex="0">
        {{ dateRangeFormat }}
      </div>
      <q-popup-proxy :offset="[0, 10]" ref="qDateProxy">
        <q-date
          v-model="dateRange"
          :options="optionsFn"
          range
          mask="YYYY/MM/DD"
          landscape
          @range-end="dateRangeHandler"
        ></q-date>
      </q-popup-proxy>
    </q-field>

    <div class="row" :class="{ 'q-mt-sm': $q.platform.is.mobile }">
      <q-select
        :class="{ 'q-ml-lg': $q.platform.is.desktop }"
        style="min-width: 90px; z-index: 99999"
        unelevated
        v-model="room"
        dense
        :options="theRooms"
        emit-value
        option-label="name"
        option-value="id"
        map-options
        :label="$t('v101.scattered.kefang')"
        standout
        @update:model-value="getRoomList"
      >
      </q-select>
      <q-btn
        unelevated
        class="bg-white hover q-px-xs q-py-sm q-ml-xs text-grey-6"
        icon="person"
      >
        <div class="text-dark q-ml-xs">
          {{ auditNum }}{{ $t("v101.scattered.chengren") }}
          <span class="q-px-sm">.</span>
          <template v-if="childNum > 0">{{ childNum }}</template>
          {{ $t("v101.scattered.ertong") }}
        </div>
        <q-popup-proxy
          class="no-shadow absolute"
          style="z-index: 0; box-shadow: 0 0 50px #ddd !important"
          :offset="[0, 20]"
          :model-value="isShowPop"
        >
          <q-card class="row wrap q-pa-md rounded-borders" style="max-width: 697px">
            <div
              class="q-mr-md"
              v-for="(item, index) in search.searchroomGroup"
              :key="index"
              style="min-width: 150px"
            >
              <div class="q-mb-md text-subtitle2">
                {{ $t("v101.scattered.kefang") }}{{ index + 1 }}
              </div>
              <div class="q-my-md">
                <q-select
                  v-model="item.numberOfAdults"
                  dense
                  :options="adultList"
                  emit-value
                  map-options
                  :label="$t('v101.scattered.chengren')"
                  standout
                  @update:model-value="setPeopleNum"
                />
              </div>
              <div class="q-my-md">
                <q-select
                  v-model="item.numberOfChildren"
                  dense
                  :options="childrenList"
                  emit-value
                  map-options
                  :label="$t('v101.scattered.ertong')"
                  standout
                  @update:model-value="setPeopleNum"
                />
              </div>
              <div class="q-my-md">
                <q-select
                  v-model="item.ChildAgeDetails"
                  dense
                  :options="childrenAgeList"
                  emit-value
                  map-options
                  :label="$t('v101.scattered.ertongage')"
                  standout
                />
              </div>
            </div>
          </q-card>
        </q-popup-proxy>
      </q-btn>
    </div>
    <div
      class="q-pl-lg text-red-6 row items-center"
      style="position: relative"
      v-if="$q.platform.is.desktop"
    >
      <q-icon
        class="absolute"
        style="left: 85px; top: 0"
        name="information"
        size="18px"
      ></q-icon>
      <span class="q-pl-lg">{{ $t("v101.scatteredDetails.prompt") }}</span>
    </div>
    <div class="col"></div>
    <q-btn
      color="primary"
      unelevated
      :label="$t('query')"
      :loading="loading"
      @click="initHotel"
    />
  </div>
  <div
    class="q-pl-lg q-pb-lg text-red-6 row items-center"
    style="position: relative"
    v-if="$q.platform.is.mobile"
  >
    <q-icon
      class="absolute"
      style="left: 65px; top: 0"
      name="information"
      size="18px"
    ></q-icon>
    <span class="q-pl-sm">{{ $t("v101.scatteredDetails.prompt") }}</span>
  </div>
  <div class="bg-light-blue-1 q-pa-md fz14 rounded-borders row items-center">
    <div class="text-weight-bold">{{ $t("v101.scatteredDetails.fuheTJroom") }}</div>
  </div>
  <div class="q-my-md">
    <template v-if="SimilarList && SimilarList.length > 0">
      <q-card
        class="row q-mb-md"
        v-for="(item, index) in SimilarList"
        :key="index"
        v-loading="loading"
      >
        <div
          class="col q-pa-sm q-pr-lg"
          :class="{
            'col-3 row no-wrap justify-between': $q.platform.is.desktop,
            'col-4 column': $q.platform.is.mobile,
          }"
          :style="{ 'border-right': $q.platform.is.desktop ? '1px solid #eeeeee' : '' }"
        >
          <div
            v-if="$q.platform.is.desktop"
            :class="{ 'col-6': $q.platform.is.desktop, 'col-12': $q.platform.is.mobile }"
            :style="{ height: $q.platform.is.desktop ? '100px' : '50px' }"
          >
            <q-img
              src="/src/assets/images/home.png"
              :style="{ height: $q.platform.is.desktop ? '100%' : '50px' }"
              spinner-color="drk"
              spinner-size="20px"
              mode="cover"
            />
          </div>
          <div class="col column" :class="{ 'q-pl-xs': $q.platform.is.desktop }">
            <div class="text-right text-green q-pt-md">
              {{ getRoomType(item.BedType) }}
            </div>
          </div>
        </div>
        <div
          class="col"
          :style="{ 'border-left': $q.platform.is.mobile ? '1px solid #eeeeee' : '' }"
        >
          <div
            class="relative-position"
            v-if="item.RatePlanList && item.RatePlanList.length > 0"
            v-for="(subItem, subIndex) in item.RatePlanList"
            :key="subIndex"
            v-show="subIndex < (isShow === index ? item.RatePlanList.length : 3)"
          >
            <q-separator v-if="subIndex != 0" />
            <div class="col q-ml-lg q-pt-lg q-pb-md q-pr-md">
              <div
                class="col q-pt-sm"
                :class="{
                  'row items-center no-wrap': $q.platform.is.desktop,
                  common: $q.platform.is.mobile,
                }"
              >
                <div
                  class="absolute text-white q-px-lg"
                  style="left: 0%; top: 0; border-bottom-right-radius: 10px"
                  :class="subItem.BreakfastType == 2 ? 'HD_Black' : 'HD_Green'"
                >
                  {{ subItem.BreakfastType == 1 ? "不含早" : "含早" }}
                </div>

                <div
                  class="col-3"
                  :class="{ 'q-pl-lg': $q.platform.is.desktop }"
                  v-if="$q.platform.is.desktop"
                >
                  {{ subItem.RatePlanName }}
                </div>

                <div
                  class="col-2 text-grey-6"
                  v-if="subItem.PriceList && subItem.PriceList != null"
                >
                  <q-card
                    class="row q-mb-md"
                    style="box-shadow: none"
                    v-for="(itemPrice, indexPrice) in subItem.PriceList"
                    :key="indexPrice"
                    v-loading="loading"
                  >
                    <div class="text-right text-green q-pt-md">
                      {{ getformatDateStr(itemPrice.StayDate) }} 报价:{{
                        itemPrice.Price
                      }}
                    </div>
                  </q-card>
                </div>
                <div
                  v-if="
                    subItem.RatePlanCancellationPolicyList &&
                    subItem.RatePlanCancellationPolicyList != null
                  "
                >
                  <q-card
                    class="row q-mb-md"
                    style="box-shadow: none"
                    v-for="(
                      itemCancella, index1
                    ) in subItem.RatePlanCancellationPolicyList"
                    :key="index1"
                    v-loading="loading"
                  >
                    <div class="column q-pl-md q-pr-md">
                      <span class="text-right text-grey-6 q-pt-md"
                        >{{ getformatDateStr(itemCancella.FromDate) }}起取消({{
                          subItem.Currency
                        }}):-{{ itemCancella.Amount }}</span
                      >
                      <span></span>
                    </div>
                  </q-card>
                </div>
                <div
                  class="row no-wrap justify-end items-center"
                  :class="{ 'q-pl-lg': $q.platform.is.desktop }"
                >
                  <div class="row no-wrap items-center q-pr-lg">
                    <span class="text-grey-6">{{ subItem.Currency }}</span>
                    <span class="fz20 text-red q-px-sm">{{
                      getPrice(subItem.TotalPrice)
                    }}</span>
                  </div>
                  <div class="q-pt-xs" style="position: absolute; right: 3%">
                    <q-btn
                      class="bg-green-6 hover q-px-md q-py-xs q-ml-xs text-white"
                      @click="goUrl('/scattered/didaHotelSure', subItem)"
                      :label="$t('v101.scatteredDetails.yuyue')"
                    />
                  </div>
                </div>
              </div>
              <div class="q-pt-sm">
                <span class="text-green fz12 q-px-sm" style="border: 1px solid green"
                  >库存：{{ subItem.InventoryCount }}</span
                >
              </div>
            </div>
          </div>
          <div
            class="order-show"
            @click="showMore(index)"
            v-if="SimilarList[index].RatePlanList.length > 3"
          >
            <span class="oder-show-content icon-gengduo">{{
              isShow === index ? "点击收起" : "点击显示更多"
            }}</span>
          </div>
        </div>
      </q-card>
    </template>
    <div v-else class="col q-pa-lg text-center">
      {{ $t("noneData") }}
    </div>
  </div>
</template>

<script lang="ts">
import { useRouter } from "vue-router";
import svgIcon from "../../global/svg-icon.vue";
import HotelService from "../../../api/scattered";
import { DirtionmaryHelper } from "../../../config/dictionary";
import message from "../../../utils/message";
import { useI18n } from "vue-i18n";
import DidaService from "../../../api/didahotel";
import { HotelArea, useHotel } from "../../../utils/hotelRate";
import {
  computed,
  inject,
  provide,
  reactive,
  ref,
  toRefs,
  defineComponent,
  onMounted,
  watch,
} from "vue";
import { ApiResult } from "../../../@types/enumHelper";
import { date } from "quasar";
import { useQuasar } from "quasar";
import useScrollModule from "../../../module/scrollbar/scrollModule";
import { moneyFormat } from "../../../utils/tools";
export default defineComponent({
  components: { svgIcon },
  props: [""],
  setup(props, context) {
    const $router = useRouter();
    const $q = useQuasar();
    const qDateProxy = ref(null) as any;
    const qNameProxy = ref(null) as any;
    const { locale, t } = useI18n();
    const data = reactive({
      isShow: "",
      scrollStyle: {} as any,
      Areas: [] as Array<HotelArea>, //区域
      cascader: {
        addressValue: null,
      } as any,
      dateRange: {} as any, //当前日期
      dateRangeFormat: "", //可选日期
      loading: false,
      canHide: false, //更多筛选
      theRooms: [] as Array<Number>, //客房下拉
      room: 1, //客房数
      auditNum: 1,
      childNum: null as any,
      adultList: [] as Array<Number>, //成人下拉
      childrenList: [] as Array<Number>, //儿童下拉
      childrenAgeList: [] as Array<Number>, //儿童年龄下拉
      isShowPop: false, //房间
      SimilarList: [] as Array<any>,
      RoomTypeList: [] as Array<HotelArea>, //房间等级
      HotelRoomTypes: [] as Array<HotelArea>, //散客房间类型
      ScatMeaList: [] as Array<HotelArea>, //散客房间餐型
    });
    for (let i = 1; i < 11; i++) {
      data.theRooms.push(i);
    }
    for (let i = 1; i < 10; i++) {
      data.adultList.push(i);
    }
    for (let i = 0; i < 6; i++) {
      data.childrenList.push(i);
    }
    for (let i = 1; i < 13; i++) {
      data.childrenAgeList.push(i);
    }
    data.scrollStyle = useScrollModule().scrollStyle;
    const search = inject(DirtionmaryHelper.DiDaHOTEL_QUERY_PARAM) as any;
    if (search.searchroomGroup && search.searchroomGroup.length == 0) {
      search.searchroomGroup.push({
        roomNum: 1,
        numberOfAdults: 1,
        numberOfChildren: 0,
      });
    }

    let getParamsMsg = JSON.parse(
      localStorage.getItem(DirtionmaryHelper.SCATTERED_DiDaHOTEL_DATE)
    );
    data.auditNum = 1;
    data.childNum = 0;
    data.room = 1;
    data.dateRange.to = search.CheckInDate;
    data.dateRange.from = search.CheckOutDate;
    data.dateRangeFormat = `${search.CheckInDate} - ${search.CheckOutDate}`;

    data.RoomTypeList = useHotel.getHotelRoomType();
    data.scatteredRoomTypeList = useHotel.getHotelScatRoom();
    data.ScatMeaList = useHotel.getHotelScatMeal();
    const methods = {
      goUrl(url: stringify, row: {}) {
        url = `${url}/${search.hotelId}/${row.RatePlanID}`;
        let d = {
          room: data.room,
          auditNum: data.auditNum,
          childNum: data.childNum,
        };
        context.emit("goUrl", url, d);
      },
      showMore(index) {
        if (data.isShow === index) {
          data.isShow = "";
        } else {
          data.isShow = index;
        }
      },
      getPrice(price) {
        return Math.ceil(price);
      },
      //日期格式化
      getformatDateStr(value) {
        var dt = new Date(value);
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2, "0");
        let date = (dt.getDate() + 1).toString().padStart(2, "0");
        return year + "-" + month + "-" + date;
      },
      setData() {
        localStorage.removeItem(DirtionmaryHelper.SCATTERED_DiDaHOTEL_DATE);
        let d = {
          CheckInDate: search.CheckInDate,
          CheckOutDate: search.CheckOutDate,
          searchroomGroup: search.searchroomGroup,
          room: data.room,
          auditNum: data.auditNum,
          childNum: data.childNum,
        };
        // 先不缓存
        localStorage.setItem(
          DirtionmaryHelper.SCATTERED_DiDaHOTEL_DATE,
          JSON.stringify(d)
        );
      },
      //获取房型
      getRoomType(roomtypeId) {
        let roomtypeName = "";
        if (roomtypeId > 0) {
          data.HotelRoomTypes.forEach((item) => {
            if (item.ID == roomtypeId) {
              roomtypeName = item.Name_CN;
            }
          });
        }
        return roomtypeName;
      },
      //获取道旅床类型列表
      getdidaBedType() {
        DidaService.GetDidaBedType({}).then((res) => {
          if (res.data.resultCode == 1) {
            data.HotelRoomTypes = res.data.data;
          }
        });
      },
      //获取道旅餐食类型
      getdidaMealType() {
        DidaService.GetDidaMealType({}).then((res) => {
          if (res.data.resultCode == 1) {
            data.HotelMealTypes = res.data.data;
          }
        });
      },
      initHotel() {
        data.loading = true;
        let param = Object.assign(search);
        DidaService.GetHotelRoomsList(param)
          .then((r) => {
            data.SimilarList = [] as Array<any>;
            if (r.data.data.HotelList && r.data.data.HotelList.length > 0) {
              if (r.data.resultCode == ApiResult.SUCCESS) {
                if (
                  Object.prototype.toString.call(
                    r.data.data.HotelList[0].GroupRatePlanList
                  ) == "[object Object]"
                ) {
                  data.SimilarList.push(r.data.data.HotelList[0].GroupRatePlanList);
                } else {
                  data.SimilarList = r.data.data.HotelList[0].GroupRatePlanList;
                }
              }
              context.emit("getPriceDetails", r.data.data.HotelList[0].LowestPrice);
            } else {
              context.emit("getPriceDetails", { Currency: "", Value: 0 });
            }

            data.loading = false;
          })
          .catch((e) => {
            data.loading = false;
            message.errorMsg(e.message);
          });
      },

      //设置房间里面成人数改变总成人数和儿童数
      setPeopleNum() {
        data.auditNum = 0;
        data.childNum = 0;
        search.searchroomGroup.forEach((x) => {
          data.auditNum += x.numberOfAdults;
          data.childNum += x.numberOfChildren;
          if (x.numberOfChildren == 0) {
            x.ChildAgeDetails = "";
          }
        });
        if (data.auditNum == null || data.auditNum == undefined) {
          data.auditNum = 1;
        }
        if (data.childNum == null || data.childNum == undefined) {
          data.childNum = 1;
        }
      },
      //房间数改变
      getRoomList(roomNum) {
        data.auditNum = 0;
        data.childNum = 0;
        let length = search.searchroomGroup.length;
        if (roomNum > length) {
          for (let i = 1; i <= roomNum - length; i++) {
            let obj = {
              roomNum: i,
              numberOfAdults: 1,
              numberOfChildren: 0,
              ChildAgeDetails: "",
            };
            search.searchroomGroup.push(obj);
          }
        } else {
          search.searchroomGroup = search.searchroomGroup.filter((x: any, i: Number) => {
            if (roomNum > i) return x;
          });
        }
        data.auditNum = 0;
        data.childNum = 0;
        search.searchroomGroup.forEach((x) => {
          data.auditNum += x.numberOfAdults;
          data.childNum += x.numberOfChildren;
        });
        data.isShowPop = true;
        search.auditNum = data.auditNum;
        search.childNum = data.childNum;
      },
      dateRangeHandler(e: any) {
        search.CheckInDate = `${e.from.year}/${e.from.month}/${e.from.day}`;
        if (search.CheckInDate != `${e.to.year}/${e.to.month}/${e.to.day}`) {
          search.CheckOutDate = `${e.to.year}/${e.to.month}/${e.to.day}`;
          data.dateRangeFormat = `${search.CheckInDate} - ${search.CheckOutDate} `;
          if (qDateProxy.value) qDateProxy.value.hide();
        } else {
          // message.errorMsg(`${t('v101.scatteredDetails.timeTis')}`)
        }
      },
      optionsFn(cd: any) {
        return (
          cd >= date.formatDate(date.addToDate(new Date(), { days: 8 }), "YYYY/MM/DD")
        );
      },
    };
    watch(search, (n, o) => {
      methods.setData();
    });
    onMounted(() => {
      methods.getdidaBedType();
      methods.getdidaMealType();
      methods.initHotel();
      methods.setData();
    });
    return {
      ...toRefs(data),
      ...methods,
      qDateProxy,
      qNameProxy,
      search,
    };
  },
});
</script>

<style>
.wrap-title {
  /* width: 33.33%; */
  overflow: hidden;
  white-space: wrap;
}
.HD_Black {
  background-color: black;
}
.HD_Green {
  background-color: green;
}
/* 显示隐藏 */
.order-show {
  width: 40%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #f6665d;
}
</style>
