<script setup lang="ts">
import emitter from '@/utils/bus'
import FilterTags from '@/components/FliterTags'
import TransportMode from '@/components/TransportMode'
import BookingTable from './components/BookingTable'
import DateRange from '@/components/DateRange'
import MoreFilters from '@/components/MoreFilters'
import { ref, reactive } from 'vue'
import { useCalculatingHeight } from '@/hooks/calculatingHeight'

const filterRef: Ref<HTMLElement | null> = ref(null)

const containerHeight = useCalculatingHeight(document.documentElement, 246, [filterRef])

const BookingSearch = ref()
const tableLoadingTableData = ref(false)
let searchTableQeury: any = {}
const filterData = reactive({
  filtersTagData: [] as Array<string>,
  transportData: [] as Array<string>,
  daterangeData: [] as Array<string>,
  morefiltersData: [] as Array<string>
})
onMounted(() => {})
const tagsData: any = ref([])
const handleClose = (tag: any) => {
  emitter.emit('clearTag', tag)
  tagsData.value.splice(tagsData.value.indexOf(tag), 1)
  if (tag.includes('Transport')) {
    delete searchTableQeury.transport_mode
  } else if (tag.includes('ETD')) {
    filterData.daterangeData.forEach((item: any, index: any) => {
      if (item.includes('ETD')) {
        filterData.daterangeData.splice(index, 1)
      }
    })
    delete searchTableQeury.f_etd_start
    delete searchTableQeury.f_etd_end
  } else if (tag.includes('ETA')) {
    filterData.daterangeData.forEach((item: any, index: any) => {
      if (item.includes('ETA')) {
        filterData.daterangeData.splice(index, 1)
      }
    })
    delete searchTableQeury.m_eta_start
    delete searchTableQeury.m_eta_end
  } else if (tag.includes('Creation')) {
    filterData.daterangeData.forEach((item: any, index: any) => {
      if (item.includes('Creation')) {
        filterData.daterangeData.splice(index, 1)
      }
    })
    delete searchTableQeury.created_time_start
    delete searchTableQeury.created_time_end
  } else if (tag.includes('Shippername')) {
    delete searchTableQeury.shipper
  } else if (tag.includes('Consigneename')) {
    delete searchTableQeury.consignee
  } else if (tag.includes('Origin Agent')) {
    delete searchTableQeury.origin
  } else if (tag.includes('Destination Agent')) {
    delete searchTableQeury.agent
  } else if (tag.includes('Sales')) {
    delete searchTableQeury.sales_rep
  } else if (tag.includes('Origin')) {
    delete searchTableQeury.shipper_city
  } else if (tag.includes('Destination')) {
    delete searchTableQeury.consignee_city
  } else if (tag.includes('Place of Receipt')) {
    delete searchTableQeury['place_of_receipt/place_of_receipt_exp']
  } else if (tag.includes('Port of Loading')) {
    delete searchTableQeury['fport_of_loading_uncode/fport_of_loading_exp']
  } else if (tag.includes('Place of delivery')) {
    delete searchTableQeury['place_of_delivery/place_of_delivery_exp']
  } else if (tag.includes('Vessel')) {
    delete searchTableQeury['f_vessel/m_vessel']
  } else if (tag.includes('Voyage')) {
    delete searchTableQeury['f_voyage/m_voyage']
  }
  sessionStorage.setItem('searchTableQeury', JSON.stringify(searchTableQeury))
  getbookingdata()
}
// 筛选框查询
const FiltersSeach = (val: any, value: any) => {
  searchTableQeury[val] = value
  sessionStorage.setItem('searchTableQeury', JSON.stringify(searchTableQeury))
  getbookingdata()
}
//TransportSearch
const TransportSearch = (val: any) => {
  filterData.transportData = []
  if (val.data) {
    let str = `${val.title}:${val.data}`
    filterData.transportData.push(str)
  }
  FiltersSeach('transport_mode', val.data)
  renderTagsData()
}
// defaultTransport
const defaultTransport = (val: any, value: any) => {
  filterData.transportData = []
  if (val.data) {
    let str = `${val.title}:${val.data}`
    filterData.transportData.push(str)
  }
  if (sessionStorage.getItem('searchTableQeury') == null) {
    searchTableQeury.transport_mode = val.data
  } else {
    searchTableQeury = value
  }
  renderTagsData()
}
// defaultDate
const defaultDate = (val: any, value: any, data: any) => {
  filterData.daterangeData = []
  if (Object.keys(val).length) {
    for (const key in val) {
      let str = `${key}:${val[key]}`
      filterData.daterangeData.push(str)
    }
  }
  if (sessionStorage.getItem('searchTableQeury') == null) {
    for (const key in value) {
      searchTableQeury.f_etd_start = value[key].data[0]
      searchTableQeury.f_etd_end = value[key].data[1]
    }
  } else {
    searchTableQeury = data
    if (searchTableQeury._textSearch) {
      BookingSearch.value = searchTableQeury._textSearch
    }
  }
  getbookingdata()
  renderTagsData()
}
//DateRangeSearch
const DateRangeSearch = (val: any, value: any) => {
  filterData.daterangeData = []
  if (Object.keys(val).length) {
    for (const key in val) {
      let str = `${key}:${val[key]}`
      filterData.daterangeData.push(str)
    }
  }
  if (Object.keys(value).length == 0) {
    delete searchTableQeury.f_etd_start
    delete searchTableQeury.f_etd_end
    delete searchTableQeury.m_eta_start
    delete searchTableQeury.m_eta_end
    delete searchTableQeury.created_time_start
    delete searchTableQeury.created_time_end
  }
  for (const key in value) {
    if (key == 'ETD') {
      searchTableQeury.f_etd_start = value[key].data[0]
      searchTableQeury.f_etd_end = value[key].data[1]
    } else if (key == 'ETA') {
      searchTableQeury.m_eta_start = value[key].data[0]
      searchTableQeury.m_eta_end = value[key].data[1]
    } else {
      searchTableQeury.created_time_start = value[key].data[0]
      searchTableQeury.created_time_end = value[key].data[1]
    }
  }
  sessionStorage.setItem('searchTableQeury', JSON.stringify(searchTableQeury))
  getbookingdata()
  renderTagsData()
}
//MoreFiltersSearch
const MoreFiltersSearch = (val: any, value: any) => {
  filterData.morefiltersData = []
  if (Object.keys(value).length == 0) {
    delete searchTableQeury.shipper
    delete searchTableQeury.consignee
    delete searchTableQeury.origin
    delete searchTableQeury.agent
    delete searchTableQeury.sales_rep
    delete searchTableQeury.shipper_city
    delete searchTableQeury.consignee_city
    delete searchTableQeury['place_of_receipt/place_of_receipt_exp']
    delete searchTableQeury['fport_of_loading_uncode/fport_of_loading_exp']
    delete searchTableQeury['place_of_delivery/place_of_delivery_exp']
    delete searchTableQeury['f_vessel/m_vessel']
    delete searchTableQeury['f_voyage/m_voyage']
  }
  for (const key in val) {
    let str = `${key}:${val[key]}`
    filterData.morefiltersData.push(str)
    if (key == 'Shippername') {
      searchTableQeury.shipper = value[key]
    } else if (key == 'Consigneename') {
      searchTableQeury.consignee = value[key]
    } else if (key == 'Origin Agent') {
      searchTableQeury.origin = value[key]
    } else if (key == 'Destination Agent') {
      searchTableQeury.agent = value[key]
    } else if (key == 'Sales') {
      searchTableQeury.sales_rep = value[key]
    } else if (key == 'Origin') {
      searchTableQeury.shipper_city = value[key]
    } else if (key == 'Destination') {
      searchTableQeury.consignee_city = value[key]
    } else if (key == 'Place of Receipt') {
      searchTableQeury['place_of_receipt/place_of_receipt_exp'] = value[key]
    } else if (key == 'Port of Loading') {
      searchTableQeury['fport_of_loading_uncode/fport_of_loading_exp'] = value[key]
    } else if (key == 'Place of delivery') {
      searchTableQeury['place_of_delivery/place_of_delivery_exp'] = value[key]
    } else if (key == 'Vessel') {
      searchTableQeury['f_vessel/m_vessel'] = value[key]
    } else if (key == 'Voyage') {
      searchTableQeury['f_voyage/m_voyage'] = value[key]
    }
  }
  sessionStorage.setItem('searchTableQeury', JSON.stringify(searchTableQeury))
  getbookingdata()
  renderTagsData()
}
const defaultMorefilters = (val: any, value: any, data: any) => {
  filterData.morefiltersData = []
  for (const key in val) {
    let str = `${key}:${val[key]}`
    filterData.morefiltersData.push(str)
    if (key == 'Shippername') {
      searchTableQeury.shipper = value[key]
    } else if (key == 'Consigneename') {
      searchTableQeury.consignee = value[key]
    } else if (key == 'Origin Agent') {
      searchTableQeury.origin = value[key]
    } else if (key == 'Destination Agent') {
      searchTableQeury.agent = value[key]
    } else if (key == 'Sales') {
      searchTableQeury.sales_rep = value[key]
    } else if (key == 'Origin') {
      searchTableQeury.shipper_city = value[key]
    } else if (key == 'Destination') {
      searchTableQeury.consignee_city = value[key]
    } else if (key == 'Place of Receipt') {
      searchTableQeury['place_of_receipt/place_of_receipt_exp'] = value[key]
    } else if (key == 'Port of Loading') {
      searchTableQeury['fport_of_loading_uncode/fport_of_loading_exp'] = value[key]
    } else if (key == 'Place of delivery') {
      searchTableQeury['place_of_delivery/place_of_delivery_exp'] = value[key]
    } else if (key == 'Vessel') {
      searchTableQeury['f_vessel/m_vessel'] = value[key]
    } else if (key == 'Voyage') {
      searchTableQeury['f_voyage/m_voyage'] = value[key]
    }
  }
  if (sessionStorage.getItem('searchTableQeury') != null) {
    searchTableQeury = data
  }
  renderTagsData()
}
const clearfilters = () => {
  BookingSearch.value = ''
  filterData.filtersTagData = []
  tagsData.value = []
  let str = 'Shipment status: All'
  filterData.filtersTagData.push(str)
  filterData.transportData = []
  filterData.daterangeData = []
  filterData.morefiltersData = []
  emitter.emit('clearTag', 'Shipment status')
  emitter.emit('clearTag', 'Transport Mode')
  emitter.emit('clearTag', 'ETD')
  emitter.emit('clearTag', 'ETA')
  emitter.emit('clearTag', 'Creation Time')
  emitter.emit('clearTag', 'Shippername')
  emitter.emit('clearTag', 'Consigneename')
  emitter.emit('clearTag', 'Origin Agent')
  emitter.emit('clearTag', 'Destination Agent')
  emitter.emit('clearTag', 'Sales')
  emitter.emit('clearTag', 'Origin')
  emitter.emit('clearTag', 'Destination')
  emitter.emit('clearTag', 'Place of Receipt')
  emitter.emit('clearTag', 'Port of Loading')
  emitter.emit('clearTag', 'Place of delivery')
  emitter.emit('clearTag', 'Vessel')
  emitter.emit('clearTag', 'Voyage')
  searchTableQeury = {}
  searchTableQeury.filterTag = ['All']
  sessionStorage.setItem('searchTableQeury', JSON.stringify(searchTableQeury))
  getbookingdata()
  renderTagsData()
}
const renderTagsData = () => {
  tagsData.value = []
  if (filterData.transportData.length) {
    tagsData.value.push(filterData.transportData[0])
  }
  if (filterData.daterangeData.length) {
    filterData.daterangeData.forEach((item) => {
      tagsData.value.push(item)
    })
  }
  if (filterData.morefiltersData.length) {
    filterData.morefiltersData.forEach((item) => {
      tagsData.value.push(item)
    })
  }
  if (filterData.filtersTagData.length) {
    filterData.filtersTagData.forEach((item) => {
      tagsData.value.push(item)
    })
  }
}
// 清除 Transport Tags
const clearTransportTags = () => {
  filterData.transportData = []
}
// 清除 Daterange Tags
const clearDaterangeTags = () => {
  filterData.daterangeData = []
}
// 清除 MoreFilters Tags
const clearMoreFiltersTags = () => {
  filterData.morefiltersData = []
}

