<script setup lang="ts">
import emitter from '@/utils/bus'
import AutoSelect from '@/components/AutoSelect'
import SelectAutoSelect from '@/components/SelectAutoSelect'
import SelectTableSelect from '@/components/SelectTableSelect'
import { ref, onMounted, onBeforeMount } from 'vue'
import SelectTable from '@/components/SelectTable/src/SelectTable.vue'

onMounted(() => {
  emitter.on('clearTag', (tag: any) => {
    if (tag.includes('shippername')) {
      clearname(InputForm.value, 'parties', 'shippername')
    } else if (tag.includes('consigneename')) {
      clearname(InputForm.value, 'parties', 'consigneename')
    } else if (tag.includes('Incoterms')) {
      clearname(InputForm.value, 'General', 'Incoterms')
    } else if (tag.includes('Service')) {
      clearname(InputForm.value, 'General', 'Service')
    } else if (tag.includes('vessel')) {
      clearname(InputForm.value, 'transportation', 'vessel')
    } else if (tag.includes('voyage')) {
      clearname(InputForm.value, 'transportation', 'voyage')
    } else if (tag.includes('origin')) {
      clearname(InputForm.value, 'palces', 'origin')
    } else if (tag.includes('destination')) {
      clearname(InputForm.value, 'palces', 'destination')
    } else if (tag.includes('Origin Agent')) {
      AddDateType.value = AddDateType.value.filter((item: any) => item.partyType !== 'Origin Agent')
      delete MoreFiltersObj['Origin Agent']
      selectedPartyTypeoptions.value = selectedPartyTypeoptions.value.filter(
        (item: any) => item !== 'Origin Agent'
      )
    } else if (tag.includes('Destination Agent')) {
      AddDateType.value = AddDateType.value.filter(
        (item: any) => item.partyType !== 'Destination Agent'
      )
      delete MoreFiltersObj['Destination Agent']
      selectedPartyTypeoptions.value = selectedPartyTypeoptions.value.filter(
        (item: any) => item !== 'Destination Agent'
      )
    } else if (tag.includes('Sales')) {
      AddDateType.value = AddDateType.value.filter((item: any) => item.partyType !== 'Sales')
      delete MoreFiltersObj['Sales']
      selectedPartyTypeoptions.value = selectedPartyTypeoptions.value.filter(
        (item: any) => item !== 'Sales'
      )
    } else if (tag.includes('Place of Receipt')) {
      AddDatePlaceType.value = AddDatePlaceType.value.filter(
        (item: any) => item.placesType !== 'Place of Receipt'
      )
      delete MoreFiltersObj['Place of Receipt']
      selectedPlacesTypeoptions.value = selectedPlacesTypeoptions.value.filter(
        (item: any) => item !== 'Place of Receipt'
      )
    } else if (tag.includes('Port of Loading')) {
      AddDatePlaceType.value = AddDatePlaceType.value.filter(
        (item: any) => item.placesType !== 'Port of Loading'
      )
      delete MoreFiltersObj['Port of Loading']
      selectedPlacesTypeoptions.value = selectedPlacesTypeoptions.value.filter(
        (item: any) => item !== 'Port of Loading'
      )
    } else if (tag.includes('Place of delivery')) {
      AddDatePlaceType.value = AddDatePlaceType.value.filter(
        (item: any) => item.placesType !== 'Place of delivery'
      )
      delete MoreFiltersObj['Place of delivery']
      selectedPlacesTypeoptions.value = selectedPlacesTypeoptions.value.filter(
        (item: any) => item !== 'Place of delivery'
      )
    }
  })
  emitter.on('clearDaterangeObj', () => {
    clearMoreFiltersObj()
  })
})

onBeforeMount(() => {
  emitter.off('clearTag')
  emitter.off('clearMoreFiltersObj')
})

