<template>
  <div
    class="items-start travel-list"
    :class="$q.platform.is.desktop ? 'row q-mt-lg' : 'colmuns'"
  >
  <!-- 移动端 -->
  <div v-if="$q.platform.is.mobile">

    <div class="row q-pb-sm">
      <div class="col row items-center justify-center bg-white">
        <div @click="showAddress = true" class="nav-item">目的地<i class="iconfont iconarrowdown text-grey-6" style="margin-top: 3px; margin-left:4px"></i></div>
        <div @click="showPrice = true" class="nav-item">價錢/时间<i class="iconfont iconarrowdown text-grey-6" style="margin-top: 3px; margin-left:4px"></i></div>
        <div @click="showStarRating = true" class="nav-item">星级<i class="iconfont iconarrowdown text-grey-6" style="margin-top: 3px; margin-left:4px"></i></div>
        
      </div>
       
    </div>
      <popup mode="top" v-model="showAddress">
      <q-card flat class="rounded-borders q-py-md">
        <div class="text-subtitle1 text-weight-bold q-mx-md">篩選目的地</div>
        <destination class="q-pa-sm"
          :msg="{
          CityCode:msg.CityCode,
          KeyWords:msg.KeyWords,
          KeyWords2:msg.CityName,
          StartDate:msg.CheckInDate,
          EndDate:msg.CheckOutDate,
          searchroomGroup:msg.searchroomGroup}"
          Type="1"
          @change="clearQuery"
          @changeCity="changCity"
          @clear="clearQuery"></destination>
          <div class="q-pt-sm cursor-pointer">
              <div v-show="regionList.length" class="self-center no-outline text-s" 
              tabindex="0"
              >
              <div class="row justify-between q-px-md" @click="showRegion = !showRegion">
                <div>区域</div>
                <div class="text-xs">
                  {{ msg.CityName_CN }}
                  <q-icon :name="showRegion?'keyboard_arrow_up':'keyboard_arrow_down'" color="grey-7"  size="20px"/>
                </div>
              </div>
            <div v-show="showRegion" id="cit">
                <div class="row no-wrap q-pa-sm" v-show="msg.CityCode&&regionList.length">
                        <div class="col q-pa-sm" style="width: 500px;">
                          <div class="w-full row wrap">
                              <div class="CityNameBox-r-kkday col-2 text-center overflow-hidden 
                              q-mb-xs q-mr-xs text-xxs text-no-wrap q-pa-xs cursor-pointer" 
                              v-for="(y,index) in regionList" :key="index"
                              :class="[msg.regionCode==y.CityCode?'active':'']"
                              @click="msg.regionCode = y.CityCode,
                              msg.CityName_CN = y.CityName_CN,
                              showRegion=false,
                              resetQuery()">
                                  <span class="text-wrap">{{ y.CityName_CN }}</span>
                              </div>
                          </div>
                        </div>
                </div>
              </div>
            </div>
            
        </div>
        <!-- <div class="relative">
          <q-input
            v-model="searchAdd.name"
            type="text"
            standout
            placeholder="搜尋目的地"
            class="q-ma-md"
            @input="changeAddrSearchHandler"
            @keyup.enter="searchCity"
            @update:model-value="searchCity"
          />
          <div class="KeyCityBox absolute bg-white showbox column q-ml-md w-full q-pa-sm" 
            v-show="showCity"
            id="city"
            transition-show="fade"
            elevated
            transition-hide="scale"
            style="z-index: 9;">
            <div v-for="item in KeyCityList" :key="item.Id"
            class="cursor-pointer q-py-xs"
            @click="selectCity(item)"
            >{{ item.Name }}</div>
          </div>
        </div>
         <q-tree
          ref="Cities"
          :nodes="CitiesList"
          no-connectors
          node-key="CityCode"
          label-key="CityName"
          tick-strategy="leaf-filtered"
          @update:ticked="handleCitiesTicked"
          :ticked="CitiesTicked"
          text-color="#666"
          no-nodes-label=" "
          no-results-label=" "
        />
        <q-tree v-if="regionList.length>0&&regionList[0].children.length > 0"
          ref="region"
          :nodes="regionList"
          no-connectors
          node-key="Id"
          label-key="Name"
          tick-strategy="leaf-filtered"
          @update:ticked="handleRegionTicked"
          :ticked="regionTicked"
          text-color="#666"
          no-nodes-label=" "
          no-results-label=" "
        /> -->
      </q-card>
      </popup>

      <popup mode="top" v-model="showPrice">

      <q-card flat class="rounded-borders q-pa-md q-mt-lg">
        <div class="text-subtitle1 text-weight-bold">價錢篩選（CNY）</div>
        <div class="q-mt-md text-grey-6 text-subtitle2 text-regular">
          {{ msg.priceRange.min }} - {{ msg.priceRange.max }}
        </div>
        <q-range
          v-model="msg.priceRange"
          :min="priceModel.min"
          :max="priceModel.max"
          :step="1"
          @change="testHandler"
          color="primary"
          class="q-mt-md"
        />
        <div class="row">
          <q-chip
            square
            class="cursor-pointer"
            clickable
            :text-color="msg.PriceName != x.Name ? 'dark' : 'white'"
            :class="{
              'bg-grey-3': msg.PriceName != x.Name,
              'bg-primary': msg.PriceName == x.Name,
            }"
            v-for="(x, i) in PriceList"
            :key="i"
            @click="chosenSortHandler(x)"
            >{{ x.Name }}</q-chip
          >
        </div>
      </q-card>
      <q-card flat class="rounded-borders q-mt-lg row no-padding q-mb-lg">
        <div
          class="q-px-md q-py-sm "
          style="border-right: 1px solid #eee; border-radius: 0 !important"
        >
          <q-icon name="iconfont iconigw-l-date-trade" size="24px" />
        </div>
        <div class="row items-center justify-center col">
          <span class="text-grey-8">
            {{
              msg.StartDate
                ? `${msg.StartDate} - ${msg.EndDate}`
                : "篩選出發日期"
            }}
          </span>
          <q-popup-proxy :offset="[0, 0]" ref="qDateProxy">
            <div>
              <q-date
                v-model="dateRange"
                :options="optionsFn"
                range
                @range-end="dateRangeHandler"
                mask="YYYY-MM-DD"
              ></q-date>
            </div>
          </q-popup-proxy>
        </div>
      </q-card>
      </popup>

      <popup mode="top" v-model="showStarRating">
        <q-card flat class="rounded-borders q-py-md">
          <div class="text-subtitle1 text-weight-bold q-mx-md q-pb-sm">篩選星级</div>
          <q-tree
            ref="region"
            :nodes="StarRatingList"
            no-connectors
            node-key="Id"
            label-key="Name"
            tick-strategy="leaf"
            @update:ticked="handleQStarRegionTicked"
            :ticked="msg.QStarRating"
            text-color="#666"
            no-nodes-label=" "
            no-results-label=" "
          />
        </q-card>
        
      </popup>

      
  </div>
    <div v-else class="col-3" :class="$q.platform.is.desktop ? 'q-mr-lg' : 'q-ma-md'">
      <q-card flat class="rounded-borders q-py-md">
        <div class="text-subtitle1 text-weight-bold q-mx-md">篩選目的地</div>
        <div class="relative">
          <destination class="q-pa-sm"
          :msg="{
          CityCode:msg.CityCode,
          KeyWords:msg.KeyWords,
          KeyWords2:msg.CityName,
          StartDate:msg.CheckInDate,
          EndDate:msg.CheckOutDate,
          searchroomGroup:msg.searchroomGroup}"
          Type="2"
          @change="clearQuery"
          @changeCity="changCity"
          @clear="clearQuery"></destination>
          
          <div class="q-pt-sm cursor-pointer">
              <div v-show="msg.CityCode&&regionList.length" class="self-center no-outline text-s" 
              tabindex="0"
              >
              <div class="row justify-between q-px-md">
                <div>区域</div>
                <div class="text-xs">
                  {{ msg.CityName_CN }}
                  <q-icon :name="showRegion?'keyboard_arrow_up':'keyboard_arrow_down'" color="grey-7"  size="20px"/>
                </div>
              </div>
            <q-popup-proxy :offset="[0, 10]">
                <div class="row no-wrap q-pa-sm">
                        <div class="col q-pa-sm" style="width: 500px;">
                          <div class="w-full row wrap">
                              <div class="CityNameBox-r-kkday col-2 text-center overflow-hidden 
                              q-mb-xs q-mr-xs text-xxs text-no-wrap q-pa-xs cursor-pointer" 
                              v-for="(y,index) in regionList" :key="index"
                              :class="[msg.regionCode==y.CityCode?'active':'']"
                              @click="msg.regionCode = y.CityCode,
                              msg.CityName_CN = y.CityName_CN,
                              showRegion=false,
                              resetQuery()">
                                  <span class="text-wrap">{{ y.CityName_CN }}</span>
                              </div>
                          </div>
                        </div>
                </div>
              </q-popup-proxy>
            </div>
            
            <!-- <q-input
            id="search_key"
            v-model="msg.regionCode"
            clearable
            label="区域"
            filled
            dense
            disable
            standout="bg-grey-2 text-black"
            >
            </q-input> -->
            
        </div>
          <!-- <q-input
            v-model="searchAdd.name"
            type="text"
            standout
            placeholder="搜尋目的地"
            class="q-ma-md"
            @input="changeAddrSearchHandler"
            @keyup.enter="searchCity"
            @update:model-value="searchCity"
          /> -->
          <!-- <div class="KeyCityBox absolute bg-white showbox column q-ml-md w-full q-pa-sm"
            v-show="showCity"
            id="city"
            transition-show="fade"
            elevated
            transition-hide="scale"
            style="z-index: 9;">
            <div v-for="item in KeyCityList" :key="item.Id"
            class="cursor-pointer q-py-xs"
            @click="selectCity(item)"
            >{{ item.Name }}</div>
          </div> -->
        </div>
         <!-- <q-tree
          ref="Cities"
          :nodes="CitiesList"
          no-connectors
          node-key="CityCode"
          label-key="CityName"
          tick-strategy="leaf-filtered"
          @update:ticked="handleCitiesTicked"
          :ticked="CitiesTicked"
          text-color="#666"
          no-nodes-label=" "
          no-results-label=" "
        />
        <q-tree v-if="regionList.length>0&&regionList[0].children.length > 0"
          ref="region"
          :nodes="regionList"
          no-connectors
          node-key="Id"
          label-key="Name"
          tick-strategy="leaf-filtered"
          @update:ticked="handleRegionTicked"
          :ticked="regionTicked"
          text-color="#666"
          no-nodes-label=" "
          no-results-label=" "
        /> -->
      </q-card>
      

      <q-card flat class="rounded-borders q-mt-lg row no-padding">
        <div
          class="q-px-md q-py-sm"
          style="border-right: 1px solid #eee; border-radius: 0 !important"
        >
          <q-icon name="iconfont iconigw-l-date-trade" size="24px" />
        </div>
        <div class="row items-center justify-center col">
          <span class="text-grey-8">
            {{
              msg.StartDate
                ? `${msg.StartDate} - ${msg.EndDate}`
                : "篩選出發日期"
            }}
          </span>
          <q-popup-proxy :offset="[0, 0]" ref="qDateProxy">
            <div>
              <q-date
                v-model="dateRange"
                :options="optionsFn"
                range
                @range-end="dateRangeHandler"
                mask="YYYY/MM/DD"
              ></q-date>
            </div>
          </q-popup-proxy>
        </div>
      </q-card>

      <q-card flat class="rounded-borders q-py-xs q-mt-lg">
        <q-tree
          ref="region"
          :nodes="StarRatingList"
          no-connectors
          node-key="Id"
          label-key="Name"
          tick-strategy="leaf"
          @update:ticked="handleQStarRegionTicked"
          :ticked="msg.QStarRating"
          text-color="#666"
          no-nodes-label=" "
          no-results-label=" "
        />
      </q-card>

      <q-card flat class="rounded-borders q-pa-md q-mt-lg">
        <div class="text-subtitle1 text-weight-bold">價錢篩選（CNY）</div>
        <div class="q-mt-md text-grey-6 text-subtitle2 text-regular">
          {{ msg.priceRange.min }} - {{ msg.priceRange.max }}
        </div>
        <q-range
          v-model="msg.priceRange"
          :min="priceModel.min"
          :max="priceModel.max"
          :step="1"
          @change="testHandler"
          color="primary"
          class="q-mt-md"
        />
        <div class="row">
          <q-chip
            square
            class="cursor-pointer"
            clickable
            :text-color="msg.PriceName != x.Name ? 'dark' : 'white'"
            :class="{
              'bg-grey-3': msg.PriceName != x.Name,
              'bg-primary': msg.PriceName == x.Name,
            }"
            v-for="(x, i) in PriceList"
            :key="i"
            @click="chosenSortHandler(x)"
            >{{ x.Name }}</q-chip
          >
        </div>
      </q-card>
      

      
    </div>
    <div class="col q-mt-sm">
      <div class="rounded-borders bg-white">
        <div class="row q-col-gutter-sm items-center q-pa-md">
          <div class="text-subtitle2 q-mr-md">
            <span class="text-weight-bold text-primary q-mr-sm">
              {{ TotalCount }}
            </span>
            <span>項體驗行程</span>
          </div>
          <q-chip
            v-for="(x, i) in chosenAddress"
            size="13px"
            :key="i"
            removable
            outline
            color="grey"
            :label="x.Name"
          />
        </div>
        <div
          class="q-pa-md row items-center"
          style="border-top: 1px solid #eee"
        >
          <span class="f12">排序：</span>
          <q-chip
            square
            :icon="x.icon"
            class="cursor-pointer"
            clickable
            :text-color="msg.QOrderBy != x.Id ? 'dark' : 'white'"
            :class="{
              'bg-grey-3': msg.QOrderBy != x.Id,
              'bg-primary': msg.QOrderBy == x.Id,
            }"
            v-for="(x, i) in sortArray"
            :key="i"
            @click="chosenSortHandler(x,1)"
            >{{ x.Name }}</q-chip
          >
        </div>
      </div>
      <div class="q-mt-lg" v-if="!$q.loading.isActive && DataList.length > 0">
        <div
          class="rounded-borders cursor-pointer overflow-hidden bg-white"
          :class="$q.platform.is.desktop ? 'row q-mb-md' : 'colmuns q-ma-md'"
          @click="GotoDetails(x)"
          v-for="(x, i) in DataList"
          :key="i"
        >
          <q-img
            :src="x.images[0]?x.images[0]:'../../assets/img/errImg.png'"
            :ratio="1"
            spinner-color="grey"
            spinner-size="20px"
            :width="$q.platform.is.desktop ? '272px' : ''"
            :height="$q.platform.is.desktop ? '' : '200px'"
            class="bg-grey-3"
          >
            <template v-slot:error>
              <div class="absolute-full flex flex-center bg-grey-3 text-dark">
                <img src="../../assets/img/errImg.png" alt="" style="width: 60%;">
              </div>
            </template>
          </q-img>
          <div class="q-pa-md col column">
            <div class="text-subtitle1 text-weight-bold text-grey-9">
              {{ x.name }}
            </div>
            <div class="col">
              <div class="row items-center q-my-sm">
                <q-chip
                  style="background: #26a69a1a"
                  size="sm"
                  class="f12 rounded-borders text-secondary"
                  label="急速確認"
                />
                <template v-if="x.tagList.length">
                  <q-chip
                    v-for="(item,index) in x.tagList"
                    :key="index"
                    style="background: #26a69a1a"
                    size="sm"
                    class="f12 rounded-borders text-secondary"
                    :label="item"
                  />
                </template>
              </div>
              <div
                class="text-subtitle2 text-grey text-weight-regular ellipsis-2-lines"
                style="line-height: 1.6"
              >
                {{ x.description?x.description:'' }}
              </div>
              <div class="row items-center f12 text-grey-6 q-mt-md">
                <q-icon
                  size="12px"
                  name="iconfont icondingweixiao"
                  class="q-mr-sm"
                />
                <span class="q-mr-lg">{{ x.address }}</span>
                <!-- <q-icon
                  size="12px"
                  name="iconfont iconigw-l-date-trade"
                  class="q-mr-sm"
                ></q-icon>
                <span>{{ x.StartDate }}</span> -->
              </div>
            </div>
            <div class="row items-end">
              <div class="col f12">
                
              </div>
              <div class="text-h6 product-price">
                CNY：{{ x.unitprice }}<span class="price-stuff">元起</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div
        v-else-if="!$q.loading.isActive && DataList.length == 0"
        class="text-center q-mt-xl"
      >
        <div class="text-center inline-block">
          <p>
            <img src="~assets/sad.svg" style="width: 30vw; max-width: 150px" />
          </p>
          <p class="text-faded">
            我们找不到有关
            <span v-if="msg.HotelName">\"{{ msg.HotelName }}\"</span>
            的旅游体验，输入其他字眼重试或探索以下人气体验
          </p>
        </div>
      </div>
      <div class="row justify-end">
        <q-pagination
          v-if="PageCount > 1"
          v-model="msg.pageIndex"
          :max="PageCount"
          @input="goSearchHandler"
          :direction-links="true"
          color="white"
          text-color="dark"
          active-color="primary"
          active-text-color="white"
          active-design="unelevated"
          unelevated
          glossy
          ellipses
          :max-pages="6"
          boundary-numbers
          size="13px"
          padding="sm md"
        ></q-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import popup from "../props/index";
