<script setup lang="ts">
import emitter from '@/utils/bus'
import { ref, computed, onMounted, onBeforeMount } from 'vue'
import IconDropDown from '@/components/IconDropDown'
import CalendarDate from './components/CalendarDate.vue'
import moment from 'moment'
import dayjs from 'dayjs'

onMounted(() => {
  defaultDate()
  emitter.on('clearTag', (tag: any) => {
    if (tag.includes('ETD')) {
      clearDateStart()
    } else if (tag.includes('ETA')) {
      clearDateEnd()
    } else {
      clearDateCreation()
    }
  })
  emitter.on('clearDaterangeObj', () => {
    clearDaterangeObj()
  })
})

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

const Date_visible = ref(false)
const DateType = ref()
const DateTypeoptions = ref([
  {
    value: 'Creation Time',
    label: 'Creation Time'
  }
])
const AddDateType = ref()
AddDateType.value = []
const AddType = () => {
  AddDateType.value.push({
    value: '',
    number: ''
  })
}
const deleteType = (i: any) => {
  AddDateType.value.splice(i, 1)
  DateType.value = ''
  clearDateCreation()
}
const props = defineProps({
  isShipment: Boolean
})
let daterangeObj: any = {}
const DateStart = ref()
DateStart.value = []
const DateEnd = ref()
DateEnd.value = []
const DateCreation = ref()
DateCreation.value = []
const searchTableQeury = ref()
const searchTableQeuryTracking = ref()
// 查询默认日期
const defaultDate = () => {
  if (props.isShipment) {
    if (
      sessionStorage.getItem('clickParams') == null ||
      sessionStorage.getItem('clickParams') == '{}'
    ) {
      if (sessionStorage.getItem('searchTableQeuryTracking') == null) {
        DateStart.value = [dayjs().subtract(2, 'month').startOf('month'), dayjs().add(1, 'month')]
        daterangeObj.ETD =
          DateStart.value[0].format('MMM/DD/YYYY') +
          ' To ' +
          DateStart.value[1].format('MMM/DD/YYYY')
        const obj = {
          title: 'ETD',
          data: [DateStart.value[0].format('MM/DD/YYYY'), DateStart.value[1].format('MM/DD/YYYY')]
        }
        daterangeObj2.ETD = obj
      } else {
        searchTableQeuryTracking.value =
          JSON.parse(sessionStorage.getItem('searchTableQeuryTracking') as string) || {}
        if (searchTableQeuryTracking.value.etd_start) {
          DateStart.value = [
            dayjs(searchTableQeuryTracking.value.etd_start),
            dayjs(searchTableQeuryTracking.value.etd_end)
          ]
          daterangeObj.ETD =
            DateStart.value[0].format('MMM/DD/YYYY') +
            ' To ' +
            DateStart.value[1].format('MMM/DD/YYYY')
          const obj = {
            title: 'ETD',
            data: [DateStart.value[0].format('MM/DD/YYYY'), DateStart.value[1].format('MM/DD/YYYY')]
          }
          daterangeObj2.ETD = obj
        }
        if (searchTableQeuryTracking.value.eta_start) {
          DateEnd.value = [
            dayjs(searchTableQeuryTracking.value.eta_start),
            dayjs(searchTableQeuryTracking.value.eta_end)
          ]
          daterangeObj.ETA =
            DateEnd.value[0].format('MMM/DD/YYYY') + ' To ' + DateEnd.value[1].format('MMM/DD/YYYY')
          const obj = {
            title: 'ETA',
            data: [DateEnd.value[0].format('MM/DD/YYYY'), DateEnd.value[1].format('MM/DD/YYYY')]
          }
          daterangeObj2.ETA = obj
        }
        if (searchTableQeuryTracking.value.created_time_start) {
          DateCreation.value = [
            dayjs(searchTableQeuryTracking.value.created_time_start),
            dayjs(searchTableQeuryTracking.value.created_time_end)
          ]
          daterangeObj['Creation Time'] =
            DateCreation.value[0].format('MMM/DD/YYYY') +
            ' To ' +
            DateCreation.value[1].format('MMM/DD/YYYY')
          const obj = {
            title: 'Creation Time',
            data: [
              DateCreation.value[0].format('MM/DD/YYYY'),
              DateCreation.value[1].format('MM/DD/YYYY')
            ]
          }
          daterangeObj2['Creation Time'] = obj
        }
      }
      emit('defaultDate', daterangeObj, daterangeObj2, searchTableQeuryTracking.value)
    } else {
      const data = JSON.parse(sessionStorage.getItem('reportList') as string) || {}
      searchTableQeuryTracking.value =
        JSON.parse(sessionStorage.getItem('searchTableQeuryTracking') as string) || {}
      if (data.eta_start) {
        DateEnd.value = [dayjs(data.eta_start), dayjs(data.eta_end)]
        daterangeObj.ETA =
          DateEnd.value[0].format('MMM/DD/YYYY') + ' To ' + DateEnd.value[1].format('MMM/DD/YYYY')
        const obj = {
          title: 'ETA',
          data: [DateEnd.value[0].format('MM/DD/YYYY'), DateEnd.value[1].format('MM/DD/YYYY')]
        }
        daterangeObj2.ETA = obj
        emit('defaultDate', daterangeObj, daterangeObj2, searchTableQeuryTracking.value)
      }
      if (data.etd_start) {
        DateStart.value = [dayjs(data.etd_start), dayjs(data.etd_end)]
        daterangeObj.ETD =
          DateStart.value[0].format('MMM/DD/YYYY') +
          ' To ' +
          DateStart.value[1].format('MMM/DD/YYYY')
        const obj = {
          title: 'ETD',
          data: [DateStart.value[0].format('MM/DD/YYYY'), DateStart.value[1].format('MM/DD/YYYY')]
        }
        daterangeObj2.ETD = obj
        emit('defaultDate', daterangeObj, daterangeObj2, searchTableQeuryTracking.value)
      }
    }
  } else {
    if (sessionStorage.getItem('searchTableQeury') == null) {
      DateStart.value = [dayjs().subtract(2, 'month').startOf('month'), dayjs().add(1, 'month')]
      daterangeObj.ETD =
        DateStart.value[0].format('MMM/DD/YYYY') + ' To ' + DateStart.value[1].format('MMM/DD/YYYY')
      const obj = {
        title: 'ETD',
        data: [DateStart.value[0].format('MM/DD/YYYY'), DateStart.value[1].format('MM/DD/YYYY')]
      }
      daterangeObj2.ETD = obj
    } else {
      searchTableQeury.value =
        JSON.parse(sessionStorage.getItem('searchTableQeury') as string) || {}
      if (searchTableQeury.value.f_etd_start) {
        DateStart.value = [
          dayjs(searchTableQeury.value.f_etd_start),
          dayjs(searchTableQeury.value.f_etd_end)
        ]
        daterangeObj.ETD =
          DateStart.value[0].format('MMM/DD/YYYY') +
          ' To ' +
          DateStart.value[1].format('MMM/DD/YYYY')
        const obj = {
          title: 'ETD',
          data: [DateStart.value[0].format('MM/DD/YYYY'), DateStart.value[1].format('MM/DD/YYYY')]
        }
        daterangeObj2.ETD = obj
      }
      if (searchTableQeury.value.m_eta_start) {
        DateEnd.value = [
          dayjs(searchTableQeury.value.m_eta_start),
          dayjs(searchTableQeury.value.m_eta_end)
        ]
        daterangeObj.ETA =
          DateEnd.value[0].format('MMM/DD/YYYY') + ' To ' + DateEnd.value[1].format('MMM/DD/YYYY')
        const obj = {
          title: 'ETA',
          data: [DateEnd.value[0].format('MM/DD/YYYY'), DateEnd.value[1].format('MM/DD/YYYY')]
        }
        daterangeObj2.ETA = obj
      }
      if (searchTableQeury.value.created_time_start) {
        DateCreation.value = [
          dayjs(searchTableQeury.value.created_time_start),
          dayjs(searchTableQeury.value.created_time_end)
        ]
        daterangeObj['Creation Time'] =
          DateCreation.value[0].format('MMM/DD/YYYY') +
          ' To ' +
          DateCreation.value[1].format('MMM/DD/YYYY')
        const obj = {
          title: 'Creation Time',
          data: [
            DateCreation.value[0].format('MM/DD/YYYY'),
            DateCreation.value[1].format('MM/DD/YYYY')
          ]
        }
        daterangeObj2['Creation Time'] = obj
      }
    }
    emit('defaultDate', daterangeObj, daterangeObj2, searchTableQeury.value)
  }
}
const daterangedata = ref()
daterangedata.value = []
let daterangeObj2: any = {}
const DateRangeChange = (val: any) => {
  if (val.data != null) {
    const date1 = moment(String(val.data[0])).format('MMM-DD-YYYY')
    const date2 = moment(String(val.data[1])).format('MMM-DD-YYYY')
    daterangeObj[val.title] = date1 + ' To ' + date2
    daterangeObj2[val.title] = val
  } else {
    delete daterangeObj[val.title]
    delete daterangeObj2[val.title]
    if (val.title == 'ETD') {
      DateStart.value = []
    } else if (val.title == 'ETA') {
      DateEnd.value = []
    } else {
      DateCreation.value = []
      AddDateType.value = []
      DateType.value = ''
    }
  }
}
const emit = defineEmits(['DateRangeSearch', 'clearDaterangeTags', 'defaultDate'])
const DateRangeSearch = () => {
  emit('DateRangeSearch', daterangeObj, daterangeObj2)
  Date_visible.value = false
}
const CalendarTitle = computed(() => {
  if (DateType.value == 'undefined') {
    return 'Date Range'
  } else {
    return DateType.value
  }
})
// 清除
const clearrest = () => {
  emit('clearDaterangeTags')
  clearDateStart()
  clearDateEnd()
  clearDateCreation()
  clearDaterangeObj()
}
// 清除EDT
const clearDateStart = () => {
  DateStart.value = []
  delete daterangeObj['ETD']
  delete daterangeObj2['ETD']
}
// 清除EDA
const clearDateEnd = () => {
  DateEnd.value = []
  delete daterangeObj['ETA']
  delete daterangeObj2['ETA']
}
// 清除Creation Time
const clearDateCreation = () => {
  DateCreation.value = []
  AddDateType.value = []
  DateType.value = ''
  delete daterangeObj['Creation Time']
  delete daterangeObj2['Creation Time']
}
// 清除 daterangeObj
const clearDaterangeObj = () => {
  daterangeObj = {}
  daterangeObj2 = {}
}
</script>
<template>
  <div class="select">
    <el-popover trigger="click" :width="400" :visible="Date_visible">
      <template #reference>
        <div class="Date_Range" @blur="Date_visible = false" @click="Date_visible = !Date_visible">
          <div class="select_title">Date Range</div>
          <span class="iconfont_icon">
            <svg class="iconfont" aria-hidden="true">
              <use xlink:href="#icon-icon_dropdown_b"></use>
            </svg>
          </span>
        </div>
      </template>
      <div>
        <div class="title">Date Range</div>
        <div class="ETD">
          <CalendarDate
            CalendarTitle="ETD"
            :Date="DateStart"
            @DateRangeChange="DateRangeChange"
          ></CalendarDate>
        </div>
        <div class="ETA">
          <CalendarDate
            CalendarTitle="ETA"
            :Date="DateEnd"
            @DateRangeChange="DateRangeChange"
          ></CalendarDate>
        </div>
        <div class="AddType" v-for="(item, index) in AddDateType" :key="item">
          <div>
            <div class="ETD_title Date_Title">
              <div>Date Type</div>
              <span class="iconfont_icon" @click="deleteType(index)">
                <svg class="iconfont icon_delete" aria-hidden="true">
                  <use xlink:href="#icon-icon_delete_b"></use>
                </svg>
              </span>
            </div>
            <el-select
              :suffix-icon="IconDropDown"
              placeholder="Please Select Date Type"
              v-model="DateType"
            >
              <el-option
                v-for="item in DateTypeoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div style="margin-top: 16px">
            <CalendarDate
              :CalendarTitle="CalendarTitle"
              CalendarWidth="352px"
              :Date="DateCreation"
              @DateRangeChange="DateRangeChange"
            ></CalendarDate>
          </div>
        </div>
        <div class="MoreType" @click="AddType" v-if="AddDateType.length != DateTypeoptions.length">
          <el-button class="el-button--noborder moretype">+ More Date Type</el-button>
        </div>
        <div class="daterange_bottom">
          <div><el-button type="default" @click="clearrest" class="Clear">Reset</el-button></div>
          <div>
            <el-button class="search el-button--dark" @click="DateRangeSearch">Search</el-button>
          </div>
        </div>
      </div>
    </el-popover>
  </div>