const drawer = ref(false)
interface TypeItem {
  partyType: ''
  partyname: []
  isshowVerfication: boolean
}
interface PlacesTypeItem {
  placesType: ''
  placesname: []
  isshowVerfication: boolean
}
const AddDateType = ref<TypeItem[]>([])
const AddDatePlaceType = ref<PlacesTypeItem[]>([])
const PartyTypeoptions = ref([
  {
    value: 'Origin Agent',
    label: 'Origin Agent'
  },
  {
    value: 'Destination Agent',
    label: 'Destination Agent'
  },
  {
    value: 'Sales',
    label: 'Sales'
  }
])
const PlaceTypeoptions = ref([
  {
    value: 'Place of Receipt',
    label: 'Place of Receipt'
  },
  {
    value: 'Port of Loading',
    label: 'Port of Loading'
  },
  {
    value: 'Place of delivery',
    label: 'Place of delivery'
  }
])

const partSelectTableSelectRef = ref(null)
const placeSelectTableSelectRef = ref(null)

const selectedPartyTypeoptions = ref()
selectedPartyTypeoptions.value = []

const selectedPlacesTypeoptions = ref()
selectedPlacesTypeoptions.value = []

const selectedPartyTypeIndex = ref()
selectedPartyTypeIndex.value = []

const selectedPlacesTypeIndex = ref()
selectedPlacesTypeIndex.value = []

const InputForm = ref({
  parties: {
    shippername: [],
    consigneename: []
  },
  transportation: {
    vessel: [],
    voyage: []
  },
  palces: {
    origin: [],
    destination: []
  },
  General: {
    Incoterms: '',
    Service: ''
  }
})
const props = defineProps({
  isShipment: Boolean
})

const AddType = (item: any) => {
  if (item == 'party') {
    AddDateType.value.push({
      partyType: '',
      partyname: [],
      isshowVerfication: false
    })
  } else if (item == 'place') {
    AddDatePlaceType.value.push({
      placesType: '',
      placesname: [],
      isshowVerfication: false
    })
  }
}
const count = ref()
const countT = ref()
const countP = ref()
const countG = ref()
const PartiesBadge = ref('')
const GeneralBadge = ref('')
const TransportationBadge = ref()
const PlacesBadge = ref()
count.value = []
countT.value = []
countP.value = []
countG.value = []

