<template>
  <div class="rounded-borders bg-white row items-center q-pa-md">
    <n-cascader v-if="$q.platform.is.desktop" class="col-2 no-border" @update:value="changearea" v-model:value="cascader.addressValue" size="large" :placeholder="$t('hotel.area')" clearable check-strategy="all" :options="provinces" value-field="ID" label-field="Name" remote :on-load="loadChilds" cascade />
    <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>
    <n-select v-if="$q.platform.is.desktop" filterable @update:value="changeHotel" class="q-ml-lg col-2" style="min-width: 190px" clearable v-model:value="search.HotelChooseArray" :placeholder="$t('hotel.searchName')" multiple :options="cacheHotels" max-tag-count="responsive" size="large" value-field="ID" label-field="Name" />
    <div class="col"></div>
    <q-btn unelevated class="bg-grey-3 hover q-mr-md" icon="shopping_cart" :title="$t('hotel.car.shoppingTitle')" @click="rightCarOpen=true">
      <q-badge color="red" rounded floating>{{HotelLength}}</q-badge>
    </q-btn>
    <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 v-if="$q.platform.is.mobile">
            <n-cascader @update:value="changearea" v-model:value="cascader.addressValue" size="large" :placeholder="$t('hotel.area')" clearable check-strategy="all" :options="provinces" value-field="ID" label-field="Name" remote :on-load="loadChilds" cascade />
          </div>
          <div class="q-my-md" v-if="$q.platform.is.mobile">
            <q-field stack-label :label="$t('daterange')" outlined 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 v-if="$q.platform.is.mobile">
            <n-select filterable style="min-width: 190px" clearable v-model:value="search.HotelChooseArray" :placeholder="$t('hotel.searchName')" multiple :options="cacheHotels" max-tag-count="responsive" size="large" value-field="ID" label-field="Name" />
          </div>
          <div class="q-my-md">
            <q-select v-model="search.Star" dense :options="hotelsRates" emit-value option-label="name" option-value="id" map-options clearable :label="$t('hotel.hotelRate')" standout />
          </div>
          <div class="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>
        </q-card>
      </q-popup-proxy>
    </q-btn>
    <q-btn color="primary" unelevated :label="$t('query')" />

  </div>
  <q-dialog v-model="rightCarOpen" maximized full-height position="right">
    <list-car @close="close" @success="setSuccess"></list-car>
  </q-dialog>

</template>

