<template>
  <div class="rounded-borders bg-white row items-center q-pa-md">
    <q-select
      v-if="$q.platform.is.desktop"
      style="min-width: 190px"
      unelevated
      v-model="search.CountryCode"
      dense
      :options="Areas"
      emit-value
      option-label="CountryName_CN"
      option-value="ISOCountryCode"
      map-options
      :label="$t('hotel.area')"
      standout
      @update:model-value="changeCountry"
      use-input
      @filter="filterCountry"
    />
    <q-select
      v-if="$q.platform.is.desktop"
      class="q-ml-lg col-2"
      style="min-width: 190px"
      unelevated
      v-model="search.CityCode"
      dense
      :options="CityList"
      emit-value
      option-label="CityName_CN"
      option-value="CityCode"
      map-options
      :label="$t('hotel.area')"
      standout
      use-input
      @filter="filterCity"
    />
    <q-field
      v-if="$q.platform.is.desktop"
      stack-label
      :label="$t('daterange')"
      standout
      class="q-ml-lg col-2"
      style="min-width: 190px"
      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="col"></div>
    <q-btn unelevated class="bg-grey-3 hover q-mr-md" :title="$t('morequery')">
      <q-badge
        rounded
        class="din bg-red-2 text-red-14 text-weight-bold"
        floating
        :label="searchCnt"
        v-if="searchCnt > 0"
      />
      <svg-icon
        color="dark"
        icon="Text/Filter.svg"
        :tips="$t('morequery')"
        :size="20"
      ></svg-icon>
      <q-tooltip>{{ $t("morequery") }}</q-tooltip>
      <q-popup-proxy
        class="no-shadow"
        style="box-shadow: 0 0 50px #ddd !important"
        :offset="[0, 20]"
        :model-value="canHide"
      >
        <q-card class="q-pa-md rounded-borders" style="width: 300px">
          <div class="q-mb-md text-subtitle2">{{ $t("morequery") }}</div>
          <div class="q-my-md" v-if="$q.platform.is.mobile">
            <q-select
              unelevated
              v-model="search.CityCode"
              dense
              :options="Areas"
              emit-value
              option-label="CityName_CN"
              option-value="CityCode"
              map-options
              :label="$t('hotel.area')"
              standout
            />
          </div>
          <div class="q-my-md" v-if="$q.platform.is.mobile">
            <q-field
              stack-label
              :label="$t('daterange')"
              standout
              style="min-width: 190px"
              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>

          <div class="q-my-md row items-center">
            <q-input
              v-model="search.MinPrice"
              class="col q-mr-md"
              mask="#.##"
              reverse-fill-mask
              dense
              type="text"
              standout
              :label="$t('hotel.minPrice')"
            />
            <q-input
              v-model="search.MaxPrice"
              class="col"
              dense
              mask="#.##"
              reverse-fill-mask
              ftype="text"
              standout
              :label="$t('hotel.maxPrice')"
            />
          </div>
          <div class="q-my-md">
            <q-select
              v-model="search.BedTypeID"
              dense
              :options="HotelRoomTypes"
              emit-value
              option-value="ID"
              clearable
              map-options
              :label="$t('v101.scattered.fangxingtype')"
              standout
            >
              <template v-slot:option="scope">
                <q-item v-bind="scope.itemProps">
                  <q-item-section>
                    <q-item-label>
                      <template v-if="scope.opt.Name_CN && scope.opt.Name_CN != ''">
                        {{ scope.opt.Name_CN }}
                      </template>
                      <template v-else>
                        {{ scope.opt.Name }}
                      </template>
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="q-my-md">
            <q-select
              v-model="search.BreakfastTypeID"
              dense
              :options="HotelMealTypes"
              emit-value
              option-label="Name_CN"
              option-value="ID"
              clearable
              map-options
              :label="$t('v101.scattered.canxingtype')"
              standout
            />
          </div>
          <div class="q-my-md row items-center">
            <q-input
              v-model="search.MinStarRating"
              class="col q-mr-md"
              mask="#.##"
              reverse-fill-mask
              dense
              type="text"
              standout
              :label="$t('v101.scattered.minxingji')"
            />
            <q-input
              v-model="search.MaxStarRating"
              class="col"
              dense
              mask="#.##"
              reverse-fill-mask
              ftype="text"
              standout
              :label="$t('v101.scattered.maxxingji')"
            />
          </div>
          <div class="q-my-md">
            <q-input
              v-model="keyWords"
              class="col"
              reverse-fill-mask
              dense
              type="text"
              standout
              :label="$t('v101.scattered.jiudianName')"
            />
          </div>
        </q-card>
      </q-popup-proxy>
    </q-btn>
    <q-btn
      color="primary"
      unelevated
      :label="$t('query')"
      :loading="loading"
      @click="setData"
    />
  </div>