const changeAll = (value: any, countTotal: any, BadegTotal: any) => {
  for (let key in value) {
    if (value[key] != '') {
      countTotal.push(value[key])
    }
  }
  if (countTotal.length == 0) {
    BadegTotal.value = ''
  } else {
    BadegTotal.value = countTotal.length
  }
}
// 折叠面板生成badge
const changeCollapse = (val: any) => {
  if (val.indexOf('Parties') == -1) {
    AddDateType.value.forEach((item: any) => {
      if (item.partyType != '' && item.partyname.length != 0) {
        count.value.push(item.partyname)
      }
    })
    changeAll(InputForm.value.parties, count.value, PartiesBadge)
    count.value = []
  } else {
    PartiesBadge.value = ''
  }
  if (val.indexOf('General') == -1) {
    changeAll(InputForm.value.General, countG.value, GeneralBadge)
    countG.value = []
  } else {
    GeneralBadge.value = ''
  }
  if (val.indexOf('Transportation') == -1) {
    changeAll(InputForm.value.transportation, countT.value, TransportationBadge)
    countT.value = []
  } else {
    TransportationBadge.value = ''
  }
  if (val.indexOf('Places') == -1) {
    AddDatePlaceType.value.forEach((item: any) => {
      if (item.partyType != '' && item.partyname.length != 0) {
        countP.value.push(item.partyname)
      }
    })
    changeAll(InputForm.value.palces, countP.value, PlacesBadge)
    countP.value = []
  } else {
    PlacesBadge.value = ''
  }
}
const verification = ref('')
const placesVerification = ref('')
let MoreFiltersObj: any = {}
let MoreFiltersObj2: any = {}
// 赋值
const changeAutoSelect = (Array: any, val: any, value: any, arraykey1: any, arraykey2: any) => {
  if (value == 'InputForm') {
    if (Array) {
      Array[arraykey1][arraykey2] = val.value
      MoreFiltersObj[arraykey2] = val.value.join()
      MoreFiltersObj2[arraykey2] = val.value
    }
  } else if (value == 'AddDateType') {
    if (Array.length) {
      Array.forEach((item: any) => {
        if (item.partyType == arraykey1) {
          item.partyname = val.value
        }
        MoreFiltersObj[item.partyType] = val.value.join()
        MoreFiltersObj2[item.partyType] = val.value
      })
    }
  }
}
const changeAutoSelectshippername = (val: any) => {
  changeAutoSelect(InputForm.value, val, 'InputForm', 'parties', 'shippername')
}
const changeAutoSelectconsigneename = (val: any) => {
  changeAutoSelect(InputForm.value, val, 'InputForm', 'parties', 'consigneename')
}
const changeAutoSelectvessel = (val: any) => {
  changeAutoSelect(InputForm.value, val, 'InputForm', 'transportation', 'vessel')
}
const changeAutoSelectvoyage = (val: any) => {
  changeAutoSelect(InputForm.value, val, 'InputForm', 'transportation', 'voyage')
}
const check = (row: any, value: any, key1: any, key2: any) => {
  value[key1][key2] = row
  MoreFiltersObj[key2] = row
}
//选择origin
const checkorigin = (row: any) => {
  if (row) {
    check(row, InputForm.value, 'palces', 'origin')
  }
}
const checkdestination = (row: any) => {
  if (row) {
    check(row, InputForm.value, 'palces', 'destination')
  }
}
const delSelect = (i: any, val: any) => {
  let index = selectedPartyTypeoptions.value.findIndex((item: any) => {
    return item == val
  })
  if (index >= 0) {
    selectedPartyTypeoptions.value.splice(index, 1)
  }
  let j = selectedPartyTypeIndex.value.findIndex((item: any) => {
    return item == i
  })
  if (j >= 0) {
    for (let i = 0; i < selectedPartyTypeIndex.value.length; i++) {
      if (selectedPartyTypeIndex.value[i] > j) {
        selectedPartyTypeIndex.value[i] = selectedPartyTypeIndex.value[i] - 1
      }
    }
    selectedPartyTypeIndex.value.splice(j, 1)
  }
}
const delPlacesSelect = (i: any, val: any) => {
  let index = selectedPlacesTypeoptions.value.findIndex((item: any) => {
    return item == val
  })
  if (index >= 0) {
    selectedPlacesTypeoptions.value.splice(index, 1)
  }
  let j = selectedPlacesTypeIndex.value.findIndex((item: any) => {
    return item == i
  })
  if (j >= 0) {
    for (let i = 0; i < selectedPlacesTypeIndex.value.length; i++) {
      if (selectedPlacesTypeIndex.value[i] > j) {
        selectedPlacesTypeIndex.value[i] = selectedPlacesTypeIndex.value[i] - 1
      }
    }
    selectedPlacesTypeIndex.value.splice(j, 1)
  }
}
const pushSelectedList = (i: any, val: any) => {
  let index = selectedPartyTypeoptions.value.findIndex((item: any) => {
    return item == val
  })
  if (index < 0) {
    if (!selectedPartyTypeIndex.value.includes(i)) {
      selectedPartyTypeoptions.value.push(val)
      selectedPartyTypeIndex.value.push(i)
    } else {
      let j = selectedPartyTypeIndex.value.findIndex((con: any) => {
        return con == i
      })
      selectedPartyTypeoptions.value.splice(i, 1, val)
    }
  }
}

const pushPlacesSelectedList = (i: any, val: any) => {
  let index = selectedPlacesTypeoptions.value.findIndex((item: any) => {
    return item == val
  })
  if (index < 0) {
    if (!selectedPlacesTypeIndex.value.includes(i)) {
      selectedPlacesTypeoptions.value.push(val)
      selectedPlacesTypeIndex.value.push(i)
    } else {
      let j = selectedPlacesTypeIndex.value.findIndex((con: any) => {
        return con == i
      })
      selectedPlacesTypeoptions.value.splice(i, 1, val)
    }
  }
}
const changeAutoSelectAddType = (index: any, val: any) => {
  pushSelectedList(index, val)
}

