<template>
  <div class="page-content top-select-list" ref="pageContent">
    <div v-if="userInfo.roleId === '1' || userInfo.roleId === '9' || userInfo.roleId === '10' || userInfo.roleId === '6'
      || userInfo.roleId === '7' || userInfo.roleId === '16'" class="addDiv success-background-color"
      @click="$router.push({ name: 'communicate-detail', query: { addDay: selectDay } })">
      <div class="text-center addDiv1">新增</div>
      <div class="text-center addDiv2">沟通</div>
    </div>
    <div class="top-select border-bottom-1">
      <van-dropdown-menu>
        <van-dropdown-item :title="cusName" ref="itemRef">
          <van-field v-model="searchValue" placeholder="请输入机构" @input="onSearchInput"
            :right-icon="searchValue ? 'clear' : ''" @click-right-icon.stop="clearSearch" />
          <van-picker show-toolbar title="机构列表" :columns="list" @confirm="onConfirm" @cancel="onCancel" />
        </van-dropdown-item>
        <van-dropdown-item v-model="linkType" :options="linkTypeList" @change="getLinkList" />
        <van-dropdown-item v-model="saleId" :options="saleList" @change="getLinkList" />
      </van-dropdown-menu>
    </div>
    <van-calendar title="" :poppable="false" :show-confirm="false" switch-mode="year-month" first-day-of-week="1"
      :style="{ height: '410px' }" :formatter="formatter" :default-date="defaultDate" @panel-change="panelChange"
      @select="onDateConfirm" />
    <communicate-item class="pb-16" :list="list" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { scrollList } from '@/mixins/scroll-list'
import { convertToUrl } from '@/utils'
import userInfoStore from '@/stores/userInfo'
const userInfo = userInfoStore()

import { cusLinkInfo, cusLinkList, sysUserGetSaleAndManagerList, cusInfoLookUp } from '@/utils/api'
let cusName = ref('机构')
let cusId = ref('')
let searchValue = ref('')
let itemRef = ref(null)
import { debounceThrottle } from '@/mixins/debounce-throttle'
const { throttle } = debounceThrottle()
const onSearchInput = throttle(
  async () => {
    if (searchValue.value) {
      const { data } = await cusInfoLookUp({ cusName: searchValue.value })
      list.value = data.map((ele: any) => {
        ele.text = ele.cusName
        ele.value = ele.cusId
        return ele
      })
    } else {
      list.value = []
    }
  },
  500
)

const clearSearch = () => {
  searchValue.value = ''
}

const onConfirm = (e: any) => {
  console.log(e)
  if (e.selectedValues.length > 0) {
    cusName.value = e.selectedOptions[0].cusName
    cusId.value = e.selectedOptions[0].cusId
    searchValue.value = e.selectedOptions[0].cusName
    getLinkList()
  }
  itemRef.value.toggle()
}

const onCancel = () => {
  itemRef.value.toggle()
}

let linkType = ref('31,32,34')
let linkTypeList: any = ref([{
  text: '全部类型',
  value: '31,32,34'
}, {
  text: '上市公司按需会议',
  value: '31'
}, {
  text: '机构路演',
  value: '32'
}, {
  text: '机构沟通',
  value: '34'
}])

let saleId = ref('')
let saleList: any = ref([])
const getSaleList = async () => {
  const { data } = await sysUserGetSaleAndManagerList()
  saleList.value = data.map((ele: any) => {
    ele.text = ele.userName
    ele.value = ele.userId
    return ele
  })
  saleList.value.unshift({ text: '全部负责人', value: '' })
}
getSaleList()

let defaultDate = ref()
import moment from 'moment'
const panelChange = (e: any) => {
  dateBegin.value = moment(e.date).startOf('month').format('YYYY-MM-DD')
  dateEnd.value = moment(e.date).endOf('month').format('YYYY-MM-DD')
  getLinkList()
}