</template>

<script lang="ts">
import { useI18n } from "vue-i18n";
import svgIcon from "../../global/svg-icon.vue";
import DidaService from "../../../api/didahotel";
import {
  computed,
  inject,
  reactive,
  ref,
  toRefs,
  defineComponent,
  onMounted,
  watch,
} from "vue";
import message from "../../../utils/message";
import { NCascader, NSelect } from "naive-ui";
import { date } from "quasar";
import { HotelRate, HotelArea, useHotel } from "../../../utils/hotelRate";
import { useQuasar } from "quasar";
import useScrollModule from "../../../module/scrollbar/scrollModule";
import { DirtionmaryHelper } from "../../../config/dictionary";
export default defineComponent({
  components: { svgIcon, NCascader, NSelect },
  setup() {
    const $q = useQuasar();
    const qDateProxy = ref(null) as any;
    const qNameProxy = ref(null) as any;
    const { t } = useI18n();
    const data = reactive({
      scrollStyle: {} as any,
      Areas: [] as any, //国家列表
      AllAreas: [] as any, //所有国家
      CityList: [] as any, //城市列表
      AllCityList: [] as any, //所有城市列表
      cascader: {
        addressValue: null,
      } as any,
      dateRange: {} as any, //当前日期
      dateRangeFormat: "", //可选日期
      loading: false,
      hotelsRates: [] as Array<HotelRate>,
      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, //房间
      HotelLiveRates: [] as Array<HotelRate>, //住宿类型
      HotelRoomTypes: [] as Array<HotelRate>, //房类型
      HotelMealTypes: [] as Array<HotelRate>, //餐型
      HotelDidaPropertyCategory: [] as Array<HotelRate>,
      keyWords: "" as stringify,
      CityCode: "" as stringify,
      CountryCode: "" as stringify,
    });
    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);
    }

    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,
      });
    }
    data.dateRange.to = date.formatDate(
      date.addToDate(new Date(), { days: 9 }),
      "YYYY/MM/DD"
    );
    data.dateRange.from = date.formatDate(
      date.addToDate(new Date(), { days: 8 }),
      "YYYY/MM/DD"
    );
    data.dateRangeFormat = `${data.dateRange.from} - ${data.dateRange.to}`;
    search.CheckInDate = data.dateRange.from;
    search.CheckOutDate = data.dateRange.to;
    data.hotelsRates = useHotel.getHotelRate();
    data.HotelMealTypes = useHotel.getHotelMeal();
    data.HotelConceptTypes = useHotel.getHotelConcept();
    data.CityCode = data.CityCode;
    const methods = {
      dateRangeHandler(e: any) {
        search.CheckInDate = `${e.from.year}/${e.from.month}/${e.from.day}`;
        search.CheckOutDate = `${e.to.year}/${e.to.month}/${e.to.day} `;
        data.dateRangeFormat = `${search.CheckInDate} - ${search.CheckOutDate} `;
        if (qDateProxy.value) qDateProxy.value.hide();
      },
      optionsFn(cd: any) {
        return (
          cd >= date.formatDate(date.addToDate(new Date(), { days: 8 }), "YYYY/MM/DD")
        );
      },
      setData() {
        localStorage.removeItem(DirtionmaryHelper.SCATTERED_DiDaHOTEL_DATE);
        let d = {
          CheckInDate: search.CheckInDate,
          CheckOutDate: search.CheckOutDate,
        };
        // 先不缓存
        localStorage.setItem(
          DirtionmaryHelper.SCATTERED_DiDaHOTEL_DATE,
          JSON.stringify(d)
        );
      },
      //获取道旅餐食类型
      getdidaMealType() {
        DidaService.GetDidaMealType({}).then((res) => {
          if (res.data.resultCode == 1) {
            data.HotelMealTypes = res.data.data;
          }
        });
      },
      //获取道旅房型列表
      getdidaBedType() {
        DidaService.GetDidaBedType({}).then((res) => {
          if (res.data.resultCode == 1) {
            data.HotelRoomTypes = res.data.data;
          }
        });
      },
      filterCountry(val: string, update: any) {
        if (update) {
          update(() => {
            if (val === "") {
              data.Areas = JSON.parse(JSON.stringify(data.AllAreas));
            } else {
              const needle = val.toLowerCase();
              data.Areas = data.AllAreas.filter(
                (v) => v.CountryName_CN.toLowerCase().indexOf(needle) > -1
              );
            }
          });
        }
      },
      //国家切换
      changeCountry(e: any) {
        if (e) {
          methods.getdidaCity();
        } else {
          data.CityList = [];
          search.CityCode = "";
        }
      },
      //获取道旅国家
      getdidaCountry() {
        DidaService.GetDiDaCountry().then((res) => {
          if (res.data.resultCode == 1) {
            var tempArray = res.data.data;
            data.Areas = tempArray;
            data.AllAreas = tempArray;
            if (tempArray && tempArray.length > 0) {
              if (tempArray.findIndex((item) => item.ISOCountryCode == "JP") != -1) {
                search.CountryCode = "JP";
              } else {
                search.CountryCode = data.Areas[0].ISOCountryCode;
              }
            }
            methods.getdidaCity();
          }
        });
      },
      //城市筛选
      filterCity(val: string, update: any) {
        if (update) {
          update(() => {
            if (val === "") {
              data.CityList = JSON.parse(JSON.stringify(data.AllCityList));
            } else {
              const needle = val.toLowerCase();
              data.CityList = data.AllCityList.filter(
                (v) => v.CityName_CN.toLowerCase().indexOf(needle) > -1
              );
            }
          });
        }
      },
      //获取道旅城市
      getdidaCity() {
        var cityParm = {
          CountryCode: search.CountryCode,
        };
        var newCity = [] as any;
        DidaService.GetDidaCity(cityParm).then((res) => {
          if (res.data.resultCode == 1) {
            var tempArray = res.data.data;
            if (tempArray && tempArray.length > 0) {
              tempArray.forEach((item) => {
                if (item.Type == "City") {
                  var obj = {
                    CityCode: item.CityCode,
                    CityName_CN: item.CityName_CN,
                  };
                  newCity.push(obj);
                }
              });
            }
            data.CityList = newCity;
            data.AllCityList = newCity;
            if (data.CityList && data.CityList.length > 0) {
              search.CityCode = data.CityList[0].CityCode;
            }
          }
        });
      },
    };
    const searchCnt = computed(() => {
      let setCnt = 0;
      if ($q.platform.is.mobile) {
        if (data.placeKeyWords && !data.keyWords) setCnt++;
        if (data.dateRange) setCnt++;
        if (search.searchroomGroup.length > 0) setCnt++;
      }
      if (data.keyWords) setCnt++;
      if (search.MaxStarRating) setCnt++;
      if (search.MinStarRating) setCnt++;
      if (search.searchRoomType && search.searchRoomType.length > 0) setCnt++;
      if (search.searchMealType && search.searchMealType.length > 0) setCnt++;
      if (search.MinPrice) setCnt++;
      if (search.MaxPrice) setCnt++;
      search.Name_CN = data.keyWords;
      return setCnt;
    });
    watch(search, (n, o) => {
      methods.setData();
    });
    onMounted(() => {
      methods.getdidaCountry();
      methods.getdidaBedType();
      methods.getdidaMealType();
      methods.setData();
    });
    return {
      ...toRefs(data),
      ...methods,
      qDateProxy,
      qNameProxy,
      searchCnt,
      search,
    };
  },
});
</script>

<style></style>