const changeAutoSelectPlacesAddType = (index: any, val: any) => {
  pushPlacesSelectedList(index, val)
}
const changeAutoSelectVal = (val: any, value: any) => {
  MoreFiltersObj = { ...MoreFiltersObj, ...val }
  for (const key in value) {
    MoreFiltersObj2[key] = value[key]
  }
}
// 点击search
const emit = defineEmits(['MoreFiltersSearch', 'clearMoreFiltersTags'])
const SearchMore = () => {
  // 判断是否有验证样式
  const input_change = document.getElementsByClassName('input_change')
  if (AddDateType.value.length) {
    AddDateType.value.forEach((item: any, index: any) => {
      if (item.partyType != '' && item.partyname.length == 0) {
        item.isshowVerfication = true
        verification.value = 'Please input Party Details'
        input_change[index].classList.add('AlertInput')
      } else {
        item.isshowVerfication = false
        input_change[index].classList.remove('AlertInput')
      }
    })
    const AlertInput = document.getElementsByClassName('AlertInput')
    if (AlertInput.length == 0) {
      // 传数据给父组件
      emit('MoreFiltersSearch', MoreFiltersObj, MoreFiltersObj2)
      drawer.value = false
    }
  } else {
    // 传数据给父组件
    emit('MoreFiltersSearch', MoreFiltersObj, MoreFiltersObj2)
    drawer.value = false
  }
}
// 清除
const clearrest = () => {
  emit('clearMoreFiltersTags')
  InputForm.value = {
    parties: {
      shippername: [],
      consigneename: []
    },
    transportation: {
      vessel: [],
      voyage: []
    },
    palces: {
      origin: [],
      destination: []
    },
    General: {
      Incoterms: 'Please Select Date Range',
      Service: 'Please Select Date Range'
    }
  }
  AddDateType.value = []
  AddDatePlaceType.value = []
  PartiesBadge.value = ''
  GeneralBadge.value = ''
  TransportationBadge.value = ''
  PlacesBadge.value = ''
  MoreFiltersObj = {}
  selectedPartyTypeoptions.value = []
  selectedPlacesTypeoptions.value = []
  IncotermsList.value.forEach((item) => {
    item.checked = false
  })
  SeiviceList.value.forEach((item) => {
    item.checked = false
  })
  IncotermsCheckAll.value = false
  ServiceCheckAll.value = false
}
// 清除name
const clearname = (val: any, key1: any, key2: any) => {
  if (key2 == 'partyType' || key2 == 'partyname') {
    val[key1][key2] = ''
  } else if (key2 == 'Incoterms') {
    val[key1][key2] = 'Please Select Date Range'
  } else {
    val[key1][key2] = []
  }
  delete MoreFiltersObj[key2]
}
// 清除 MoreFiltersObj
const clearMoreFiltersObj = () => {
  MoreFiltersObj = {}
}
const IncotermsCheckAll = ref(false)
const ServiceCheckAll = ref(false)
const IncotermsList = ref([
  {
    name: 'FOB',
    number: 2229,
    checked: false
  },
  {
    name: 'CIF',
    number: 1000,
    checked: false
  }
])
const SeiviceList = ref([
  {
    name: 'FOB',
    number: 2229,
    checked: false
  },
  {
    name: 'CIF',
    number: 1000,
    checked: false
  }
])
const IncotermsSearch = (val: any) => {
  InputForm.value.General.Incoterms = val.data
  MoreFiltersObj[val.title] = val.data
}
const ServiceSearch = (val: any) => {
  InputForm.value.General.Service = val.data
  MoreFiltersObj[val.title] = val.data
}
</script>
<template>
  <div>
    <el-button class="More_Filters el-button--grey" @click="drawer = true">
      <span class="iconfont_icon icon_more">
        <svg class="iconfont" aria-hidden="true">
          <use xlink:href="#icon-icon_filter_b"></use>
        </svg>
      </span>
      <div class="Filters_title">More Filters</div>
    </el-button>
    <el-drawer size="400px" title="More Filters" v-model="drawer">
      <el-collapse @change="changeCollapse"
        ><!-- General -->
        <el-collapse-item class="collapse_item" name="General" v-if="props.isShipment">
          <template #title>
            <span class="collapse-title"
              >General <el-badge class="mark" :value="GeneralBadge" type="warning"
            /></span>
          </template>
          <div class="ETD">
            <div class="ETD_title">Incoterms</div>
            <SelectValue
              :checkAll="IncotermsCheckAll"
              title="Incoterms"
              :TransportListItem="IncotermsList"
              @generalSearch="IncotermsSearch"
              :Serval="InputForm.General.Incoterms"
            ></SelectValue>
          </div>
          <div class="ETA">
            <div class="ETD_title">Service</div>
            <SelectValue
              :checkAll="ServiceCheckAll"
              title="Service"
              :TransportListItem="SeiviceList"
              @generalSearch="ServiceSearch"
              :Serval="InputForm.General.Service"
            ></SelectValue>
          </div>
        </el-collapse-item>
        <!-- Parties -->
        <el-collapse-item class="collapse_item" name="Parties">
          <template #title>
            <span class="collapse-title"
              >Parties <el-badge class="mark" :value="PartiesBadge" type="warning"
            /></span>
          </template>
          <div class="ETD">
            <div class="ETD_title">Shipper Name</div>
            <AutoSelect
              ASType="contanct"
              @changeAutoSelect="changeAutoSelectshippername"
              :ASValue="InputForm.parties.shippername"
              ASPlaceholder="Please input shipper name"
            >
            </AutoSelect>
          </div>
          <div class="ETA">
            <div class="ETD_title">Consignee Name</div>
            <AutoSelect
              ASType="contanct"
              @changeAutoSelect="changeAutoSelectconsigneename"
              :ASValue="InputForm.parties.consigneename"
              ASPlaceholder="Please input consignee name"
            >
            </AutoSelect>
          </div>
          <SelectAutoSelect
            ref="partSelectTableSelectRef"
            :AddDateType="AddDateType"
            :DateTypeoptions="PartyTypeoptions"
            :Verification="verification"
            @changeAutoSelectAddType="changeAutoSelectAddType"
            @changeAutoSelect="changeAutoSelectVal"
            :selectedPartyTypeoptions="selectedPartyTypeoptions"
            @delSelect="delSelect"
            ASPlaceholder="Please input party name"
          >
          </SelectAutoSelect>
          <div
            class="MoreType"
            @click="AddType('party')"
            v-if="AddDateType.length != PartyTypeoptions.length"
          >
            + More Party Type
          </div>
        </el-collapse-item>
        <!-- Places -->
        <el-collapse-item class="collapse_item" name="Places">
          <template #title
            ><span class="collapse-title"
              >Places<el-badge class="mark" :value="PlacesBadge" type="warning" /></span
          ></template>
          <div class="ETD">
            <div class="ETD_title">Origin</div>
            <SelectTable :searchInput="InputForm.palces.origin" @check="checkorigin" />
          </div>
          <div class="ETA">
            <div class="ETD_title">Destination</div>
            <SelectTable :searchInput="InputForm.palces.destination" @check="checkdestination" />
          </div>
          <SelectTableSelect
            ref="placeSelectTableSelectRef"
            :AddDateType="AddDatePlaceType"
            :DateTypeoptions="PlaceTypeoptions"
            :Verification="placesVerification"
            @changeAutoSelectAddType="changeAutoSelectPlacesAddType"
            @changeAutoSelect="changeAutoSelectVal"
            :selectedPartyTypeoptions="selectedPlacesTypeoptions"
            @delSelect="delPlacesSelect"
            ASPlaceholder="Please input places name"
          >
          </SelectTableSelect>
          <!-- More Place Type -->
          <div
            class="MoreType"
            @click="AddType('place')"
            v-if="AddDatePlaceType.length != PlaceTypeoptions.length"
          >
            + More Place Type
          </div>
        </el-collapse-item>
        <!-- Transportation -->
        <el-collapse-item class="collapse_item" name="Transportation">
          <template #title
            ><span class="collapse-title"
              >Transportation
              <el-badge class="mark" :value="TransportationBadge" type="warning" /></span
          ></template>
          <div class="ETD">
            <div class="ETD_title">Vessel</div>
            <AutoSelect
              ASType="vessel"
              @changeAutoSelect="changeAutoSelectvessel"
              class="input_change"
              :ASValue="InputForm.transportation.vessel"
              ASPlaceholder="Please input vessel name or code"
            >
            </AutoSelect>
          </div>
          <div class="ETA">
            <div class="ETD_title">Voyage/Flight</div>
            <AutoSelect
              ASType="vessel"
              @changeAutoSelect="changeAutoSelectvoyage"
              class="input_change"
              :ASValue="InputForm.transportation.voyage"
              ASPlaceholder="Please input voyage or flight no."
            ></AutoSelect>
          </div>
        </el-collapse-item>
        <!-- Others -->
        <el-collapse-item class="collapse_item" name="Others">
          <template #title><span class="collapse-title">Others</span></template>
        </el-collapse-item>
      </el-collapse>
      <div class="more_bottom">
        <el-button class="reset" type="default" @click="clearrest">
          <span class="iconfont_icon select_icon">
            <svg class="iconfont" aria-hidden="true">
              <use xlink:href="#icon-icon_reset_b"></use>
            </svg>
          </span>
          Reset
        </el-button>
        <el-button class="reset el-button--dark" style="margin-left: 8px" @click="SearchMore">
          <span class="iconfont_icon select_icon search_icon">
            <svg class="iconfont" aria-hidden="true">
              <use xlink:href="#icon-icon_search_b"></use>
            </svg>
          </span>
          Search
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.icon_more {
  margin-left: 8px;
  margin-right: 0;
}