import { date } from "quasar";
import destination from '../../pages/didaHotel/destination.vue'
export default {
  props: ["qMsg"],
  components: {popup,destination},
  data() {
    return {
      showAddress: false,
      showStarRating: false,
      showDate: false,
      showPrice: false,
      areaTicked: [],
      ticked: [],
      selected: [],
      searchAdd: {
        name: "",
        value: "",
      },
      areaList: [],
      chosenAddress: [],
      goodsType: [],
      dateRange: null,
      msg: null,
      dayArray: [
        {
          id: 1,
          min: 1,
          max: 1,
          text: "1天",
        },
        {
          id: 2,
          min: 2,
          max: 2,
          text: "2天",
        },
        {
          id: 3,
          min: 3,
          max: 3,
          text: "3天",
        },
        {
          id: 4,
          min: 4,
          max: 4,
          text: "4天",
        },
        {
          id: 5,
          min: 5,
          max: 5,
          text: "5天",
        },
        {
          id: 6,
          min: 6,
          max: 6,
          text: "6天",
        },
        {
          id: 7,
          min: 7,
          max: 8,
          text: "7-8天",
        },
        {
          id: 8,
          min: 9,
          max: 10,
          text: "9-10天",
        },
        {
          id: 9,
          min: 10,
          max: 1000,
          text: "10天以上",
        },
      ],
      DataList: [],
      sortArray: [
        // {
        //   label: "默认排序",
        //   value: 0,
        //   icon: "iconfont icongood",
        // },
        // {
        //   label: "價格：低到高",
        //   value: 1,
        //   icon: "iconfont iconmeiyuan",
        // },
        // {
        //   label: "價格：高到低",
        //   value: 2,
        //   icon: "iconfont iconmeiyuan",
        // },
      ],
      TotalCount: 0,
      PageCount: 0,
      priceModel: {
        min: 1,
        max: 100000,
      },
      CitiesList: [],
      CitiesTicked: [],
      CitiesListAll: [],
      DestiByCityList: [],//   搜索城市
      regionListAll: [],//   区域
      regionList: [],//   区域
      regionTicked: [],
      KeyCityList: [],//   搜索城市
      KeyCityTicked: [],
      showCity: false,
      StarList: [],
      TagList: [],
      NearbyList: [],
      StarRatingList: [],
      PriceList: [],
      showRegion: false,
    };
  },
  watch: {
    qMsg: {
      handler(newVal, oldVal) {
        this.msg = JSON.parse(JSON.stringify(this.qMsg));
        console.log(newVal.KeyWords2,'----222')
        this.msg.priceRange = {
          min: 1,
          max: 100000,
        };
        this.msg.StartPrice = 0;
        this.msg.EndPrice = 100000;
        this.dayArray.forEach((x) => {
          x.checked = false;
        });
        if(!newVal.StartDate||!newVal.EndDate){
          this.msg.StartDate = date.formatDate(new Date(this.qMsg.StartDate), "YYYY/MM/DD")
          this.msg.EndDate = date.formatDate(new Date(this.qMsg.EndDate), "YYYY/MM/DD")
        }
        this.dateRange = { from: this.msg.StartDate, to: this.msg.EndDate };
        if(this.msg.KeyWords!=''){
          this.CitiesTicked = []
          this.regionTicked = []
        }
        if(this.msg.CityCode){
          this.getRegion(this.msg.CityCode)
        }
        this.resetQuery();
      },
      deep: true,
      immediate: true,
    },
  },
  beforeDestroy() {
    document.removeEventListener("click", this.clickHandler);
  },
  created() {
    this.getCity()
    this.initGoods();
    this.getSorts()
    
  },
  mounted() {
    document.addEventListener("click", this.clickHandler);
    // this.CitiesTicked = this.msg.Country ? [this.msg.Country] : (this.msg.Countrys ? this.msg.Countrys : []);
    var CategoryName = this.getUrlKey("CategoryName", window.location.href);
    if (CategoryName) {
      let list = this.goodsType.find(
        (item) => item.CategoryName === CategoryName
      );
      let arr = [];
      list.children.forEach((item) => {
        arr.push(item.Id);
        if (item.children && item.children.length) {
          item.children.forEach((item2) => {
            arr.push(item2.Id);
          });
        }
      });
      this.ticked = arr;
    }
  },
  methods: {
    clearQuery(msg) {
      this.msg = {
        ...this.msg,
        ...msg
      }
      this.$emit('change', this.msg)
    },
    changCity(y){
      // this.msg.CityCode2 = y.CityCode
      this.msg.CityCode = y.CityCode
      this.msg.CityName = y.CityName
      this.resetQuery()
      this.getRegion(this.msg.CityCode)
    },
    clickHandler(e) {
      try {
        if (!document.querySelector("#cit").contains(e.target)) {
          this.showRegion = false;
        }
      } catch (error) {}
      try {
        if (!document.querySelector("#city").contains(e.target)) {
          this.showCity = false;
        }
      } catch (error) {}
    },
    getSorts(){
      this.apipost('dmc_post_B2BAndB2CDiDaHotelQueryCondition', {},
			(res) => {
        if(res.data.resultCode == 1){
          let data = res.data.data
          data.OrderByList.unshift({
            Name: "默认排序",
            Id: 0,
            icon: "iconfont icongood",
          })
          data.OrderByList.forEach((x,index) => {
            if(x.Id==1){
              x.icon = 'iconfont iconmeiyuan'
            }else if(x.Id==2){
              x.icon = 'iconfont iconmeiyuan'
            }else if(x.Id==3){
              x.icon = 'iconfont icongood'
            }else if(x.Id==4){
              x.icon = 'iconfont icongood'
            }
            
          })
          this.sortArray = data.OrderByList
          // data.StarRatingList.forEach((x,index) => {
          //   x.Name = x.StarRating
          //   x.Id = x.StarRating
          // })
          this.StarRatingList = [
            {
              Id: 0,
              Name: "星级",
              children: data.StarRatingList,
            },
          ]
          this.PriceList = data.PriceList
        }
      })
      this.apipost('dmc_post_GetDiDaHotelQuery', {
					
				},
				(res) => {
					if (res.data.resultCode == 1) {
            let data = res.data.data
            data.OrderByList.forEach((x,index) => {
              if(x.Id==1){
                x.icon = 'iconfont icongood'
              }else if(x.Id==2){
                x.icon = 'iconfont iconmeiyuan'
              }else if(x.Id==3){
                x.icon = 'iconfont iconmeiyuan'
              }else if(x.Id==4){
                x.icon = 'iconfont icongood'
              }
              
            })
            
            this.StarList = data.StarList
            this.TagList = data.TagList
            this.NearbyList = data.NearbyList
          }
				},
				(err) => {
				}
			);
    },
    selectCity(item){
      this.msg.CityCode = item.Id
      this.msg.CityCode2 = item.Id
      this.msg.CityName = item.Name.split(' ')[0]
      this.msg.KeyWords2 = item.Name.split(' ')[0]
      this.showCity = false
      this.resetQuery()
    },
    // 关键字搜索城市
    searchCity() {
      if(this.CitiesList.length||this.regionList.length||this.searchAdd.name=='') return this.showCity = false
      else if(this.msg.KeyWords==this.searchAdd.name&&this.searchAdd.name) return this.showCity = true
      this.msg.KeyWords = this.searchAdd.name
			this.apipost('dmc_post_B2BAndB2CGetDestination', {
					KeyWords: this.msg.KeyWords
				},
				(res) => {
					if (res.data.resultCode == 1) {
            let data = res.data.data
            data.forEach((x,index) => {
              x.Name = x.NameCN
              x.Id = x.CityCode
            })
            this.KeyCityList = data
            if(data.length) this.showCity = true
            else this.$q.notify({
              color: "negative",
              textColor: "#FFF",
              icon: "report_problem",
              message: "没有搜索到相关目的地",
              position: "top",
              timeout: 3000,
            })
          }
				},
				(err) => {
				}
			);
		},
    getCity(){
      this.apipost(
        "dmc_post_B2BAndB2CGetHotCity", {},
        res => {
          if (res.data.resultCode == 1) {
            let data = res.data.data
            data.forEach((x,index) => {
              x.CityName = x.GName
              x.CityCode = `title_${index}`
              x.children = x.CityList
              x.CityList.forEach(y => {
                if(index) this.CitiesListAll.push(y)
              })
              if(index) this.CitiesList.push(x)
            })
            // this.msg.CityCode = this.msg.KeyWords?'':data[0].CityList[0].CityCode
            // this.msg.CityName = this.msg.KeyWords?'':data[0].CityList[0].CityName_CN
            // this.msg.CityCode2 = this.msg.KeyWords?'':data[0].CityList[0].CityCode
            // this.CitiesTicked = this.msg.KeyWords?[]:[data[0].CityList[0].CityCode]
            this.CitiesJSON = JSON.parse(JSON.stringify(this.CitiesList));
          }
        },
      );
    },
    // 区域
    getRegion(CityCode) {
				//this.parameters.regionCode = ''
				var regMsg = {
					CityCode: CityCode,
					Name: '',
				};
				this.apipost('dmc_post_GetDestinationByCityCode', regMsg,
					(res) => {
						if (res.data.resultCode == 1) {
              this.regionListAll = []
              this.regionList = []
              let data = res.data.data;
              let arrList = function(list){
                list.forEach(x => {
                  x.Id = x.CityCode;
                  x.Name = x.CityName_CN;
                })
              }
              arrList(data);
							// this.regionTicked = [data[0].CityCode]
              this.regionListAll = data
              // this.regionList = [
              //   {
              //     Id: 0,
              //     Name: '区域',
              //     children: data
              //   }
              // ]
              // this.regionJSON = JSON.parse(JSON.stringify(this.regionList));
              this.regionList = data
              
              
              // const totalRows = Math.ceil(data.length / this.itemsPerRow)
              
              // for (let i = 0; i < totalRows; i++) {
              //   const startIndex = i * this.itemsPerRow
              //   const endIndex = startIndex + this.itemsPerRow
              //   const row = tempObj.HotelFacilityList.slice(startIndex, endIndex)
              //   this.Facilities.push(row)
              // }
						}
					},
					(err) => {}
				);
			},
    handleSelected(target) {
      
    },
    handleQStarRegionTicked(target) {
      this.msg.QStarRating = target
      this.resetQuery();
    },
    // 区域
    handleRegionTicked(target) {
        if(target.length>1) this.regionTicked = [target[0]]
        else if(target.length==1) this.regionTicked = target
        else this.regionTicked = [];
        this.msg.regionCode = this.regionTicked[0]
        let findIndex = this.regionListAll.findIndex(x=>x.CityCode==this.msg.regionCode)
        if(findIndex!=-1) this.msg.CityName_CN = this.regionListAll[findIndex].CityName_CN
        this.resetQuery();
    },
    // 目的地城市
    handleCitiesTicked(target) {
      let oldCityCode = this.msg.CityCode2
      if(target.length>1) this.CitiesTicked = [target[0]]
      else if(target.length==1) this.CitiesTicked = target
      else {
        this.CitiesTicked = [];
        this.regionList = []
        this.regionListAll = []
      }
      this.CitiesList.forEach(x=>{
        x.children.forEach(y => {
          if(y.CityCode==this.msg.CityCode){
            this.msg.GName = x.CityName
          }
        })
      })
      this.msg.CityCode = this.CitiesTicked.length?this.CitiesTicked[0]:''
      this.msg.CityCode2 = this.CitiesTicked.length?this.CitiesTicked[0]:''
      let findIndex = this.CitiesListAll.findIndex(x=>x.CityCode==this.msg.CityCode)
      if(findIndex!=-1) this.msg.CityName = this.CitiesListAll[findIndex].CityName
      if(this.msg.CityCode2!=oldCityCode&&this.CitiesTicked.length){
        this.getRegion(this.msg.CityCode2)
      }else this.regionList = []
      this.resetQuery();
    },
    
    changeExplesdHandler(x) {
      x.explsed = !x.explsed;
      if (x.SubList) {
      }
    },

    chosenSortHandler(x,type) {
      if(type){
        this.msg.QOrderBy = x.Id;
      }else{
        this.msg.StartPrice = x.MinPrice
        this.msg.EndPrice = x.MaxPrice
        this.msg.PriceName = x.Name

        this.priceModel = {
          min: 0,
          max: x.MaxPrice,
        }

        this.msg.priceRange = {
          'min': x.MinPrice,
          'max': x.MaxPrice,
        }
      }
      this.resetQuery();
    },
    optionsFn(cd) {
      return (
        cd >=
        date.formatDate(date.addToDate(new Date(), { days: 8 }), "YYYY/MM/DD")
      );
    },
    testHandler(e) {
      this.$forceUpdate();
      this.msg.StartPrice = e.min;
      this.msg.EndPrice = e.max;
      let PriceName = ''
      this.PriceList.forEach((x) => {
        if(e.min>=x.MinPrice && e.max<=x.MaxPrice){
          PriceName = x.Name;
        }
      })
      if(PriceName){
        this.msg.PriceName = PriceName;
      }else{
        this.msg.PriceName = '';
      }
      this.resetQuery();
    },
    dateRangeHandler(e) {
      this.msg.StartDate = `${e.from.year}/${e.from.month}/${e.from.day}`;
      this.msg.EndDate = `${e.to.year}/${e.to.month}/${e.to.day} `;
      this.$refs.qDateProxy.hide();
      this.resetQuery();
    },
    initGoods() {
      let arr = [];
      let jObj = JSON.parse(window.localStorage.getItem("baseifo"));
      jObj.CategoryList.forEach((x) => {
        if(x.Id==1){
          return;
        }
        if(x.Id==this.msg.categoryId){
          arr.push(x.Id);
        }
        x.checked = false;
        x.explsed = false;
        x.isShow = true;
        x.children = x.SubList;
        x.children.forEach((y) => {
          y.checked = false;
          y.explsed = false;
          y.isShow = true;
          if (y.Id === this.msg.categoryId) {
            arr.push(y.Id);
          }
          if (y.SubList && y.SubList.length) {
            y.children = y.SubList;
            y.children.forEach((z) => {
              z.checked = false;
              z.explsed = false;
              z.isShow = true;
              if (z.Id === this.msg.categoryId) {
                arr.push(z.Id);
              }
              if (y.Id === this.msg.categoryId) {
                arr.push(z.Id);
              }
            });
          }
        });
        this.goodsType.push(x);
      });
      this.goodsTypeJSON = JSON.stringify(this.goodsType);
      if (this.msg.categoryId) {
        this.$nextTick(() => {
          this.$refs.category?.setTicked([...new Set(arr)], true);
        });
      }
    },
    dfs(tree, ope, filter) {
      const walkAndCopy = (tree, depth = 1) => {
        if (filter(tree)) {
          const copy = { ...tree };
          ope(tree.Name, depth);
          if (tree.children) {
            copy.children = [];
            tree.children.forEach((node) => {
              const subTree = walkAndCopy(node, depth + 1);
              subTree && copy.children.push(subTree);
            });
          }
          return copy;
        } else if (tree && tree.children && tree.children.length) {
          const copy = { ...tree };
          ope(tree.Name, depth);
          copy.Name = tree.Name;
          if (tree.children) {
            copy.children = [];
            tree.children.forEach((node) => {
              const subTree = walkAndCopy(node, depth + 1);
              subTree && copy.children.push(subTree);
            });
          }
          return copy;
        }
      };
      return walkAndCopy(tree);
    },
    changeAddrSearchHandler(v) {
      this.showCity = false
      this.CitiesJSONTMP = JSON.parse(JSON.stringify(this.CitiesJSON));
      let tree = this.dfs(
        { CityName: "", children: this.CitiesJSONTMP },
        (name, depth) => {},
        ({ CityName }) => {
          return CityName.indexOf(v) !== -1;
        }
      );
      tree = this.dfs(
        tree,
        (name, depth) => {},
        ({ CityName }) => {
          return CityName.indexOf(v) !== -1;
        }
      );
      // tree = this.dfs(
      //   tree,
      //   (name, depth) => {},
      //   ({ CityName }) => {
      //     return CityName.indexOf(v) !== -1;
      //   }
      // );
      if(tree.children) this.CitiesList = tree.children;

       if(this.regionJSON){
        this.regionJSONTMP = JSON.parse(JSON.stringify(this.regionJSON));
        let treeRegion = this.dfs(
          { Name: "", children: this.regionJSONTMP },
          (name, depth) => {},
          ({ Name }) => {
            return Name.indexOf(v) !== -1;
          }
        );
        treeRegion = this.dfs(
          treeRegion,
          (name, depth) => {},
          ({ Name }) => {
            return Name.indexOf(v) !== -1;
          }
        );
        // treeRegion = this.dfs(
        //   treeRegion,
        //   (name, depth) => {},
        //   ({ Name }) => {
        //     return Name.indexOf(v) !== -1;
        //   }
        // );
        if(treeRegion&&treeRegion.children) this.regionList = treeRegion.children;
        
        if(this.regionList.length||this.CitiesList.length){
          this.msg.KeyWords = ''
          this.msg.KeyWords2 = ''
          this.msg.CityCode = this.CitiesTicked[0]
          this.msg.CityCode2 = this.CitiesTicked[0]
          // this.KeyCityList = []
          this.resetQuery()
        }
      }
    },
    resetQuery(){
      this.msg.pageIndex = 1
      this.goSearchHandler()
    },
    goSearchHandler() {
      this.$q.loading.show();
      this.DataList = [];
      this.PageCount = 0;
      this.TotalCount = 0;
      this.apipost(
        "dmc_post_B2BAndB2CGetDidaHotelPage",
        this.msg,
        (res) => {
          this.$q.loading.hide();

          if (res.data.resultCode == 1) {
            this.PageCount = res.data.data.pageCount;
            this.TotalCount = res.data.data.count;
            var tempArray = res.data.data.pageData;
            if (tempArray && tempArray.length > 0) {
              tempArray.forEach(item => {
                item.productType = 6;
                item.configId = item.hotelid;
                item.images = []
                if(item.coverimg){
                  this.checkImageExists(item.coverimg, (exists) => {
                    if(exists){
                      item.images.push(item.coverimg)
                    }
                  });
                }
              });
              this.DataList = tempArray;
            }
          }
        },
        (err) => {}
      );
    },
    renderSearchInfo(condition) {
      if (!condition.length) {
        return;
      }
      let areaInfo = condition.find((item) => item.type === 1);
      let dayInfo = condition.find((item) => item.type === 2);
      let priceInfo = condition.find((item) => item.type === 3);
      let categoryInfo = condition.find((item) => item.type === 4);
      // this.areaTicked = areaInfo;
      this.areaListJSONTMP = JSON.parse(JSON.stringify(this.areaListJSON));
      let tree = this.dfs(
        { Name: "", children: this.areaListJSONTMP },
        (name, depth) => {},
        ({ Id }) => {
          return areaInfo.includes(Id);
        }
      );
      tree = this.dfs(
        tree,
        (name, depth) => {},
        ({ Id }) => {
          return areaInfo.includes(Id);
        }
      );
      tree = this.dfs(
        tree,
        (name, depth) => {},
        ({ Id }) => {
          return areaInfo.includes(Id);
        }
      );
      this.areaList = tree.children;
      const categoryTmp = JSON.parse(this.goodsTypeJSON);
      let category = this.dfs(
        { Name: "", children: categoryTmp },
        (name, depth) => {},
        (item) => {
          return categoryInfo.includes(item.Id);
        }
      );
      category = this.dfs(
        category,
        (name, depth) => {},
        (item) => {
          return categoryInfo.includes(item.Id);
        }
      );
      category = this.dfs(
        category,
        (name, depth) => {},
        (item) => {
          return categoryInfo.includes(item.Id);
        }
      );
      this.goodsType = category.children;
      // this.ticked = categoryInfo;
      this.priceModel = { min: priceInfo.StartPrice, max: priceInfo.EndPrice };
      // this.msg.priceRange = {
      //   min: priceInfo.StartPrice,
      //   max: priceInfo.EndPrice,
      // };
      let arr = [];
      dayInfo.forEach((item) => {
        if (item < 6) {
          arr.push(item);
        } else if (item === 7 || item === 8) {
          arr.push(7);
        } else if (item === 8 || item === 10) {
          arr.push(8);
        } else {
          arr.push(9);
        }
      });
      // arr = [... new Set(arr)]
      // this.dayArray.forEach(item => {
      //   if(arr.includes(item.id)) {
      //     item.checked = true
      //   }
      // })
      this.dayArray = this.dayArray.filter((item) => arr.includes(item.id));
      // this.msg.dayNumList = arr;
    },
    GotoDetails(item) {
      item.CheckInDate = this.msg.StartDate
      item.CheckOutDate = this.msg.EndDate
      this.CommonJump(item, {}, "blank");
    },
  },
};
</script>

