<template>
  <!--搜尋輪播淡出 - 中-->
  <div class="banner-style9" v-if="!hideSearch">
    <div
      class="search-content column items-center justify-center rounded-borders"
      style="border-radius: 6px"
    >
      <div>
        <div class="relative" v-if="!$q.screen.xs">
          <div
            class="row rounded-borders overflow-hidden"
            style="width: 300px"
            v-if="plugData.Title.split('^').length == 1"
          >
            <div class="col-10">
              <q-input
                filled
                square
                id="search_key"
                v-model="searchKey"
                class="bg-grey-1"
                clearable
                :label="$t('search')"
                @focus="searchFocusHandler"
                @blur="searchBlurHandler"
                @keyup.enter="searchChangeHandler"
              />
            </div>
            <div class="col-2">
              <q-btn
                dark-percentage
                color="primary"
                unelevated
                icon="search"
                style="
                  width: 100%;
                  height: 40px;
                  border-bottom-left-radius: 0;
                  border-top-left-radius: 0;
                "
                @click="goSearchHandler"
              />
            </div>
          </div>
          <div
            class="row overflow-hidden bg-white"
            style="width: 640px; margin: 0 auto; border-radius: 5px"
            v-if="
              plugData.Title.split('^').length > 1 &&
              plugData.Title.split('^')[1] == 'ns1'
            "
          >
            <q-input
              filled
              square
              id="search_key"
              v-model="searchKey"
              class="bg-grey-1 col"
              clearable
              label="搜尋目的地、景點、行程觀光或酒店名稱..."
              @focus="searchFocusHandler"
              @blur="searchBlurHandler"
              @keyup.enter="goSearchHandler"
            />
            <q-btn
              dark-percentage
              color="primary"
              style="border-radius: 0"
              class="col-2"
              unelevated
              icon="search"
              @click="goSearchHandler"
            />
          </div>
          <div
            v-show="showSplitPannel"
            id="sb"
            transition-show="fade"
            elevated
            transition-hide="scale"
            class="showbox column"
            style="z-index: 9;"

          >
            <div class="q-px-sm q-pt-sm" v-if="historys.length>0">
              <div class="q-mb-sm text-weight-bold">歷史搜索</div>
                <div class="row">
                  <div class="col overflow-hidden" style="height:36px">
                    <template v-for="(x,i) in historys">
                    <q-chip v-if="x" style="background:#f6f7f9;" @click="goSearchHandler(x)" clickable text-color="dark" class="cursor-pointer" :label="x" :key="i" /></template>
                  </div>
                  <q-btn text-color="grey-6" icon="delete" class="q-py-none" dense size="sm" flat @click="clearHistorys">
                    <q-tooltip class="bg-dark" co>清空歷史</q-tooltip>
                  </q-btn>
                </div>
            </div>
            <div class="column">
              <div class="text-weight-bold q-pa-sm">熱門目的地</div>
              <q-separator />
              <div class="flex flex-wrap">
                <q-scroll-area class="w-full" style="height: 305px;" 
                  :thumb-style="{
                    right: '2px',
                    borderRadius: '5px',
                    backgroundColor: 'rgba(0, 0, 0, .1)',
                    width: '5px',
                    opacity: '0.75'
                  }"
                  :content-style="{
                    backgroundColor: 'rgba(0, 0, 0, 0)',
                    color: '#555'
                  }"
                  :content-active-style="{
                    backgroundColor: 'rgba(0, 0, 0, 0)',
                    color: 'black'
                  }">
                  <div class="flex flex-wrap">
                    <div class="hot-tag" @click="handleHotTagClick(item)" :class="{'hot-tag-select': setectHotTag === item.Id}" :key="item.Id" v-for="item in hotList">{{item.Name}}</div>
                  </div>
                </q-scroll-area>
              </div>
            </div>
          </div>
        </div>
        <div class=" bg-white q-px-md" v-if="$q.screen.xs" @click="showPopupHandler">
          <i class="iconfont iconchazhao"></i>
              <!-- <q-icon name="search" /> -->
          <!-- <q-input
            filled
            v-model="searchKey"
            class="bg-grey-1 q-mx-md"
            :label="$t('search')"
            readonly="readonly"
            @click="showPopupHandler"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input> -->
        </div>
      </div>
    </div>
    <popup
      v-model="showPopup"
      mode="top"
      :safeAreaInsetBottom="true"
      border-radius="5"
    >
      <div class="chosen-box">
        <div class="title">搜尋行程</div>
        <div class="chosen-tab">
          <q-tabs
            v-model="tab"
            align="justify"
            narrow-indicator
            class="q-mb-md"
          >
            <q-tab class="text-purple" name="dest" label="目的地" />
            <q-tab class="text-teal" name="kw" label="關鍵字" />
          </q-tabs>
          <div v-show="tab == 'dest'">

      <q-card flat class="rounded-borders q-py-md">
        <div class="text-subtitle1 text-weight-bold q-mx-md">篩選目的地</div>
        <!-- <q-input
          v-model="searchAdd.name"
          type="text"
          standout
          placeholder="搜尋目的地、景點、行程觀光或酒店名稱..."
          class="q-ma-md"
          @input="changeAddrSearchHandler"
        /> -->
        <q-tree
          ref="area"
          :nodes="areaList"
          no-connectors
          node-key="Id"
          label-key="Name"
          tick-strategy="leaf"
          @update:ticked="handleAreaTicked"
          @update:selected="handleAreaSelected"
          :ticked="areaTicked"
          text-color="#666"
          no-nodes-label=" "
          no-results-label=" "
        />
      </q-card>
            <!-- <div class="q-mb-md">
              <q-select
                filled
                v-model="chosenResult.fl"
                :options="areas"
                option-label="Name"
                option-value="Name"
                label="請選擇地區"
              />
            </div>
            <div class="q-mb-md" v-if="chosenResult.fl.SubList">
              <q-select
                filled
                v-model="chosenResult.sl"
                :options="chosenResult.fl.SubList"
                option-label="Name"
                option-value="Name"
                label="請選擇地區"
              />
            </div>
            <div class="q-mb-md" v-if="chosenResult.sl.SubList">
              <q-select
                filled
                v-model="chosenResult.tl"
                :options="chosenResult.sl.SubList"
                option-label="Name"
                option-value="Name"
                label="請選擇地區"
              />
            </div>
            <div class="q-mb-md" v-if="chosenResult.tl.SubList">
              <q-select
                filled
                v-model="chosenResult.ful"
                :options="chosenResult.tl.SubList"
                option-label="Name"
                option-value="Name"
                label="請選擇地區"
              />
            </div> -->
          </div>
          <div v-show="tab == 'kw'" class="q-mb-md">
            <q-input
              filled
              id="search_key"
              v-model="searchKey"
              class="bg-grey-1"
              :label="$t('search')"
            />
          </div>
          <div class="q-mb-md row">
            <div class="col">
              <q-input
                filled
                v-model="searchDate"
                :label="$t('search_date_begin')"
                mask="date"
                class="bg-grey-1"
              >
                <template v-slot:append>
                  <q-icon name="event" class="cursor-pointer">
                    <q-popup-proxy ref="qS3DateProxy">
                      <q-date
                        mask="YYYY-MM-DD"
                        :title="$t('search_date_begin')"
                        subtitle="選擇"
                        v-model="searchDate"
                        @input="() => $refs.qS3DateProxy.hide()"
                      />
                    </q-popup-proxy>
                  </q-icon>
                </template>
              </q-input>
            </div>
            <div class="split-word bg-grey-3 q-pl-xs q-pr-xs">至</div>
            <div class="col">
              <q-input
                filled
                v-model="searchEndDate"
                :label="$t('search_date_end')"
                mask="date"
                class="bg-grey-1"
              >
                <template v-slot:append>
                  <q-icon name="event" class="cursor-pointer">
                    <q-popup-proxy ref="qS4DateProxy">
                      <q-date
                        mask="YYYY-MM-DD"
                        :title="$t('search_date_begin')"
                        subtitle="選擇"
                        v-model="searchEndDate"
                        @input="() => $refs.qS4DateProxy.hide()"
                      />
                    </q-popup-proxy>
                  </q-icon>
                </template>
              </q-input>
            </div>
          </div>
          <div>
            <q-btn
              color="primary"
              unelevated
              style="width: 100%"
              filled
              label="搜尋"
              @click="goSearchHandler"
            />
          </div>
        </div>
      </div>
    </popup>
  </div>