.icon_delete {
  fill: var(--color-danger);
  cursor: pointer;
}

.More_Filters {
  display: flex;
  align-items: center;
  height: 32px;
  font-size: var(--font-size-3);
  margin-left: 8px;
  width: 116px;
}

.More_Filters:hover {
  .Filters_title {
    color: var(--color-theme);
  }
}

.select_icon {
  margin-right: 8px;
}

.Filters_title {
  margin: 0 8px;
}

:deep(.el-drawer__header) {
  background-color: var(--color-table-header-bg);
  display: flex;
  align-items: center;
  height: 64px;
  padding: 0;
  padding-left: 17.12px;
  margin-bottom: 0;
  color: var(--color-neutral-1);
}

:deep(.el-drawer__title) {
  font-size: var(--font-size-6);
  font-weight: bold;
}

:deep(.el-drawer__close-btn) {
  font-size: var(--font-size-4);
  color: var(--icon-color-black);
  margin-right: 24px;
  padding: 0;
}

:deep(.el-drawer__body) {
  padding: 0;
  position: relative;
}

.collapse-title {
  flex: 1 0 90%;
  order: 1;
  text-align: left;
}

:deep(.el-collapse-item__header) {
  border-bottom: none;
  height: 48px;
  color: var(--icon-color-blac);
  font-size: var(--font-size-4);
  font-weight: bold;
  padding-left: 16px;
}

