<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">{{$t('v103.scheduledTrip.screeningtitle')}}</div>
        <q-input
          v-model="searchAdd.name"
          type="text"
          standout
          :placeholder="$t('v103.scheduledTrip.searchinput')"
          class="q-ma-md"
          @update:model-value="changeAddrSearchHandler"
        />
        <div v-for="(x, i) in areaList" :key="i">
          <div class="addr">
            <div
              class="addr-list q-px-md q-py-sm cursor-pointer row items-center"
              v-if="x.isShow"
            >
              <q-checkbox
                indeterminate-value="half"
                @update:model-value="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
                    @update:model-value="changeCheckHandler(y, x)"
                    v-model="y.checked"
                    size="xs"
                  />
                  <span class="col">{{ y.Name }}</span>
                </div>
              </template>
            </div>
          </div>
        </div>
      </q-card>
      <q-card flat class="rounded-borders q-py-md q-mt-lg">
        <div class="text-subtitle1 text-weight-bold q-mx-md">{{$t('v103.scheduledTrip.allcommoditytype')}}</div>
        <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.Name
            }}</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
              class="addr-list q-px-md q-py-sm row items-center"
              v-for="(y, yi) in x.SubList"
              :key="yi"
            >
              <q-checkbox
                v-model="y.checked"
                size="xs"
                @update:model-value="changeGoodTypeHandler(y)"
              />
              <span class="col">{{ y.Name }}</span>
            </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="event" size="24px" />
        </div>
        <div class="row items-center justify-center col">
          <span class="text-grey-8">{{
            dateRange.from
              ? `${dateRange.from} - ${dateRange.to}`
              : $t('v103.scheduledTrip.screeningdate')
          }}</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">{{$t('v103.scheduledTrip.screeningprice')}}（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="$t('v103.scheduledTrip.journeytime')"
          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"
              @update:model-value="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>{{$t('v103.scheduledTrip.experiencetrip')}}</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">{{$t('v103.scheduledTrip.sort')}}：</span>
          <q-chip
            square
            :icon="x.icon"
            class="cursor-pointer"
            clickable
            :text-color="sortNum != x.value ? 'dark' : 'white'"
            :class="{
              'bg-grey-3': sortNum != x.value,
              'bg-primary': sortNum == 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.newCoverImg"
            :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: #E9F6F5;"
                  size="sm"
                  class="f12 rounded-borders text-secondary text-teal-7"
                  :label="$t('v103.scheduledTrip.quickconfirmation')"
                />
                <q-chip
                  style="background: #E9F6F5;"
                  size="sm"
                  class="f12 rounded-borders text-secondary text-teal-7"
                  :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="place"
                  class="q-mr-sm"
                />
                <span class="q-mr-lg">{{ x.countryName }}</span>
                <q-icon
                  size="12px"
                  name="event"
                  class="q-mr-sm"
                ></q-icon>
                <span>{{ x.startDate }}</span>
              </div>
            </div>
            <div class="row items-end">
              <div class="col f12">
                <span>{{$t('v103.scheduledTrip.residualvacancy')}}：</span>
                <span
                  class="text-primary text-weight-bold q-pr-sm q-mr-sm"
                  style="border-right: 1px solid #efefef"
                  >{{ x.surplus }}</span
                >
                <span>{{$t('v103.scheduledTrip.daysoftravel')}}：</span>
                <span class="text-secondary text-weight-bold text-teal-7"
                  >{{ x.dayNum }} {{$t('v103.scheduledTrip.day')}}</span
                >
              </div>
              <div class="text-h6 product-price">CNY：{{ x.b2CPrice }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="q-mb-md row justify-center">
        <q-pagination
          v-if="PageCount > 1"
          v-model="msg.pageIndex"
          :max="PageCount"
          @update:model-value="goSearchHandler"
          :direction-links="true"
          color="white"
          text-color="dark"
          active-color="primary"
          active-text-color="white"
          active-design="unelevated"
          unelevated
          glossy
          size="13px"
          padding="xs xs"
        >
        </q-pagination>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { date,useQuasar } from "quasar";
import { inject, reactive, toRefs, defineComponent,onMounted,ref,watch, getCurrentInstance  } from 'vue';
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { DirtionmaryHelper } from 'src/config/dictionary'
import scheduledTripService from 'src/api/scheduledTrip'
import { ApiResult } from 'src/@types/enumHelper'
import message from 'src/utils/message'
export default defineComponent({
  components: {  },
  props: [],
  setup(props) {
    const $router = useRouter()
    const { t } = useI18n()
    const $q = useQuasar()
    const qDateProxy = ref(null) as any
    let {ctx:that, proxy} = getCurrentInstance()
    
    const data= reactive({
        searchAdd: {
          name: "",
          value: 0,
        },
        areaList: [],
        chosenAddress: [],
        goodsType: [],
        dateRange: null,
        msg: null,
        qMsg: null,
        dayArray: [
          {
            id: 1,
            min: 1,
            max: 1,
            text: "1"+t('v103.scheduledTrip.day'),
          },
          {
            id: 2,
            min: 2,
            max: 2,
            text: "2"+t('v103.scheduledTrip.day'),
          },
          {
            id: 3,
            min: 3,
            max: 3,
            text: "3"+t('v103.scheduledTrip.day'),
          },
          {
            id: 4,
            min: 4,
            max: 4,
            text: "4"+t('v103.scheduledTrip.day'),
          },
          {
            id: 5,
            min: 5,
            max: 5,
            text: "5"+t('v103.scheduledTrip.day'),
          },
          {
            id: 6,
            min: 6,
            max: 6,
            text: "6"+t('v103.scheduledTrip.day'),
          },
          {
            id: 7,
            min: 7,
            max: 8,
            text: "7-8"+t('v103.scheduledTrip.day'),
          },
          {
            id: 8,
            min: 9,
            max: 10,
            text: "9-10"+t('v103.scheduledTrip.day'),
          },
          {
            id: 9,
            min: 10,
            max: 1000,
            text: "10"+t('v103.scheduledTrip.above'),
          },
        ],
        dataList: [],
        sortNum: 1,
        sortArray: [
          {
            label: t('v103.scheduledTrip.recommend'),
            value: 1,
            icon: "iconfont icongood",
          },
          {
            label: t('v103.scheduledTrip.ascendingorder'),
            value: 2,
            icon: "iconfont iconmeiyuan",
          },
          {
            label: t('v103.scheduledTrip.descendingorder'),
            value: 3,
            icon: "iconfont iconmeiyuan",
          },
        ],
        TotalCount: 0,
        PageCount: 0,
    })
    const search = inject(DirtionmaryHelper.TICKET_QUERY_PARAM) as any
    data.qMsg = JSON.parse(JSON.stringify(search.msg))
    data.msg = JSON.parse(JSON.stringify(search.msg))
    data.msg.teamType = [];
    
    data.msg.priceRange = {
      min: 1,
      max: 100000,
    };
    data.msg.minPrice = 0;
    data.msg.maxPrice = 100000;
    data.dayArray.forEach((x) => {
      x.checked = false;
    });
    data.dateRange = { from: data.msg.startDate, to: data.msg.endDate };
    watch(data.msg, (n, o) => {
      data.msg.pageIndex = 1
      methods.goSearchHandler()
    })

    const methods = {
      initAreaList() {
        let jObj = JSON.parse(localStorage.getItem("baseifo"));
        jObj.AreaList.forEach((x) => {
          x.SubList.forEach((y) => {
            y.checked = false;
            y.explsed = false;
            y.isShow = true;
            if (y.SubList) {
              y.SubList.forEach((z) => {
                z.checked = false;
                z.explsed = false;
                z.isShow = true;
              });
            }
          });
          data.areaList.push(...x.SubList);
        });
      },
      changeExplesdHandler(x) {
        x.explsed = !x.explsed;
        if (x.SubList) {
        }
      },
      changeGoodTypeHandler(x) {
        if (x.checked && data.msg.teamType.indexOf(x.Id) == -1) {
          data.msg.teamType.push(x.Id);
        } else if (!x.checked && data.msg.teamType.indexOf(x.Id) != -1) {
          let i = data.msg.teamType.findIndex((item) => item == x.Id);
          data.msg.teamType.splice(i, 1);
        }
      },
      chosenSortHandler(x) {
        data.sortNum = x.value;
        data.msg.orderByDate = data.sortNum == 4 ? 1 : data.sortNum == 5 ? 2 : 0;
        data.msg.orderByPrice = data.sortNum == 2 ? 1 : data.sortNum == 3 ? 2 : 0;
        data.msg.orderByDay = data.sortNum == 6 ? 1 : data.sortNum == 7 ? 2 : 0;
      },
      changeCheckHandler(x, p = null) {
        if(x.checked=='half'){
          x.checked = true
        }else{
          x.checked = !x.checked
        }
        if (p) {
          let t = p.SubList.filter((x) => x.checked);
          p.checked = t.length == p.SubList.length ? true : t.length == 0 ? false : "half";
            methods.changeChosenHandler(x);
        } else {
          x.SubList.forEach((item) => {
            item.checked = x.checked;
            methods.changeChosenHandler(item);
          });
        }
      },
      changeChosenHandler(x) {
        let i = data.chosenAddress.findIndex((item) => item.Id == x.Id) ?? -1;
        if (!x.checked) {
          if (i > -1) {
            data.chosenAddress.splice(i, 1);
          }
        } else {
          if (i == -1) {
            data.chosenAddress.push(x);
          }
        }
      },
      changeTripDayHandler() {
        that.$forceUpdate()
        data.msg.minTripDay = "0";
        data.msg.maxTripDay = "0";
        data.dayArray.forEach((x) => {
          if (x.checked) {
            data.msg.minPrice =
              data.msg.minPrice > x.min ? x.min : data.msg.minPrice;
            data.msg.maxPrice =
              data.msg.maxPrice < x.max ? x.max : data.msg.maxPrice;
          }
        });
        data.msg.minTripDay =
          data.msg.minTripDay == "0" ? "" : data.msg.minTripDay;
        data.msg.maxTripDay =
          data.msg.maxTripDay == "0" ? "" : data.msg.maxTripDay;
      },
      optionsFn(cd) {
        return (
          cd >=
          date.formatDate(date.addToDate(new Date(), { days: 1 }), "YYYY/MM/DD")
        );
      },
      testHandler(e) {
        that.$forceUpdate();
        data.msg.minPrice = e.min;
        data.msg.maxPrice = e.max;
      },
      dateRangeHandler(e) {
        data.msg.startDate = `${e.from.year}/${e.from.month}/${e.from.day}`;
        data.msg.endDate = `${e.to.year}/${e.to.month}/${e.to.day} `;
        if (qDateProxy.value) qDateProxy.value.hide()
      },
      initGoods() {
        data.goodsType.push({
          Id: 1,
          Name: t('v103.scheduledTrip.sightseeingitinerary'),
          explsed: false,
          SubList: [
            {
              Id: 2,
              Name: t('v103.scheduledTrip.daytrip'),
              checked: false,
            },
            {
              Id: 3,
              Name: t('v103.scheduledTrip.multiday'),
              checked: false,
            },
          ],
        });
      },
      changeAddrSearchHandler(v) {
        data.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;
            }
          });
        });
      },
      goSearchHandler() {
        $q.loading.show();
        data.DataList = [];
        let minTripDay = -1,
          maxTripDay = -1,
          minPrice = -1,
          maxPrice = -1;
        if (data.qMsg.minPrice != "") {
          minPrice = parseFloat(data.qMsg.minPrice);
        }
        if (data.qMsg.maxPrice != "") {
          maxPrice = parseFloat(data.qMsg.maxPrice);
          if (minPrice > maxPrice) {
            message.errorMsg(t('v103.scheduledTrip.interval'));
            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) {
            data.msg.priceOrderByField = 2;
          }
        }
        let param = Object.assign(data.msg)
        scheduledTripService.GetB2BTravelPageList(param).then(r => {
          $q.loading.hide();
          if (r.data.resultCode == ApiResult.SUCCESS) {
            if (r.data.data) {
              data.PageCount = r.data.data.pageCount;
              data.TotalCount = r.data.data.count;
              var tempArray = r.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) {}
                  }
                });
                data.DataList = tempArray;
              }
            }
          } else {
            message.errorMsg(r.data.message)
          }
        }).catch(e => {
          $q.loading.hide();
          message.errorMsg(e.message)
        })
      },
      GotoDetails(item) {
        $router.push({ 
          path:`/scheduledTrip/details/${encodeURIComponent(item.id)}/${item.tcid}`
        })
      },
    
    }
    methods.initAreaList();
    methods.initGoods();
    methods.goSearchHandler();
    onMounted(()=>{
      
    })
    return {
      ...toRefs(data),
      ...methods,
      qDateProxy
    }
  }
})
</script>

<style>
.blank-block{
  margin: 100px auto;
  width: 300px;
  text-align: center;
}
.blank-block i{
  font-size: 80px;
  color: #ddd;
}
.blank-block p{
  color: #999;
  font-size: 15px;
  letter-spacing: 1px;
}
.addr-list:hover {
  background: #f1416c1a;
}
</style>