</template>

<script>
import { date } from "quasar";
//搜尋輪播淡出 - 中
import popup from "../props/index";
export default {
  props: ["plugData"],
  components: {
    popup,
  },
  data() {
    return {
      areaTicked: [],
      areaList: [],
      setectHotTag: '',
      hotList: [],
      slide: 0,
      searchKey: "",
      searchDate: "",
      searchEndDate: "",
      showSplitPannel: false,
      thumbStyle: {
        right: "4px",
        borderRadius: "5px",
        backgroundColor: "#027be3",
        width: "5px",
        opacity: 0.75,
      },
      barStyle: {
        right: "2px",
        borderRadius: "9px",
        backgroundColor: "#027be3",
        width: "9px",
        opacity: 0.2,
      },
      areas: [],
      crtAreaIndex: 0,
      showPopup: false,
      tab: "dest",
      historys:[],
      chosenResult: {
        fl: "",
        sl: "",
        tl: "",
        ful: "",
      },
      RB_Group_Id: 0,
      hideSearch: false,
    };
  },
  created() {
  },
  mounted() {
    this.isSearch = this.$router.history.current.path === "/search"||this.$router.history.current.path === "/searchProduct"
    ||this.$router.history.current.path === "/searchVisa"||this.$router.history.current.path === "/planeticket";
    this.initAreaList()
    var jObj = JSON.parse(window.localStorage.getItem('baseifo'));
    const hotList = this.getHotList(jObj.AreaList)
    this.hotList = hotList
    this.getHistory()
    var newStartDate = new Date();
    var newStartDateStr = this.formatDate(
      newStartDate.getFullYear(),
      newStartDate.getMonth() + 1,
      newStartDate.getDate()
    );
    var newEndDate = this.AddMonth(newStartDateStr, 2);
    var newEndDateStr = this.formatDate(
      newEndDate.getFullYear(),
      newEndDate.getMonth() + 1,
      newEndDate.getDate()
    );
    this.searchDate = newStartDateStr;
    this.searchEndDate = newEndDateStr;

    this.$root.$emit("change-head-style", 2);
    document.addEventListener("click", this.clickHandler);
    var jObj = JSON.parse(localStorage.getItem("groupinfo"));
    this.RB_Group_Id = jObj.GroupId;
    if (localStorage.baseifo) {
      var jObj = JSON.parse(localStorage.baseifo);
      this.areas = jObj.AreaList;
    } else {
      this.getAera();
    }
  },
  beforeDestroy() {
    document.removeEventListener("click", this.clickHandler);
  },
  watch: {
    '$route': {
      handler(to, from) {
        if(to.path.indexOf('searchdida')!=-1||to.path.indexOf('searchDida')!=-1||to.path.indexOf('detailHotalDida')!=-1){
          this.getHotalHotList()
          this.hideSearch = true
        }else{
          var jObj = JSON.parse(window.localStorage.getItem('baseifo'));
          const hotList = this.getHotList(jObj.AreaList)
          this.hotList = hotList
          this.hideSearch = false
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getHistory() {
      let historys = JSON.parse(localStorage.getItem("searchHistory")) || [];
      this.historys = historys;
    },
    clearHistory() {
      localStorage.removeItem("searchHistory");
      this.historys = [];
      
    }
  },
  computed: {},
  methods: {
    handleAreaTicked(target) {
         this.areaTicked = target
    },
    handleAreaSelected(target) {
      
    },
    initAreaList() {
      let jObj = JSON.parse(window.localStorage.getItem("baseifo"));
      let arr = [];
      jObj.AreaList.forEach((x) => {
        x.selectable = false
        x.children = x.SubList;
        x.children.forEach((y) => {
          y.checked = false;
          y.explsed = false;
          y.isShow = true;
          if (y.SubList) {
        y.selectable = false
            y.children = y.SubList;
            y.children.forEach((z) => {
              z.checked = false;
              z.explsed = false;
              z.isShow = true;
            });
          }
        });
        this.areaList = jObj.AreaList;
        this.areaListJSON = JSON.parse(JSON.stringify(this.areaList));
      });
    },
    getHotList(arr) {
      let hotArr = [];
      arr.forEach(item => {
        if (item.SubList && item.SubList.length) {
          hotArr = hotArr.concat(this.getHotList(item.SubList));
        } else {
          if (item.IsHot === 1) {
            hotArr.push(item);
          }
        }
      });
      return hotArr;
    },
    getHotalHotList() {
      let hotArr = [];
      this.apipost(
      "dmc_post_B2BAndB2CGetHotCity", {},
      res => {
        if (res.data.resultCode == 1) {
          let arr = res.data.data
          arr.forEach((item,index) => {
            if(!index){
              item.Name = item.GName
              if (item.CityList && item.CityList.length) {
                item.CityList.forEach((x) => {
                  x.Name = x.CityName
                  x.Id = x.CityCode
                })
                hotArr = hotArr.concat(item.CityList);
              } else {
                if (item.IsHot === 1) {
                  item.Name = item.CityName
                  item.Id = item.CityCode
                  hotArr.push(item);
                }
              }
            }
          });
          this.hotList = hotArr;
        }
      })
    },
    handleHotTagClick(item) {
      this.setectHotTag = item.Id
      let qsearchDate = this.searchDate
      let qsearchEndDate = this.searchEndDate
      let val = item.Name
      if(val!='' && typeof val == 'string'){
        this.searchKey=val
      }
      // this.historys=Array.from(new Set([this.searchKey].concat(this.historys)))
      // localStorage['recent_search'] = JSON.stringify(this.historys)
      var currentUrl = window.location.href;
      let urlName="/search";

      // let currentUrlArr = currentUrl.split('/')
      // let urlType = currentUrlArr[4].split('?')[0]
      // if(urlType){
      //   urlName = `/${urlType}`
      //   if(urlType=='searchProduct'){
      //     urlName = `/search`
      //   }else if(urlType=='detailsVisa'){
      //     urlName = `/searchVisa`
      //   }else if(urlType=='searchDida'||urlType=='searchDida'||urlType=='detailHotalDida'){
      //     qsearchDate  = date.formatDate(date.addToDate(new Date(), { days: 8 }), "YYYY/MM/DD")
      //     qsearchEndDate  = date.formatDate(date.addToDate(new Date(), { days: 9 }), "YYYY/MM/DD")
      //     if(urlType=='detailHotalDida') urlName = `/searchDida`
      //   }
      // }
      if(currentUrl.includes('/#/searchProduct')){
        urlName="/searchProduct";
      }else if(currentUrl.includes('/#/planeticket')){
        urlName="/planeticket";
      }else if(currentUrl.includes('/#/searchVisa')){
        urlName="/searchVisa";
      }else if(currentUrl.includes('/#/searchdida')||currentUrl.includes('/#/searchDida')||currentUrl.includes('/#/detailHotalDida')){
        urlName="/searchdida";
        qsearchDate  = date.formatDate(date.addToDate(new Date(), { days: 8 }), "YYYY/MM/DD")
        qsearchEndDate  = date.formatDate(date.addToDate(new Date(), { days: 9 }), "YYYY/MM/DD")
      }

      if(urlName=='/searchVisa'||urlName=='/planeticket'){
        this.CommonJump(urlName, {
          Name: this.searchKey,
          VisaCountryId: item.Id
        });
      }else{
        this.CommonJump(urlName, {
          qsearchKey: this.searchKey,
          qsearchDate,
          qsearchEndDate,
          areaId: item.Id,
          areaName: item.Name
        });
      }
      if(this.isSearch) {
        window.location.reload()
      }
    },
    //获取地区数据
    getAera() {
      this.apipost(
        "ws_get_GetSearchArea",
        {
          RB_Group_Id: this.RB_Group_Id,
        },
        (res) => {
          if (res.data.resultCode == 1) {
            if (res.data.data) {
              this.areas = res.data.data.AreaList;
            }
          }
        },
        (err) => {}
      );
    },
    getHistory(){
      this.historys =JSON.parse(localStorage['recent_search']??'[]')
    },
    showPopupHandler() {
      this.showPopup = true;
    },
    clickHandler(e) {
      try {
        if (!document.querySelector("#sb").contains(e.target)) {
          this.showSplitPannel = false;
        }
      } catch (error) {}
    },
    clickSlideHandler(url) {
      if (url && url.length > 1) {
        location.href = url;
      }
    },
    searchFocusHandler() {
      if (this.searchKey == "") {
        setTimeout(() => {
          this.showSplitPannel = true;
        }, 200);
      }
    },
    searchBlurHandler() {
      //this.showSplitPannel = false;
    },
    clkAreaHandler(i) {
      this.crtAreaIndex = i;
    },
    searchChangeHandler() {
      if (this.searchKey == "") {
        this.showSplitPannel = true;
      } else {
        this.showSplitPannel = false;
      }
    },
    chosenAreaHandler(name) {
      this.searchKey = name;
      this.showSplitPannel = false;
    },
    //跳转到搜索页面
    goSearchHandler(val='') {
      if(val!='' && typeof val == 'string'){
        this.searchKey=val
        this.historys=Array.from(new Set([this.searchKey].concat(this.historys)))
        localStorage['recent_search'] = JSON.stringify(this.historys)
      }
      let qsearchDate = this.searchDate
      let qsearchEndDate = this.searchEndDate
      var currentUrl = window.location.href;
      let urlName="/search";
      
      // let currentUrlArr = currentUrl.split('/')
      // let urlType = currentUrlArr[4].split('?')[0]
      // if(urlType){
      //   urlName = `/${urlType}`
      //   if(urlType=='searchProduct'){
      //     urlName = `/search`
      //   }else if(urlType=='detailsVisa'){
      //     urlName = `/searchVisa`
      //   }else if(urlType=='searchDida'||urlType=='searchDida'||urlType=='detailHotalDida'){
      //     qsearchDate  = date.formatDate(date.addToDate(new Date(), { days: 8 }), "YYYY/MM/DD")
      //     qsearchEndDate  = date.formatDate(date.addToDate(new Date(), { days: 9 }), "YYYY/MM/DD")
      //     if(urlType=='detailHotalDida') urlName = `/searchDida`
      //   }
      // }
      if(currentUrl.includes('/#/searchProduct')){
        urlName="/searchProduct";
      }else if(currentUrl.includes('/#/planeticket')){
        urlName="/planeticket";
      }else if(currentUrl.includes('/#/searchVisa')){
        urlName="/searchVisa";
      }else if(currentUrl.includes('/#/searchdida')||currentUrl.includes('/#/searchDida')||currentUrl.includes('/#/detailHotalDida')){
        urlName="/searchdida";
        qsearchDate  = date.formatDate(date.addToDate(new Date(), { days: 8 }), "YYYY/MM/DD")
        qsearchEndDate  = date.formatDate(date.addToDate(new Date(), { days: 9 }), "YYYY/MM/DD")
      }

      if(urlName=='/searchVisa'||urlName=='/planeticket'){
        this.CommonJump(urlName, {
          Name: this.searchKey,
          VisaCountryIds: this.areaTicked.join(',')
        });
      }else{
        this.CommonJump(urlName, {
          qsearchKey: this.searchKey,
          areaIds: this.areaTicked.join(','),
          qsearchDate,
          qsearchEndDate,
        });
      }
      
      this.showSplitPannel = false
      if(this.isSearch) {
        window.location.reload()
      }
    },
    clearHistorys(){
      this.historys =[]
      localStorage['recent_search'] = JSON.stringify(this.historys)
    }
  },
};
</script>

<style>
.banner-style9 {
  /* margin-top: 0px; */
  /* position: relative; */
  /* overflow: hidden; */
  border-radius: 5px;
}

.banner-style9 .search-content {
  /* position: absolute; */
  /* top: 0;
  left: 0;
  right: 0;
  bottom: 0; */
  z-index: 2;
  /* transform: translate(-50%, -50%); */
  /* margin-top: 40px; */
  background: rgb(0, 0, 0, 0.1);
}

.banner-style9 .search-content .search-title {
  margin: 0 auto;
  max-width: 520px;
  color: #fff;
  width: 80%;
  font-weight: 600;
}

.banner-style9 .search-content .search-title .title {
  margin-bottom: 10px;
  font-size: 36px;
  line-height: 1.2;
  text-align: center;
  letter-spacing: 1px;
}

.banner-style9 .search-content .search-title .sub-title {
  margin-bottom: 30px;
  font-size: 18px;
  text-align: center;
  letter-spacing: 1px;
}

.banner-style9 .showbox {
  position: absolute;
  box-sizing: border-box;
  width: 650px !important;
  height: 345px;
  background: #fff;
  left: 0;
  top: 60px;
  box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.3), 0px 0px 20px rgba(0, 0, 0, 0.1);
}

.banner-style9 .showspbox {
  position: absolute;
  box-sizing: border-box;
  width: calc(41.6667% - 22px);
  height: 345px;
  background: #fff;
  left: 0;
  top: 185px;
  box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.3), 0px 0px 20px rgba(0, 0, 0, 0.1);
}

.my-menu-link {
  background-color: rgb(237, 237, 237) !important;
}

.area-box .h3 {
  font-size: 22px;
  color: #333;
  font-weight: 600;
  padding: 0;
  height: unset;
  list-style: unset;
  margin: 0;
  cursor: pointer;
}

.area-box .h4 {
  font-size: 18px;
  color: #424242;
  padding: 0;
  height: unset;
  list-style: unset;
  margin: 0;
  margin-right: 20px;
  font-weight: 600;
  cursor: pointer;
}

.area-box .h5 {
  font-size: 16px;
  color: #636363;
  padding: 0;
  height: unset;
  list-style: unset;
  margin: 0;
  margin-right: 12px;
  cursor: pointer;
}

.area-box .h6 {
  font-size: 14px;
  color: gray;
  padding: 0;
  height: unset;
  list-style: unset;
  margin: 0;
  text-align: right;
  cursor: pointer;
}

.area-box .h6:hover,
.area-box .h5:hover,
.area-box .h4:hover,
.area-box .h3:hover {
  color: var(--q-color-primary);
}

.area-box .to-end {
  align-items: flex-end;
}

.chosen-box {
  padding: 15px;
  min-height: 30vh;
}

.chosen-box .title {
  font-size: 20px;
  font-weight: 600;
  color: #111;
  margin-bottom: 5px;
}

.chosen-box .split-word {
  font-size: 15px;
  color: #333;
  line-height: 40px;
}
</style>
<style lang="scss" scoped>
.hot-tag {
  width: 141px;
  height: 34px;
  line-height: 34px;
  padding-left: 8px;
  border-radius: 8px;
  margin: 12px 0 12px 12px;
  cursor: pointer;
}
.hot-tag-select {
  text-align: center;
  background: $secondary;
  color: #fff;
}
::v-deep .q-field__control {
  height: 40px;
}
::v-deep .q-field__control-container {
  height: 40px;
}
::v-deep .q-field--auto-height .q-field__control {
  height: 40px;
}
::v-deep .q-field__marginal {
  height: 40px;
}
::v-deep .q-field--auto-height .q-field__native {
  height: 40px;
}
::v-deep .q-field__label {
  top: 13px
}
</style>