:deep(.el-collapse-item__wrap) {
  border-bottom: none;
  background-color: var(--more-filters-background-color);
}

.ETD {
  margin: 8px 16px;
}

.ETA {
  margin: 16px 16px;
}

.ETD_title {
  font-size: var(--font-size-2);
  color: var(--color-neutral-2);
}

.Date_Title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.MoreType {
  color: var(--color-accent-2);
  padding: 0 0 16px 16px;
  cursor: pointer;
}

.AddType {
  background-color: var(--addparties-background-color);
  margin: 0 16px 8px 16px;
  padding: 8px;
  border-radius: var(--border-radius-6);
}

.more_bottom {
  display: flex;
  align-items: center;
  bottom: 0;
  height: 64px;
  border-top: 1px solid var(--color-border-top);
  width: 400px;
  padding: 16px;
}

.reset {
  width: 180px;
  display: flex;
  align-items: center;
  height: 40px;
  justify-content: center;
  border: 1px solid var(--color-accent-13);
  border-radius: var(--border-radius-6);
}

.AlertInput :deep(.el-select__wrapper) {
  box-shadow: 0 0 0 0.5px var(--color-danger);
}

:deep(.el-drawer__body) {
  padding: 0 !important;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  overflow-x: hidden;
}

:deep(.el-overlay) {
  background-color: transparent;
}
:deep(.el-drawer__close-btn) {
  margin-right: 0;
}
</style>
