<template>
  <div>
    <div class="sticky top-49 z-50 bg-white w-full">
      <div class="w-full p-16">
        <!-- 列表搜索 -->
        <div class="flex h-40 w-full items-center justify-between rounded-full border bg-[#fff]">
          <input
            type="text"
            v-model="searchString"
            class="ml-5 w-[80%] pl-10 text-sm"
            placeholder="输入要办理的签证居留的国家或地区名称"
            style="outline: none; background: none"
            @keydown.enter="search"
          />
          <button @click="search" class="h-full border-l-[1px] w-46 shrink-0 rounded-r-full">
            <van-icon size="16" :name="searchSvg" />
          </button>
        </div>
      </div>

      <van-dropdown-menu active-color="#FF9300" ref="visaDropDownMenuRef">
        <van-dropdown-item
          ref="itemTypeRef"
          @open="showItemType = true"
          @close="showItemType = false"
          @closed="onVisaFilterClose"
          v-model="checkedVisaType"
        >
          <template #title>
            <div class="flex h-50 box-border py-12 justify-center items-center">
              <van-icon v-if="showItemType" size="16" :name="orangeVisaTypeSvg" />
              <van-icon v-else size="16" :name="visaTypeSvg" />
              <span class="pl-4 text-base">{{ visaTypeTitle }}</span>
            </div>
          </template>
          <van-cell
            v-for="el in visaTypeList"
            :key="el?.id"
            :title="el.title"
            @click="handleCheckedVisaTypeChange(el)"
          >
            <template #right-icon>
              <van-radio-group v-model="checkedVisaType">
                <van-radio
                  checked-color="#FF9300"
                  :name="el?.id"
                  v-model="el.id"
                  @click="handleCheckedVisaTypeChange(el)"
                  shape="square"
                ></van-radio>
              </van-radio-group>
            </template>
          </van-cell>
        </van-dropdown-item>

        <van-dropdown-item
          ref="itemLocationRef"
          @open="showItemLocation = true"
          @close="showItemLocation = false"
          @closed="onVisaLocFilterClose"
          v-model="checkedIssueVisaAddr"
        >
          <template #title>
            <div class="flex h-50 box-border py-12 justify-center items-center">
              <van-icon v-if="showItemLocation" size="16" :name="orangeLocationSvg" />
              <van-icon v-else size="16" :name="locationSvg" />

              <span class="pl-4 text-base">{{ visaLocationTitle }}</span>
            </div>
          </template>
          <van-cell
            v-for="item in countryCodeList"
            :key="item?.id"
            :title="item.name"
            @click="handleCheckedCitiesChange(item)"
          >
            <template #right-icon>
              <van-radio-group v-model="checkedIssueVisaAddr">
                <van-radio
                  checked-color="#FF9300"
                  :name="item.code"
                  v-model="item.code"
                  @click="handleCheckedCitiesChange(item)"
                  shape="square"
                ></van-radio>
              </van-radio-group>
            </template>
          </van-cell>
        </van-dropdown-item>
      </van-dropdown-menu>
    </div>

    <div class="w-full box-border px-16">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <Empty v-if="!visaList?.length && !loading" title="暂无该签证数据" top="100" />
        <van-list
          v-else-if="visaList.length"
          v-model:loading="loading"
          error-text="获取失败"
          finished-text="-- 没有更多了 --"
          :finished="finished"
          :immediate-check="false"
          @load="getLoadList"
        >
          <div
            v-for="item in visaList"
            :key="item?.id"
            class="w-full min-h-160 box-border border rounded-lg mt-12 px-12 pt-15 pb-13 relative"
            style="background: linear-gradient(180deg, #fff7eb 0%, #ffffff 100%)"
          >
            <NuxtLink :to="'/visa/details/' + item?.id" @click.prevent class="w-full block">
              <div class="flex w-full h-90 box-border justify-start mb-15">
                <div class="w-110 h-80 rounded mr-12">
                  <img class="h-full w-full rounded object-cover" :src="item?.img" alt="" />
                </div>

                <div class="w-200">
                  <h1
                    :title="item?.visaTitle"
                    class="w-full h-24 mb-2 truncate whitespace-nowrap text-nowrap text-base font-semibold leading-5xl text-[#444]"
                  >
                    {{ item?.visaTitle }}
                  </h1>

                  <p class="w-full leading-3xl font-normal text-sm truncate">
                    <span class="text-black-9">签证类型：</span>
                    <span :title="item?.visaTypeIdDictMap?.name" class="font-semibold text-[#444]">
                      {{ item?.visaTypeIdDictMap?.name }}
                    </span>
                  </p>
                  <p
                    v-if="item?.validity > 0"
                    class="w-full truncate leading-3xl font-normal text-sm"
                  >
                    <span class="text-black-9">有效期：</span>
                    <span class="text-[#444] font-semibold">
                      {{ item?.validity ? `${item?.validity}天` : '无限制' }}
                    </span>
                  </p>

                  <p
                    v-if="item?.processingDays > 0"
                    class="w-full font-normal truncate leading-3xl text-sm"
                  >
                    <span class="text-black-9">出签周期：</span>
                    <span class="text-[#444] font-semibold">
                      收齐材料后{{ item?.processingDays }}个工作日
                    </span>
                  </p>
                </div>
              </div>

              <div class="w-full box-border flex justify-between h-24 items-center">
                <p class="block text-center text-sm font-normal text-[#FF476A] pt-3 m-0">
                  ¥
                  <span class="text-5xl font-semibold">
                    {{ item?.floorPrice ? item?.floorPrice : '????' }}
                  </span>
                  起
                </p>

                <button
                  class="h-full border-[0.5px] text-base px-13 shrink-0 border-black-9 rounded-full bg-white active:bg-black/[0.1]"
                >
                  详情
                  <van-icon size="14" name="arrow" />
                </button>
              </div>
            </NuxtLink>

            <button
              @click.stop="getVisaCounselorDetails(item.id)"
              class="h-24 absolute bottom-15 right-97 z-20 border-[0.5px] text-[#FD9A00] text-base px-13 shrink-0 border-[#FD9A00] rounded-full bg-white active:bg-[#FD9A00]/[0.1]"
            >
              联系顾问
            </button>
          </div>
        </van-list>

        <div
          class="mb-20 mt-11 overflow-hidden box-border h-107 w-full rounded-lg border border-[#F5F5F5] flex"
        >
          <div
            class="box-border flex h-full w-115 px-15 py-11 items-center justify-center border-r-[1px] border-r-[#F5F5F5]"
            style="background: linear-gradient(180deg, #fff7eb 0%, #ffffff 100%)"
          >
            <div class="h-84 w-84 shrink-0">
              <img
                :src="rightTopCounselorData?.counselorWechat"
                alt=""
                class="h-full w-full object-cover"
              />
            </div>
          </div>
          <div
            class="font-semibold h-full w-230 flex items-center justify-start text-base text-[#444]"
          >
            <div class="w-22 h-12 shrink-0 mx-20">
              <img class="w-full h-full" src="@/assets/img/visa/three_left.svg" alt="" />
            </div>
            扫码联系 人工服务
          </div>
        </div>

        <div class="z-[10] flex w-full mb-8 items-center text-xl font-semibold text-black-3">
          <div class="w-16 h-16 shrink-0 mr-4">
            <img class="w-full h-full object-cover" src="@/assets/img/visa/fire.svg" alt="" />
          </div>
          超值热卖
        </div>

        <div class="relative min-h-244 w-full rounded-lg border overflow-hidden mb-20">
          <img
            class="absolute left-0 top-0 z-0 h-67 w-full object-cover"
            src="@/assets/img/visa/Rectangle.png"
            alt=""
          />
          <div class="absolute left-0 top-0 z-1 box-border h-full w-full px-11">
            <NuxtLink
              v-for="item in hotList"
              :key="item.id"
              :to="'/t/' + item?.id"
              class="my-15 flex h-60 w-full justify-between"
            >
              <div class="w-90 h-full shrink-0 overflow-hidden rounded-[4px]">
                <img
                  class="h-full w-full object-cover"
                  :src="item.homeHotPicturesAfterConvert[0]"
                  alt=""
                />
              </div>

              <div class="ml-15 box-border w-220">
                <p
                  :title="`【热销纯玩】 ${item?.projectTitle}`"
                  class="h-38 text-sm line-clamp-2 leading-2xl"
                >
                  【热销纯玩】{{ item?.projectTitle }}
                </p>
                <p class="text-right text-sm font-semibold leading-2xl text-black-9">
                  <span class="text-base text-[#FF476A]">
                    ￥ {{ item?.price ? item?.price : '????' }}
                  </span>
                  起
                </p>
              </div>
            </NuxtLink>
          </div>
        </div>
      </van-pull-refresh>
    </div>

    <van-back-top
      bottom="30vh"
      right="12px"
      style="background-color: white; color: #ff9300"
      class="w-56 h-56 text-[10px] font-semibold"
    >
      <div class="w-full border border-[#000]/[0] flex justify-center flex-wrap">
        <van-icon name="back-top" size="19" color="#FF9300" />
        <div>TOP</div>
      </div>
    </van-back-top>

    <van-dialog
      :keyboard-enabled="false"
      v-model:show="showVisaModal"
      style="width: 80%; border-radius: 12px"
    >
      <template #title>
        <div class="flex justify-between items-center border-b-[1px] px-15 pb-10">
          <h1 class="text-[16px] font-semibold text-[#333]">顾问信息</h1>
          <div class="w-31 h-31 shrink-0" @click="showVisaModal = false">
            <img
              class="w-full h-full object-cover"
              src="~/assets/img/note-create/close.svg"
              alt=""
            />
          </div>
        </div>
      </template>
      <div class="box-border w-full h-256">
        <div class="flex items-start justify-start pt-34 pl-24 pr-15 mb-22">
          <div
            class="box-border h-64 w-64 overflow-hidden rounded-full border-[2px] border-[#E2E2E2]"
          >
            <img class="h-full w-full object-cover" :src="consultantInfo?.counselorAvatar" alt="" />
          </div>

          <div class="ml-21 w-160 text-left">
            <p class="line-clamp-1 text-base font-normal leading-5xl text-[#333]/[0.9]">
              {{ consultantInfo?.counselorName }} ({{ consultantInfo?.levelDictMap?.name }})
            </p>
            <p class="line-clamp-1 text-sm font-normal leading-5xl text-black-9">
              工作时间 {{ consultantInfo?.workingTime }}
            </p>
            <p
              :title="phoneSection(consultantInfo?.countryCodeId, consultantInfo?.counselorPhone)"
              class="line-clamp-1 text-xl font-semibold text-[#000]"
            >
              {{ phoneSection(consultantInfo?.countryCodeId, consultantInfo?.counselorPhone) }}
            </p>
          </div>
        </div>

        <div>
          <div class="ml-109">
            <div class="h-94 w-94 overflow-hidden">
              <img
                class="h-full w-full object-cover"
                :src="consultantInfo?.counselorWechat"
                alt=""
              />
            </div>

            <p class="text-sm pt-8 font-normal leading-base text-black-9">扫码添加 企业微信</p>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="w-full flex justify-center mb-19">
          <van-button
            @click="showVisaModal = false"
            style="width: 120px; height: 40px"
            color="#FF9300"
            round
            type="warning"
          >
            确认
          </van-button>
        </div>
      </template>
    </van-dialog>
  </div>
