<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="flex">
       <div @click="showAddress = true" class="nav-item col">目的地<i class="iconfont iconarrowdown text-grey-6" style="margin-top: 3px; margin-left:4px"></i></div>
       <div @click="showCategory = true" class="nav-item col">商品類別<i class="iconfont iconarrowdown text-grey-6" style="margin-top: 3px; margin-left:4px"></i></div>
       <div @click="showVisa = true" class="nav-item col">次数<i class="iconfont iconarrowdown text-grey-6" style="margin-top: 3px; margin-left:4px"></i></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>
        <q-input
          v-model="searchAdd.name"
          type="text"
          standout
          placeholder="搜尋目的地"
          class="q-ma-md"
          @input="changeAddrSearchHandler"
        />
        <q-scroll-area style="height: 200px; width: 100%;">
          <div
              class="addr-list q-px-md q-py-sm row items-center"
              v-for="(y, yi) in areaList"
              :key="yi"
            >
              <q-checkbox
                v-model="y.checked"
                size="xs"
                @input="changeVisaHandler(1,y)"
              />
              <span
                class="col text-grey-8 text-subtitle2 text-regular q-mt-xs"
                style="font-weight: 400"
              >
                {{ y.CountryName }}
              </span>
          </div>
        </q-scroll-area>
          
      </q-card>
      </popup>

      <popup mode="top" v-model="showCategory">
      <q-card flat class="rounded-borders q-py-md">
        <div class="text-subtitle1 text-weight-bold q-mx-md">所有商品類別</div>
        <div
              class="addr-list q-px-md q-py-sm row items-center"
              v-for="(y, yi) in goodsType"
              :key="yi"
            >
              <q-checkbox
                v-model="y.checked"
                size="xs"
                @input="changeVisaHandler(2,y)"
              />
              <span
                class="col text-grey-8 text-subtitle2 text-regular q-mt-xs"
                style="font-weight: 400"
              >
                {{ y.Name }}
              </span>
          </div>
      </q-card>
    </popup>
    <popup mode="top" v-model="showVisa">
      <q-card flat class="rounded-borders q-py-md">
        <div class="text-subtitle1 text-weight-bold q-mx-md">次数</div>
        <div
            class="addr-list q-px-md q-py-sm row items-center"
            v-for="(y, yi) in visaArray"
            :key="yi"
          >
            <q-checkbox
              v-model="y.checked"
              size="xs"
              @input="changeVisaHandler(3,y)"
            />
            <span
              class="col text-grey-8 text-subtitle2 text-regular q-mt-xs"
              style="font-weight: 400"
            >
              {{ y.Name }}
            </span>
          </div>
      </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>
        <q-input
          v-model="searchAdd.name"
          type="text"
          standout
          placeholder="搜尋目的地"
          class="q-ma-md"
          @input="changeAddrSearchHandler"
        />
        <q-expansion-item
          expand-separator
          label="目的地"
          default-opened
          class="text-weight-bold rounded-borders"
        >
          <div
              class="addr-list q-px-md q-py-sm row items-center"
              v-for="(y, yi) in areaList"
              :key="yi"
            >
              <q-checkbox
                v-model="y.checked"
                size="xs"
                @input="changeVisaHandler(1,y)"
              />
              <span
                class="col text-grey-8 text-subtitle2 text-regular q-mt-xs"
                style="font-weight: 400"
              >
                {{ y.CountryName }}
              </span>
          </div>
        </q-expansion-item>
        
      </q-card>
      <q-card flat class="rounded-borders q-py-md q-mt-lg">
        <div class="text-subtitle1 text-weight-bold q-mx-md">所有商品類別</div>
        <div
              class="addr-list q-px-md q-py-sm row items-center"
              v-for="(y, yi) in goodsType"
              :key="yi"
            >
              <q-checkbox
                v-model="y.checked"
                size="xs"
                @input="changeVisaHandler(2,y)"
              />
              <span
                class="col text-grey-8 text-subtitle2 text-regular q-mt-xs"
                style="font-weight: 400"
              >
                {{ y.Name }}
              </span>
          </div>
        
      </q-card>
      <q-card flat class="rounded-borders q-py-md q-mt-lg overflow-hidden">
        <div class="text-subtitle1 text-weight-bold q-mx-md">次数</div>
        <div
            class="addr-list q-px-md q-py-sm row items-center"
            v-for="(y, yi) in visaArray"
            :key="yi"
          >
            <q-checkbox
              v-model="y.checked"
              size="xs"
              @input="changeVisaHandler(3,y)"
            />
            <span
              class="col text-grey-8 text-subtitle2 text-regular q-mt-xs"
              style="font-weight: 400"
            >
              {{ y.Name }}
            </span>
          </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.orderBy != x.value ? 'dark' : 'white'"
            :class="{
              'bg-grey-3': msg.orderBy != x.value,
              'bg-primary': msg.orderBy == x.value,
            }"
            v-for="(x, i) in sortArray"
            :key="i"
            @click="chosenSortHandler(x)"
            >{{ x.label }}</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.newCoverImg"
            :ratio="1"
            spinner-color="grey"
            spinner-size="20px"
            :width="$q.platform.is.desktop ? '272px' : ''"
            :height="$q.platform.is.desktop ? '177px' : '200px'"
            class="bg-grey-3"
          />
          <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="x.entryType==1?'单次':x.entryType==2?'多次':''"
                /> -->
                <q-chip
                  v-if="x.visaType"
                  style="background: #26a69a1a"
                  size="sm"
                  class="f12 rounded-borders text-secondary"
                  :label="x.visaType==1?'个签':x.visaType==2?'团签':''"
                />
                <template v-if="x.typeTagList&&x.typeTagList.length>0">
                  <template v-for="item in x.typeTagList">
                    <q-chip v-if="item.tagTame!=''"
                      style="background: #26a69a1a"
                      size="sm"
                      class="f12 rounded-borders text-secondary"
                      :label="item.tagTame"
                    />
                  </template>
                </template>
                <template v-if="x.productTagList&&x.productTagList.length>0">
                  <template v-for="item in x.productTagList">
                    <q-chip v-if="item.tagTame!=''"
                      style="background: #26a69a1a"
                      size="sm"
                      class="f12 rounded-borders text-secondary"
                      :label="item.tagTame"
                    />
                  </template>
                </template>
                <template v-if="x.featureTagList&&x.featureTagList.length>0">
                  <template v-for="item in x.featureTagList">
                    <q-chip v-if="item.tagTame!=''"
                      style="background: #26a69a1a"
                      size="sm"
                      class="f12 rounded-borders text-secondary"
                      :label="item.tagTame"
                    />
                  </template>
                </template>
              </div>
              <div v-if="x.sendCityName||x.manageDuration" class="row items-center f12 text-grey-6 q-mt-md">
                <template v-if="x.sendCityName">
                  <span class="text-grey-9">送签地：</span>
                  <span class="q-mr-lg">{{ x.sendCityName }}</span>
                </template>
                <template v-if="x.manageDuration">
                  <span class="tetx-grey-9">办理时长：</span>{{ x.manageDuration }}个工作日
                </template>
              </div>
            </div>
            <div class="row items-end">
              <div class="col f12">
                <template v-if="x.bookAdvance">
                  <span>提前</span>
                  <span class="q-px-xs text-secondary text-weight-bold"
                    >{{ x.bookAdvance }} 天</span
                  >预定
                </template>
              </div>
              <div class="text-h6 product-price">
                CNY：{{ x.visaB2CPrice }}<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.Name">\"{{ msg.Name }}\"</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";