const onDateConfirm = (e: any) => {
  defaultDate.value = e
  getList()
}

let list: any = ref([])
let selectDay = ref('')
const getList = () => {
  list.value = []
  selectDay.value = moment(defaultDate.value).format('YYYY-MM-DD')
  linkList.value.forEach((ele: any) => {
    if (ele.sysDay === selectDay.value) {
      list.value = ele.list
    }
  })
}

const formatter = computed(() => {
  if (linkList.value.length === 0) {
    return (day: any) => day
  }
  return (day: any) => {
    let time = moment(day.date).format('YYYY-MM-DD')
    linkList.value.forEach((ele: any) => {
      if (ele.sysDay === time) {
        day.topInfo = ele.num
      }
    })
    return day
  }
})

const dateBegin = ref()
const dateEnd = ref()
const linkList: any = ref([])
const getLinkList = async () => {
  let url = getLinkParams()
  const data = await cusLinkList(url)
  let map = new Map()
  data.forEach((item: any, index: any, arr: any) => {
    if (!map.has(item.sysDay)) {
      map.set(
        item.sysDay,
        arr.filter((a: any) => a.sysDay == item.sysDay)
      )
    }
  })
  let res = Array.from(map).map((item) => [...item[1]])
  linkList.value = []
  res.forEach((ele: any) => {
    linkList.value.push({ sysDay: ele[0].sysDay, num: ele.length, list: ele })
  })
  getList()
}

const getLinkParams = () => {
  const res = {
    dateBegin: dateBegin.value,
    dateEnd: dateEnd.value,
    limit: 999,
    dataStatus: 1,
    curPage: 1,
    saleId: saleId.value,
    linkTypes: linkType.value,
    cusId: cusId.value
  }
  const url = convertToUrl(res)
  return url
}

let pageContent = ref(null)
const scrollPosition = ref(0)
const refresh = async (type: any, id: any) => {
  if (type === 'delete' || type === 'refresh') {
    let dayIndex = linkList.value.findIndex((ele: any) => {
      return ele.sysDay === selectDay.value
    })
    if (dayIndex > -1) {
      let index = linkList.value[dayIndex].list.findIndex((ele: any) => {
        return Number(ele.linkId) === Number(id)
      })
      if (type === 'delete') {
        if (index > -1) {
          linkList.value[dayIndex].list.splice(index, 1)
          linkList.value[dayIndex].num -= 1
        }
      } else {
        if (index > -1) {
          const { data } = await cusLinkInfo(id)
          switch (data.linkTypeMenu) {
            case '32':
              data.tagColor = 'danger-background-color'
              break
            case '34':
              data.tagColor = 'primary-background-color'
              break
            case '31':
              data.tagColor = 'success-background-color'
              break
          }
          linkList.value[dayIndex].list[index] = data
        }
        getList()
      }
    }
  } else {
    defaultDate.value = new Date()
    dateBegin.value = moment().startOf('month').format('YYYY-MM-DD')
    dateEnd.value = moment().endOf('month').format('YYYY-MM-DD')
    getLinkList()
  }
}
const { setScrollTop, setScrollPositionAndRefreshFlag } = scrollList(pageContent, scrollPosition, refresh)
setScrollTop()
import { onBeforeRouteLeave } from 'vue-router'
onBeforeRouteLeave((to, from) => {
  setScrollPositionAndRefreshFlag(to, 'communicate-detail')
})
</script>

<style lang='scss' scoped>
:deep(.van-calendar__header-title) {
  display: none;
}

:deep(.van-calendar__top-info) {
  width: 16px;
  height: 16px;
  left: calc(100vw / 7 - 20px);
  border-radius: 100%;
  background-color: #f56c6c;
  color: #fff;

  @media screen and (min-width: 678px) {
    left: 58px;
  }
}

:deep(.van-calendar__day) {
  border: 1px solid #f2f2f2;
  margin-bottom: 0;
}
</style>