</template>
<script setup>
import searchSvg from '@/assets/img/visa/search.svg'
import visaTypeSvg from '@/assets/img/visa/qianzheng_three.svg'
import orangeVisaTypeSvg from '@/assets/img/visa/orange_qianzheng_three.svg'
import locationSvg from '@/assets/img/visa/location.svg'
import orangeLocationSvg from '@/assets/img/visa/orangeLocation.svg'

const route = useRoute()

const UNLIMITED_TEXT = '不限'
const TYPE_TEXT = '签证类型'
const ADDRESS_TEXT = '出签地'

const visaDropDownMenuRef = ref(null)

const itemTypeRef = ref(null)
const showItemType = ref(false)

const itemLocationRef = ref(null)
const showItemLocation = ref(false)

const visaTypeTitle = ref(TYPE_TEXT)
const visaLocationTitle = ref(ADDRESS_TEXT)

watch(showItemType.value, () => {}, { deep: true })

// 监听签证类型筛选框收起
function onVisaFilterClose() {}

// 监听出签地筛选框收起
function onVisaLocFilterClose() {}

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  searchString: computed(() => route.query?.searchString ?? ''),
  countryCodeId: computed(() => route.query?.countryCodeId ?? '')
})

const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)

// 超值热卖的页数
const pageNum = ref(1)