const BookingTable_ref = ref()
const TransportListItem = ref()
interface ListItem {
  name: string
  number: number
  type: string
  checked: boolean
}
const TagsList = ref<ListItem[]>([])
const filterTag = ref(['All'])
const isShowAlertIcon = ref(false)
const getbookingdata = () => {
  tableLoadingTableData.value = true
  BookingTable_ref.value.getLoadingData(tableLoadingTableData.value)
  $api
    .getBookingTableData({
      cp: BookingTable_ref.value.pageInfo.pageNo,
      ps: BookingTable_ref.value.pageInfo.pageSize,
      rc: -1,
      other_filed: '',
      ...searchTableQeury
    })
    .then((res: any) => {
      if (res.code === 200) {
        TransportListItem.value = res.data.TransportList
        TagsList.value = res.data.tagsList
        let taglist: any = []
        if (Object.keys(filterData.filtersTagData).length == 0) {
          TagsList.value.forEach((item: any) => {
            if (item.checked == true) {
              taglist.push(item.name)
            }
          })
          let str = 'Shipment status: ' + taglist.toString()
          filterData.filtersTagData.push(str)
          filterData.filtersTagData.forEach((item) => {
            tagsData.value.push(item)
          })
        }
        sessionStorage.setItem('BookingData', JSON.stringify(res.data))
        BookingTable_ref.value.searchTableData(searchTableQeury)
        // 查询没结果的话显示icon
        if (BookingSearch.value != '' && BookingSearch.value != undefined) {
          if (res.data.searchData.length == 0) {
            isShowAlertIcon.value = true
          }
        } else {
          isShowAlertIcon.value = false
        }
      }
    })
}
const changeTag = (val: any) => {
  filterData.filtersTagData = []
  searchTableQeury.filterTag = val
  let str = 'Shipment status: ' + val
  filterData.filtersTagData.push(str)
  sessionStorage.setItem('searchTableQeury', JSON.stringify(searchTableQeury))
  getbookingdata()
  renderTagsData()
  filterTag.value = val
}
// 点击search按钮
const SearchInput = () => {
  searchTableQeury._textSearch = BookingSearch.value
  sessionStorage.setItem('searchTableQeury', JSON.stringify(searchTableQeury))
  getbookingdata()
}
</script>