</template>
<style lang="scss" scoped>
.iconfont_icon {
  margin-right: 8px;
}
.icon_delete {
  fill: var(--color-danger);
}
.select {
  width: 186px;
  margin-left: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-6);
}
.Date_Range {
  width: 186px;
  display: flex;
  position: relative;
  align-items: center;
  justify-content: space-between;
}
.select_title {
  font-size: var(--font-size-3);
  font-weight: 400;
  margin-left: 8.53px;
  color: var(--color-neutral-1);
}
.select_icon {
  width: 16px;
  margin-right: 10.5px;
}
.select:hover {
  border: 1px solid var(--color-theme);
}
.title {
  font-weight: 700;
  font-size: var(--font-size-5);
  background-color: #f6f8fa;
  height: 48px;
  display: flex;
  align-items: center;
  padding-left: 16px;
}
.ETD {
  margin: 8px 16px;
}
.ETA {
  margin: 16px 16px;
}
.ETD_title {
  font-size: var(--font-size-2);
  margin-bottom: 4px;
  color: var(--color-neutral-2);
}
.Date_Title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
:deep(.el-dialog__header) {
  display: none;
}
:deep(div.el-dialog) {
  width: 400px;
  padding: 0;
  margin-top: 202px;
  border: 1px solid var(--color-border);
}
:deep(div.el-dialog__body) {
  padding: 0;
}
.MoreType {
  color: var(--color-accent-2);
  padding: 0 0 16px 16px;
}
:deep(.el-select__wrapper) {
  border-radius: var(--border-radius-6);
  height: 40px;
}
.AddType {
  background-color: var(--color-neutral-4);
  margin: 0 16px 8px 16px;
  padding: 8px;
  border-radius: var(--border-radius-6);
}
.daterange_bottom {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 48px;
  border-top: 1px solid var(--color-border);
  margin-top: 5px;
  font-weight: 400;
  font-size: var(--font-size-3);
}
.Clear {
  width: 81px;
  height: 32px;
  margin-right: 7.82px;
}
.search {
  width: 86px;
  height: 32px;
  margin-right: 16px;
}
:deep(.el-date-editor .el-range__icon) {
  position: absolute;
  right: 16px;
}
@media only screen and (min-width: 1280px) {
  .Date_Range,
  .select {
    width: 224px;
  }
}
@media only screen and (min-width: 1440px) {
  .Date_Range,
  .select {
    width: 336px;
  }
}
.moretype {
  background-color: transparent;
  padding: 0 4px;
  height: 24px;
}
</style>