// 顾问的模态框
let showVisaModal = ref(false)

// 签证列表
const visaList = ref([])

// 右上角签证顾问
const rightTopCounselorData = ref({})

// 出签地列表
const countryCodeList = ref([])

// 搜索得参数
let searchString = ref('')

// 选中的筛选类型
let checkedVisaType = ref(0)

// 选中的筛选出签地
let checkedIssueVisaAddr = ref(0)

// 顾问信息
let consultantInfo = ref({})

// 超值热卖
let hotList = ref([])

const isValue = (parmas) => {
  if (parmas !== null || parmas !== undefined || parmas !== '') {
    return parmas
  } else {
    return ''
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  queryParams.pageNum = 1
  visaList.value = []
  getVisaList()
}

// 搜索的方法
function search() {
  if (searchString.value) {
    navigateTo({
      path: '/visa/visaList',
      query: {
        searchString: searchString.value
      }
    })
  } else {
    navigateTo('/visa/visaList')
  }
}

// 选择类型的筛选条件
const handleCheckedVisaTypeChange = (parmas) => {
  if (parmas.title == TYPE_TEXT) {
    visaTypeTitle.value = TYPE_TEXT
  } else {
    visaTypeTitle.value = parmas.title
  }
  checkedVisaType.value = parmas.id
  itemTypeRef.value.toggle(false)
  showItemType.value = !showItemType.value
  document.title = parmas.title
  visaList.value = []
  queryParams.pageNum = 1
  finished.value = false
  getVisaList()
}

// 电话分段
const phoneSection = (codeId, phone) => {
  if (codeId || phone) {
    return `+${codeId} ${phone?.slice(0, 3)} ${phone?.slice(3, 7)} ${phone?.slice(7, 11)}`
  }
}

// 出签地得选择筛选条件
const handleCheckedCitiesChange = (parmas) => {
  queryParams.pageNum = 1
  visaList.value = []
  finished.value = false
  if (parmas.name == ADDRESS_TEXT) {
    visaLocationTitle.value = ADDRESS_TEXT
  } else {
    visaLocationTitle.value = parmas.name
  }

  checkedIssueVisaAddr.value = parmas.code
  itemLocationRef.value.toggle(false)
  showItemLocation.value = !showItemLocation.value
  document.title = parmas.name

  getVisaList()
}

// 获取出签地列表
async function getCountryCodeList() {
  let url = `/website/tourism/visa/findCountryCodeList`

  const { data } = await request(url)
  data?.unshift({ name: UNLIMITED_TEXT, code: 0, id: '' })
  if (Array.isArray(data)) countryCodeList.value = data
}

// 获取签证的类型列表
const visaTypeList = ref([])
async function getVisaTypeList() {
  const { data } = await request(`/website/tourism/visa/getTypeList`)
  data?.unshift({ title: UNLIMITED_TEXT, code: 0, id: 0 })
  if (Array.isArray(data)) visaTypeList.value = data
}

// 获取签证列表
async function getVisaList() {
  try {
    let url = `/website/tourism/visa/list/page`
    let data = {}

    if (checkedVisaType.value != 0) {
      data.visaTypeId = checkedVisaType.value
    }

    if (checkedIssueVisaAddr.value != 0) {
      data.issueVisaCode = checkedIssueVisaAddr?.value
    }
    loading.value = true
    let {
      data: { dataList, totalCount }
    } = await request(url, {
      query: {
        ...queryParams,
        ...data
      }
    })

    if (Array.isArray(dataList) && dataList?.length) {
      visaList.value = visaList.value.concat(dataList)
    } else {
      visaList.value = []
    }

    loading.value = false
    refreshing.value = false
    if (visaList.value.length >= totalCount) {
      finished.value = true
    } else {
      finished.value = false
    }
  } catch (err) {
  } finally {
    refreshing.value = false
    loading.value = false
  }
}

// 获取筛选签证列表
function getLoadList() {
  queryParams.pageNum++
  finished.value = true
  getVisaList()
}

//  获取签证顾问信息
async function getVisaCounselorDetails(cid) {
  // 阻止事件冒泡

  showVisaModal.value = !showVisaModal.value
  try {
    let url = `/website/tourism/visa/findByById?id=${cid}`

    let {
      data: { visa, counselor }
    } = await request(url)

    if (counselor) {
      counselor.countryCodeId = visa?.countryCodeId
      counselor.workingTime =
        counselor?.start > 0 && counselor?.end > 0
          ? `${isValue(counselor?.start)}:00 - ${isValue(counselor?.end)}:00`
          : ''
      consultantInfo.value = counselor
    }
  } catch (error) {
    return
  }
}

// 签证列表单独获取顾问得的二维码
const getCounselorQr = async () => {
  let url = `/website/tourism/visa/findWechatList`

  let { data } = await request(url)

  if (data) rightTopCounselorData.value = data
}

// 获取超值热卖的接口
async function getTourismProject() {
  let url = `/website/tourism/project/list`
  let data = `?pageNum=${pageNum.value}&pageSize=${3}&isHotspot=${1}`
  let {
    data: { dataList, totalCount }
  } = await request(`${url}${data}`)

  if (Array.isArray(dataList)) hotList.value = dataList
}

watch(searchString, (newValue, oldValue) => {
  searchString.value = newValue
  if (newValue) {
    navigateTo({
      path: '/visa/visaList',
      query: {
        searchString: searchString.value
      }
    })
  } else {
    navigateTo('/visa/visaList')
  }
})

watch(
  [() => route.query.searchString, () => route.query.countryCodeId],
  () => {
    queryParams.pageNum = 1
    visaList.value = []
    getVisaList()
  },
  { immediate: true }
)

onMounted(() => {
  // 获取出签地的信息
  getCountryCodeList()
  // 获取签证类型的列表
  getVisaTypeList()

  getTourismProject()

  getCounselorQr()

  // getCountryList()
})

useSeoMeta({
  title: '签证列表'
})

// 获取全部国家列表
// const countryList = ref([])
// // 选中的筛选类型
// const moreCountryFlag = ref(false)
// const checkedCountryType = ref([UNLIMITED_TEXT])
// async function getCountryList() {
//   const { data } = await request(`/website/tourism/visa/getCountryList`)
//   // data?.unshift({ title: UNLIMITED_TEXT, code: UNLIMITED_TEXT, id: UNLIMITED_TEXT })
//   // if (Array.isArray(data)) countryList.value = data
// }
</script>

<style lang="scss" scoped>
::v-deep .van-dialog__header {
  padding-top: 10px;
}
</style>