<template>
  <div class="Title">Booking</div>
  <div class="display" ref="filterRef">
    <FilterTags :TagsListItem="TagsList" @changeTag="changeTag"></FilterTags>
    <div class="heaer_top">
      <div class="search">
        <el-input
          placeholder="Enter Booking/HBL/PO/Container/Carrier Booking No. "
          v-model="BookingSearch"
        >
          <template #prefix>
            <span class="iconfont_icon">
              <svg class="iconfont" aria-hidden="true">
                <use xlink:href="#icon-icon_search_b"></use>
              </svg>
            </span>
          </template>
          <template #suffix>
            <el-tooltip
              v-if="isShowAlertIcon"
              :offset="6"
              popper-class="ShowAlerIcon"
              effect="dark"
              content="We support the following references number to find bookings:· Booking No./HAWB No./MAWB No./PO No./Carrier Booking No./Contract No./File No./Quote No."
              placement="bottom"
            >
              <span class="iconfont_icon iconfont_icon_tip">
                <svg class="iconfont" aria-hidden="true">
                  <use xlink:href="#icon-icon_info_b"></use>
                </svg>
              </span>
            </el-tooltip>
          </template>
        </el-input>
      </div>
      <TransportMode
        :isShipment="false"
        :TransportListItem="TransportListItem"
        @TransportSearch="TransportSearch"
        @defaultTransport="defaultTransport"
        @clearTransportTags="clearTransportTags"
      ></TransportMode>
      <DateRange
        :isShipment="false"
        @DateRangeSearch="DateRangeSearch"
        @clearDaterangeTags="clearDaterangeTags"
        @defaultDate="defaultDate"
      ></DateRange>
      <MoreFilters
        :isShipment="false"
        :searchTableQeury="searchTableQeury"
        @MoreFiltersSearch="MoreFiltersSearch"
        @clearMoreFiltersTags="clearMoreFiltersTags"
        @defaultMorefilters="defaultMorefilters"
      ></MoreFilters>
      <el-button class="el-button--dark" style="margin-left: 8px" @click="SearchInput"
        >Search</el-button
      >
    </div>
    <!-- 筛选项 -->
    <div class="filtersTag" v-if="tagsData.length">
      <el-tag
        :key="tag"
        class="tag"
        v-for="tag in tagsData"
        :closable="!tag.includes('Shipment')"
        :disable-transitions="false"
        @close="handleClose(tag)"
        color="#EFEFF0"
      >
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="tag"
          placement="top"
          v-if="tag.length > 39"
        >
          {{ tag.length > 39 ? tag.substr(0, 39) + '...' : tag }}
        </el-tooltip>
        <div v-else>{{ tag }}</div>
      </el-tag>
      <div class="text_button" @click="clearfilters">Clear Filters</div>
    </div>
  </div>
  <BookingTable
    :height="containerHeight"
    :tagsData="tagsData"
    ref="BookingTable_ref"
  ></BookingTable>
</template>

<style lang="scss" scoped>
.Title {
  display: flex;
  height: 68px;
  border-bottom: 1px solid var(--color-border);
  font-size: var(--font-size-6);
  font-weight: 700;
  padding: 0 24px;
  align-items: center;
}
.display {
  border: 1px solid var(--color-border);
  border-width: 0 0 1px 0;
  padding: 0 24px;
}
.heaer_top {
  margin-top: 6.57px;
  margin-bottom: 8px;
  display: flex;
}
.search {
  width: 400px;
  height: 32px;
}
.filtersTag {
  margin-bottom: 8.7px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.tag {
  border-color: #efeff0;
  border-radius: var(--border-radius-22);
  margin: 0 8px 8px 0;
  color: var(--color-neutral-1);
  font-weight: 600;
  font-size: var(--font-size-2);
}
.iconfont_icon_tip {
  margin-left: 8px;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
}
@media only screen and (min-width: 1280px) {
  .search {
    width: 480px;
  }
}
@media only screen and (min-width: 1440px) {
  .search {
    width: 740px;
  }
}
</style>