<script lang="ts">
import svgIcon from '../../global/svg-icon.vue'
import { computed, inject, provide, reactive, ref, toRefs, defineComponent, onMounted, watch } from 'vue'
import HotelService from '../../../api/hotel'
import message from '../../../utils/message'
import { ApiResult } from '../../../@types/enumHelper'
import { CascaderOption,NCascader,NSelect } from 'naive-ui'
import { date } from 'quasar'
import { HotelRate, useHotel } from '../../../utils/hotelRate'
import { useQuasar } from 'quasar'
import useScrollModule from '../../../module/scrollbar/scrollModule'
// import { dateDiffer } from '../../../utils/tools'
import ListCar from "./ListCar.vue"
import { DirtionmaryHelper } from '../../../config/dictionary'
export default defineComponent({
  components: { svgIcon, ListCar, NCascader, NSelect },
  setup() {
    const HotelLength = inject(DirtionmaryHelper.HOTEL_CAR_ORDER_LENGTH) as any
    const cars = inject(DirtionmaryHelper.HOTEL_CAR_LIST) as any
    // cars&&cars.value.forEach((item:any,index:Number) => {
    //   if(dateDiffer(item.Date)<15){
    //     cars.value.splice(index,1)
    //   }
    // });
    HotelLength.value = cars.value.length
    const $q = useQuasar()
    const qDateProxy = ref(null) as any
    const qNameProxy = ref(null) as any
    const data = reactive({
      rightCarOpen: false,
      scrollStyle: {} as any,
      addressParams: {
        Id: '651'
      },
      provinces: [],
      cascader: {
        addressValue: null
      } as any,
      dateRange: {} as any,
      dateRangeFormat: '',
      hotelName: '',
      loading: false,
      cacheHotels: [] as Array<any>,
      hotelsRates: [] as Array<HotelRate>,
      canHide: false,
    })
    data.scrollStyle = useScrollModule().scrollStyle
    const search = inject(DirtionmaryHelper.HOTEL_QUERY_PARAM) as any

    data.dateRange.to = date.formatDate(date.addToDate(new Date(), { days: 50 }), 'YYYY/MM/DD')
    data.dateRange.from = date.formatDate(date.addToDate(new Date(), { days: 20 }), 'YYYY/MM/DD')
    data.dateRangeFormat = `${data.dateRange.from} - ${data.dateRange.to}`
    search.StartDate = data.dateRange.from
    search.EndDate = data.dateRange.to
    data.hotelsRates = useHotel.getHotelRate()

    const methods = {
      initAddress() {
        HotelService.GetDestination(data.addressParams)
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              r.data.data.forEach((x: any) => {
                x.isLeaf = false
                x.depth = 1
              })
              data.provinces = r.data.data
            } else {
              message.errorMsg(r.data.message)
            }
          })
          .catch(e => {
            message.errorMsg(e.message)
          })
      },
      initHotels() {
        HotelService.GetHasStockHotelList()
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              data.cacheHotels = r.data.data
            } else {
              message.errorMsg(r.data.message)
            }
          })
          .catch(e => {
            message.errorMsg(e.message)
          })
      },
      loadChilds(option: CascaderOption) {
        return new Promise<void>(resolve => {
          console.log('innnnnnn', option)
          HotelService.GetDestination({ Id: option.ID })
            .then(r => {
              if (r.data.resultCode == ApiResult.SUCCESS) {
                r.data.data.forEach((x: any) => {
                  x.isLeaf = true
                  x.depth = 2
                })
                option.children = r.data.data
                resolve()
              } else {
                message.errorMsg(r.data.message)
                resolve()
              }
            })
            .catch(e => {
              message.errorMsg(e.message)
              resolve()
            })
        })
      },
      dateRangeHandler(e: any) {
        search.StartDate = `${e.from.year}/${e.from.month}/${e.from.day}`
        search.EndDate = `${e.to.year}/${e.to.month}/${e.to.day} `
        data.dateRangeFormat = `${search.StartDate} - ${search.EndDate} `
        if (qDateProxy.value) qDateProxy.value.hide()
      },
      optionsFn(cd: any) {
        return cd >= date.formatDate(date.addToDate(new Date(), { days: 20 }), 'YYYY/MM/DD')
      },
      changearea(e: number, option: any, pathValues: Array<any>) {
        search.Province = 0
        search.City = 0
        if(pathValues){
          if (pathValues.length > 0) {
            search.Province = pathValues[0].ID
          }
          if (pathValues.length > 1) {
            search.City = pathValues[1].ID
          }
        }
      },
      changeHotel() {
        setTimeout(() => {
          console.log(search.HotelChooseArray)
        }, 1000)
      },
      close(){
        data.rightCarOpen = false
      },
      setSuccess(){
        data.rightCarOpen = false
      },
    }
    const searchCnt = computed(() => {
      let setCnt = 0
      if ($q.platform.is.mobile) {
        if (search.Province > 0) setCnt++
        if (search.StartDate.length > 0) setCnt++
        if (search.HotelChooseArray.length > 0) setCnt++
      }
      if (search.Star != 0) setCnt++
      if (search.MaxPrice.length > 0) setCnt++
      if (search.MinPrice.length > 0) setCnt++
      return setCnt
    })
    methods.initAddress()
    methods.initHotels()
    watch(cars.value, (n, o) => {
      localStorage.setItem(DirtionmaryHelper.HOTEL_HOTELCARS_CACHE,JSON.stringify(cars.value))
    })
    watch(HotelLength, (n, o) => {
      HotelLength.value = n
    })

    onMounted(()=>{
      HotelLength.value = cars.value.length
    })
    return {
      ...toRefs(data),
      ...methods,
      qDateProxy,
      qNameProxy,
      searchCnt,
      search,
      cars,
      HotelLength
    }
  }
})
</script>

<style>

</style>