<style>
.KeyCityBox div:hover{
  color: var(--q-color-primary);
  
}
.KeyCityBox div:hover{
  text-decoration: solid;
  opacity: .8;
}
.addr-list:hover {
  background: #E3F2FD;
}
</style>
<style lang="scss" scoped>
::v-deep .q-menu {
  width: 100% !important;
}
.price-stuff {
  font-size: 12px;
  margin-left: 4px;
}
.nav-item {
  width: 25%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background: #fff;
  font-weight: bold;
}
.nav-item:hover {
  background: #f5f5f5;
}
.CountryKkday{
  color: #666;
  font-family: Roboto, Arial,微軟正黑體修正, 微軟正黑體, "Microsoft JhengHei","Microsoft JhengHei UI", sans-serif;
}
.CountryKkday:hover {
  background: #fff;
}

::v-deep .CountryKkday .addr-list{
  background: rgba(225,225,225,0);
}
::v-deep .CountryKkday .addr-list:hover{
  background: rgba(225,225,225,0);
}
body.desktop .CountryKkday .g-hoverable:hover >.g-focus-helper{
  background: rgba(0,0,0,0);
}
.CityNameBox-r-kkday{
  border-radius: 3px;
  text-overflow: ellipsis;

}
.CityNameBox-r-kkday:hover{
    background: rgba(5,32,50,.2);
    color: var(--q-color-primary);
}
.CityNameBox-r-kkday.active{
  background: rgba(5,32,50,1);
  color: #fff;
}
</style>
