<template>
  <div class="row items-start q-mt-lg">
    <div class="col-3 q-mr-lg">
      <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"
        />
        <!-- <template v-for="(x, i) in areaList">
          <div class="addr" :key="i">
            <div class="addr-list q-px-md q-py-sm cursor-pointer row items-center" v-if="x.isShow">
              <q-checkbox
                indeterminate-value="half"
                @input="changeCheckHandler(x)"
                v-model="x.checked"
                size="xs"
              />
              <span class="col" @click="changeExplesdHandler(x)">
                {{
                x.Name
                }}
              </span>
              <q-icon
                @click="changeExplesdHandler(x)"
                v-if="
                  searchAdd.name.length == 0 ||
                  (searchAdd.name.length > 0 && x.isShowChild)
                "
                :name="!x.explsed ? 'keyboard_arrow_down' : 'keyboard_arrow_up'"
                size="20px"
              />
            </div>
            <div
              class="q-mx-md"
              v-if="
                x.explsed ||
                (x.SubList && x.isShowChild && searchAdd.name.length > 0)
              "
            >
              <template v-for="(y, yi) in x.SubList">
                <div class="addr-list q-px-md q-py-sm row items-center" :key="yi" v-if="y.isShow">
                  <q-checkbox @input="changeCheckHandler(y, x)" v-model="y.checked" size="xs" />
                  <span class="col">{{ y.Name }}</span>
                </div>
              </template>
            </div>
          </div>
        </template> -->
        
        <q-tree
          ref="area"
          :nodes="areaList"
          no-connectors
          node-key="Id"
          label-key="Name"
          tick-strategy="leaf"
          @update:ticked="handleAreaTicked"
          :ticked="areaTicked"
        />
      </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>
        <q-tree
          ref="category"
          :nodes="goodsType"
          no-connectors
          node-key="Id"
          label-key="CategoryName"
          tick-strategy="leaf"
          @update:ticked="handleTicked"
          :ticked="ticked"
        />
        <!-- <div class="add q-mt-md" v-for="(x, i) in goodsType" :key="i">
          <div class="addr-list q-px-md q-py-sm cursor-pointer row items-center">
            <span class="col" @click="changeExplesdHandler(x)">
              {{
              x.CategoryName
              }}
            </span>
            <q-icon
              @click="changeExplesdHandler(x)"
              :name="!x.explsed ? 'keyboard_arrow_down' : 'keyboard_arrow_up'"
              size="20px"
            />
          </div>
          <div class="q-mx-md" v-if="x.explsed">
            <div
              
              v-for="(y, yi) in x.SubList"
              :key="yi"
            >
              <div class="addr-list q-px-md q-py-sm row items-center">
                <q-checkbox v-model="y.checked" size="xs" @input="changeGoodTypeHandler(y)" />
              <span class="col">{{ y.CategoryName }}</span>
            </div>
            <div class="q-mx-md" v-if="y.explsed">
              <div
                class="addr-list q-px-md q-py-sm row items-center"
                v-for="(z, zi) in y.SubList"
                :key="zi"
              >
                <q-checkbox v-model="z.checked" size="xs" @input="changeGoodTypeHandler(z)" />
                <span class="col">{{ z.CategoryName }}</span>
              </div>
            </div>
              </div>
          </div>
        </div> -->
      </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-pa-md q-mt-lg">
        <div class="text-subtitle1 text-weight-bold">價錢篩選（CNY）</div>
        <div
          class="q-mt-md text-grey-6 text-subtitle1"
        >{{ msg.priceRange.min }} - {{ msg.priceRange.max }}</div>
        <q-range
          v-model="msg.priceRange"
          :min="1"
          :max="100000"
          :step="1"
          @input="testHandler"
          color="primary"
          class="q-mt-md"
        />
      </q-card>
      <q-card flat class="rounded-borders q-mt-lg overflow-hidden">
        <q-expansion-item
          expand-separator
          label="旅程時間"
          class="text-subtitle1 text-weight-bold rounded-borders"
        >
          <div
            class="addr-list q-px-md q-py-sm row items-center"
            v-for="(y, yi) in dayArray"
            :key="yi"
          >
            <q-checkbox v-model="y.checked" size="xs" @input="changeTripDayHandler" />
            <span class="col text-grey-8" style="font-weight: 400">
              {{
              y.text
              }}
            </span>
          </div>
        </q-expansion-item>
      </q-card>
    </div>
    <div class="col q-mt-sm">
      <div class="rounded-borders bg-white q-col-gutter-sm">
        <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">
        <div
          class="rounded-borders cursor-pointer overflow-hidden q-mb-md row bg-white"
          @click="GotoDetails(x)"
          v-for="(x, i) in DataList"
          :key="i"
        >
          <q-img
            :src="x.imgCover"
            :ratio="1"
            spinner-color="grey"
            spinner-size="20px"
            width="272px"
            class="bg-grey-3"
          />
          <div class="q-pa-md col column">
            <div class="text-subtitle1 text-weight-bold text-grey-9">{{ x.title }}</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="急速確認"
                />
                <q-chip v-if="x.ltName"
                  style="background: #26a69a1a"
                  size="sm"
                  class="f12 rounded-borders text-secondary"
                  :label="x.ltName"
                />
              </div>
              <div
                class="text-subtitle2 text-grey-6 text-weight-regular ellipsis-2-lines"
                style="line-height: 1.6"
              >{{ x.productRecommend }}</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.countryName }}</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">
                <!-- <span>剩餘空位：</span>
                <span
                  class="text-primary text-weight-bold q-pr-sm q-mr-sm"
                  style="border-right: 1px solid #efefef"
                >{{ x.surplus }}</span> -->
                <span>行程天數：</span>
                <span class="text-secondary text-weight-bold">{{ x.dayNum }} 天</span>
              </div>
              <div class="text-h6 product-price">CNY：{{ x.b2CPrice }}<span class="price-stuff">元</span></div>
            </div>
          </div>
        </div>
      </div>

      <div style="display: flex; justify-content: center">
        <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 { date } from "quasar";