export default {
  props: ["qMsg"],
  components: {popup},
  data() {
    return {
      showAddress: false,
      showCategory: false,
      showDate: false,
      showPrice: false,
      areaTicked: [],
      ticked: [],
      selected: [],
      searchAdd: {
        name: "",
        value: 0,
      },
      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: 30000,
      },
      visaArray: [],
      showVisa: false,
    };
  },
  created() {
    this.msg = this.qMsg;
    // this.initAreaList();
    this.initGoods();
    this.dayArray.forEach((x) => {
      x.checked = false;
    });
    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 };
    this.goSearchHandler();
  },
  mounted() {
      this.areaTicked = this.msg.areaId ? [this.msg.areaId] : (this.msg.areaIds ? this.msg.areaIds : []);
    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;
    }
    this.getEnumeration()
  },
  methods: {
    getEnumeration(){
      let jObj = JSON.parse(window.localStorage.getItem("groupinfo"));
      this.apipost(
        "b2c_get_GetVisaProductSelect",
        {GroupId:jObj.GroupId},
        (res) => {
          if (res.data.resultCode == 1) {
            let arrList = function(list){
              list.forEach(x=>{
                x.checked = false
              })
            }
            arrList(res.data.data.Country)
            arrList(res.data.data.EntryTypeList)
            arrList(res.data.data.VisaTypeList)
            this.areaList = res.data.data.Country
            this.goodsType = res.data.data.VisaTypeList
            this.visaArray = res.data.data.EntryTypeList
          }
        },
        (err) => {}
      );
    },
    handleSelected(target) {
      
    },
    handleTicked(target) {
      this.msg.pageIndex = 1
      this.ticked = target;
      this.goSearchHandler();
    },
    handleAreaTicked(target) {
      this.msg.pageIndex = 1
      this.areaTicked = target;
      
      this.goSearchHandler();
    },
    initAreaList() {
      let jObj = JSON.parse(window.localStorage.getItem("baseifo"));
      let arr = [];
      jObj.AreaList.forEach((x) => {
        x.children = x.SubList;
        x.children.forEach((y) => {
          y.checked = false;
          y.explsed = false;
          y.isShow = true;
          if (y.Id === this.msg.areaId) {
            arr.push(y.Id);
          }
          if (y.SubList) {
            y.children = y.SubList;
            y.children.forEach((z) => {
              z.checked = false;
              z.explsed = false;
              z.isShow = true;
              if (z.Id === this.msg.areaId) {
                arr.push(z.Id);
              }
              if (y.Id === this.msg.areaId) {
                arr.push(z.Id);
              }
            });
          }
        });
        this.areaList = jObj.AreaList;
        this.areaListJSON = JSON.parse(JSON.stringify(this.areaList));
      });

      if (this.msg.areaId) {
        this.$nextTick(() => {
          this.$refs.area?.setTicked([...new Set(arr)], true);
        });
      }
    },
    changeExplesdHandler(x) {
      x.explsed = !x.explsed;
      if (x.SubList) {
      }
    },

    chosenSortHandler(x) {
      this.msg.orderBy = x.value;
      this.msg.pageIndex = 1
      this.goSearchHandler();
    },
    getChoseAddressCity() {
      let result = [];
      function treeToArray(tree) {
        return tree.reduce((res, item) => {
          const { children, ...i } = item;
          return res.concat(
            i,
            children && children.length ? treeToArray(children) : []
          );
        }, []);
      }
      const areaList = treeToArray(this.areaList);
      areaList.forEach((item) => {
        if (this.areaTicked.includes(item.Id)) {
          let arr = item.DestinationList.map((item) => item.ID);
          result = result.concat(arr);
        }
      });
      return result;
    },
    changeTripDayHandler() {
      this.$forceUpdate();
      let arr = [];
      this.dayArray.forEach((item) => {
        if (item.checked) {
          arr.push(item.id);
        }
      });
      this.msg.dayNumList = arr;
      this.msg.pageIndex = 1
      this.goSearchHandler();
    },
    changeVisaHandler(type,row){
      this.$forceUpdate();
      let arr = [];
      if(type==1){
        this.msg.VisaCountryId = ''
        this.areaList.forEach((item) => {
          if(row.checked&&row.Id==item.Id){
            this.msg.VisaCountryId = item.Id;
          }else{
            item.checked = false
          }
          if (item.checked) {
            arr.push(item.Id);
          }
        });
      }else if(type==2){
        this.msg.ManagementName = ''
        this.goodsType.forEach((item) => {
          if(row.checked&&row.Id==item.Id){
            this.msg.ManagementName = item.Name;
          }else{
            item.checked = false
          }
          if (item.checked) {
            arr.push(item.Id);
          }
        });
      }else if(type==3){
        this.msg.EntryType = 0
        this.visaArray.forEach((item) => {
          if(row.checked&&row.Id==item.Id){
            this.msg.EntryType = item.Id;
          }else{
            item.checked = false
          }
          if (item.checked) {
            arr.push(item.Id);
          }
        });
      }
      this.msg.pageIndex = 1
      this.goSearchHandler();
    },
    optionsFn(cd) {
      return (
        cd >=
        date.formatDate(date.addToDate(new Date(), { days: 1 }), "YYYY/MM/DD")
      );
    },
    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.msg.pageIndex = 1
      this.goSearchHandler();
    },
    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.areaListJSONTMP = JSON.parse(JSON.stringify(this.areaListJSON));
      let tree = this.dfs(
        { Name: "", children: this.areaListJSONTMP },
        (name, depth) => {},
        ({ Name }) => {
          return Name.indexOf(v) !== -1;
        }
      );
      tree = this.dfs(
        tree,
        (name, depth) => {},
        ({ Name }) => {
          return Name.indexOf(v) !== -1;
        }
      );
      tree = this.dfs(
        tree,
        (name, depth) => {},
        ({ Name }) => {
          return Name.indexOf(v) !== -1;
        }
      );
      this.areaList = tree.children;
   
    },
    goSearchHandler() {
      this.$q.loading.show();
      this.DataList = [];
      this.PageCount = 0;
      this.TotalCount = 0;
      this.apipost(
        "b2c_get_GetB2CVisaProductList",
        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 => {
                if (item.coverImageList && item.coverImageList.length>0) {
                  try {
                    item.coverImageList = item.coverImageList.filter(item=>{
                      return item.url!=null
                    })
                    var imgArray = item.coverImageList;
                    if (imgArray && imgArray.length > 0) {
                      item.newCoverImg = imgArray[0].url;
                    } else {
                      item.newCoverImg = "";
                    }
                  } catch (e) {}
                }
              });
              this.DataList = tempArray;
              this.$forceUpdate();
            }
          }
        },
        (err) => {}
      );
    },
    GotoDetails(item) {
      this.CommonJump(
        "/detailsVisa/" + encodeURIComponent(item.id),
        {},
        "blank"
      );
    },
  },
};
</script>

<style>
.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;
}
</style>