export default {
  props: ["qMsg"],
  data() {
    return {
      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
    };
  },
  created() {
    this.msg = this.qMsg;
    // this.msg.teamType = [];
    this.initAreaList();
    this.initGoods();
    this.msg.priceRange = {
      min: 1,
      max: 100000
    };
    this.msg.minPrice = 0;
    this.msg.maxPrice = 100000;
    this.dayArray.forEach(x => {
      x.checked = false;
    });
    this.dateRange = { from: this.msg.startDate, to: this.msg.endDate };
    this.goSearchHandler();
  },
  methods: {
    handleSelected(target) {
      console.log("handleSelected", target);
    },
    handleTicked(target) {
      console.log("handleTicked", target, this.ticked);
      this.ticked = target
      this.goSearchHandler();
    },
    handleAreaTicked(target) {
      console.log("handleAreaTicked", target, this.areaTicked);
      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))
      });
      console.log("this.areaList", this.areaList, this.msg)
      
      if(this.msg.areaId) {
        this.$nextTick(() => {
          this.$refs.area.setTicked([...new Set(arr)], true)
        })
      }
    },
    changeExplesdHandler(x) {
      x.explsed = !x.explsed;
      if (x.SubList) {
      }
    },
    // changeGoodTypeHandler(x) {
    //   if (x.checked && this.msg.teamType.indexOf(x.Id) == -1) {
    //     this.msg.teamType.push(x.Id);
    //   } else if (!x.checked && this.msg.teamType.indexOf(x.Id) != -1) {
    //     let i = this.msg.teamType.findIndex(item => item == x.Id);
    //     this.msg.teamType.splice(i, 1);
    //   }
    // },
    chosenSortHandler(x) {
      this.msg.orderBy = x.value;
      this.goSearchHandler();
    },
    changeCheckHandler(x, p = null) {
      if (p) {
        let t = p.SubList.filter(x => x.checked);
        p.checked =
          t.length == p.SubList.length ? true : t.length == 0 ? false : "half";
        this.changeChosenHandler(x);
      } else {
        x.SubList.forEach(item => {
          item.checked = x.checked;
          this.changeChosenHandler(item);
        });
      }
    },
    changeChosenHandler(x) {
      let i = this.chosenAddress.findIndex(item => item.Id == x.Id) ?? -1;
      if (!x.checked) {
        if (i > -1) {
          this.chosenAddress.splice(i, 1);
        }
      } else {
        if (i == -1) {
          this.chosenAddress.push(x);
        }
      }
      this.msg.placeIds = this.getChoseAddressCity().join(',');
      this.goSearchHandler();
    },
    getChoseAddressCity() {
      console.log("this.chosenAddress", this.chosenAddress);
      let result = [];
      this.chosenAddress.forEach(item => {
        let arr = item.DestinationList.map(item => item.ID);
        result = result.concat(arr);
      });
      console.log("getChoseAddressCity", result);
      return result;
    },
    changeTripDayHandler() {
      this.$forceUpdate();
      // this.msg.minTripDay = "0";
      // this.msg.maxTripDay = "0";
      // this.dayArray.forEach(x => {
      //   if (x.checked) {
      //     this.msg.minPrice =
      //       this.msg.minPrice > x.min ? x.min : this.msg.minPrice;
      //     this.msg.maxPrice =
      //       this.msg.maxPrice < x.max ? x.max : this.msg.maxPrice;
      //   }
      // });
      // this.msg.minTripDay =
      //   this.msg.minTripDay == "0" ? "" : this.msg.minTripDay;
      // this.msg.maxTripDay =
      //   this.msg.maxTripDay == "0" ? "" : this.msg.maxTripDay;
      let arr = []
      this.dayArray.forEach(item => {
        if(item.checked) {
          arr.push(item.id)
        }
      })
      this.msg.dayNumList = arr
      this.goSearchHandler();
    },
    optionsFn(cd) {
      return (
        cd >=
        date.formatDate(date.addToDate(new Date(), { days: 1 }), "YYYY/MM/DD")
      );
    },
    testHandler(e) {
      this.$forceUpdate();
      this.msg.minPrice = e.min;
      this.msg.maxPrice = e.max;
      this.goSearchHandler();
    },
    dateRangeHandler(e) {
      console.log('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.goSearchHandler();
    },
    initGoods() {
      let arr = []
      let jObj = JSON.parse(window.localStorage.getItem("baseifo"));
      jObj.CategoryList.forEach(x => {
        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.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);
        console.log('this.goodsType', this.goodsType, this.ticked, arr)
      });
      if(this.msg.categoryId) {
      this.$nextTick(() => {
      this.$refs.category.setTicked([...new Set(arr)], true)
      })
      }
    },
    changeAddrSearchHandler(v) {
       this.areaListJSONTMP = JSON.parse(JSON.stringify(this.areaListJSON));
      this.filterAddress(this.areaListJSON, v);
      this.filterAddress2(this.areaListJSON, 1);
      this.areaList = this.areaListJSON.filter(item => item.canFilter || item.children.length)
      console.log('areaList >>>', this.areaList)
      // this.areaList.forEach(x => {
      //   x.isShow = x.Name.indexOf(v) != -1;
      //   x.isShowChild = false;
      //   x.SubList.forEach(y => {
      //     y.isShow = y.Name.indexOf(v) != -1;
      //     if (y.isShow) {
      //       x.isShow = true;
      //       x.isShowChild = true;
      //     }
      //   });
      // });
      
    },
    filterAddress(addressList, v) {
      addressList.forEach(item => {
        if(item.Name.indexOf(v) != -1) {
          item.canFilter = true
        } else {
          item.canFilter = false
        }
        if(item.children && item.children.length) {
          this.filterAddress(item.children, v)
        }
      })
      console.log('filterAddress',this.areaListJSON, addressList)
    },
    filterAddress2(addressList, index) {
      if(index === 2) {
      addressList.forEach(item => {
        if(item.children && item.children.length) {
          item.children = item.children.filter(i => i.canFilter)
        }
      })
      }
      addressList.forEach(item => {
        if(item.children && item.children.length) {
          this.filterAddress2(item.children, 2)
        }
      })
      console.log('filterAddress2',this.areaListJSON, addressList)
    },
    goSearchHandler() {
      this.msg.webSiteCategoryIds = this.ticked.join(',')
      // this.$q.loading.show();
      this.DataList = [];
      let minTripDay = -1,
        maxTripDay = -1,
        minPrice = -1,
        maxPrice = -1;
      if (this.qMsg.minPrice != "") {
        minPrice = parseFloat(this.qMsg.minPrice);
      }
      if (this.qMsg.maxPrice != "") {
        maxPrice = parseFloat(this.qMsg.maxPrice);
        if (minPrice > maxPrice) {
          this.Error("价格区间的最低价格不能低于最大价格");
          return false;
        }
      }
      var companyId = -1;
      if (localStorage.groupinfo) {
        var groupinfo = JSON.parse(localStorage.groupinfo);
        companyId = groupinfo.siteList[0].companyId;
      }
      if (localStorage.b2bUser) {
        var b2bUser = JSON.parse(window.localStorage.getItem("b2bUser"));
        if (b2bUser) {
          this.msg.priceOrderByField = 2;
        }
      }
      this.PageCount = 0
      this.TotalCount = 0
      this.apipost(
        "b2c_get_GetB2CMergeProductPageList",
        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.imgCover && item.imgCover != "") {
              //     try {
              //       var imgArray = JSON.parse(item.imgCover);
              //       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(
        "/detail/" + encodeURIComponent(item.id) + "/" + item.tcid,
        {}
      );
    }
  }
};
</script>

<style>
.addr-list:hover {
  background: #f1416c1a;
}
</style>
<style scoped>
.price-stuff {
  font-size: 12px;
  margin-left: 4px;
}
</style>
