<script lang="ts" setup>
import { debounce } from 'lodash-es'
import {
  computed,
  inject,
  onBeforeMount,
  onMounted,
  onUnmounted,
  ref,
  shallowRef,
  unref,
  watch,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import CustomFieldModal from '../modal/CustomFieldModal.vue'
import AdvanceFilter from '../../home/aside/comp/AdvanceFilter.vue'
import { FilterModalVue } from '../../home/aside/comp/modals'
import NewFilterModalVue from '../modal/NewFilterModal.vue'
import TaskList from './TaskList.vue'
import type { AsideEntity } from '@/config/aside'
import { useUser } from '@/store/modules/user'
import { getAllfieldList, getConditionList, getfieldList } from '@/api/home/filter'
import { useTaskStore } from '@/store/modules/task'
import emitter from '@/utils/mitt'
import { useConfig } from '@/store/modules/asideConfig'

import type { FilterSearchParam } from '/#/api'

const route = useRoute()
const router = useRouter()
const searchContent = route.query.searchContent as string
const CustomFieldModalRef = ref(null)
const collapse = ref(false)
const taskStore = useTaskStore()
const taskListRef: any = ref(null)
const AdvanceFilterRef: any = ref(null)
// 展示字段
const showFieldList = ref<any[]>([])
const search = ref('')
function collapseHandler() {
  collapse.value = !collapse.value
}
const mousetrap = inject('mousetrap') as any
mousetrap.bind('[', collapseHandler)
const asideWidth = computed(() => {
  return collapse.value ? 0 : 308
})

const asideStyle = computed(() => {
  return {
    width: `${asideWidth.value}px`,
  }
})

const collapseIcon = computed(() => {
  return collapse.value ? 'expand-cir' : 'collapse-cir'
})

const asideEnter = ref(false)

const showCollapse = computed(() => {
  return collapse.value ? true : asideEnter.value
})

watch(
  () => taskStore.immersion,
  () => {
    collapse.value = true
  },
)

function showFilter() {
  const modal = unref(CustomFieldModalRef)! as any
  modal.showModal()
}

const showSearch = ref(false)

function setShowSearch(value: boolean) {
  if (!value) {
    search.value = ''
    taskListRef.value.search('')
    if (searchContent)
      router.replace(route.path)
  }
  showSearch.value = value
}

const inputHandler = debounce((word) => {
  (taskListRef.value as any).search(word)
}, 500)

const reviewType = 2
async function getshowFieldList() {
  showFieldList.value = []
  const userStore = useUser()
  const userInfo = userStore.getUserInfo
  let res
  res = await getAllfieldList(reviewType) // 所有筛选项目
  const allList = res.data
  res = await getfieldList(reviewType, userInfo.id) // 当前用户选择的项目
  const useList = res.data
  /**
   * name 标题
   * id 键值
   * fix 是否默认
   * checked 是否选中
   */
  if (useList?.userFieldFixed) {
    useList?.userFieldFixed?.split(',').map((v) => {
      let item = allList.find(v2 => v2.name == v)
      if (item) {
        item = {
          name: item.fieldDesc,
          id: item.name,
          fix: item.isrequired == 2,
          checked: true,
        }
        showFieldList.value.push(item)
      }
      return v
    })
  }
  else {
    // 若为首次获取 则赋默认值
    allList?.map((v) => {
      if (v.isrequired == 2) {
        const item = {
          name: v.fieldDesc,
          id: v.name,
          fix: v.isrequired == 2,
          checked: true,
        }
        showFieldList.value.push(item)
      }
      return v
    })
  }
}

onMounted(() => {
  getshowFieldList()
  window.addEventListener('keydown', handleKeydown)
  init()
})
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown)
})
async function init() {
  try {
    const searchParam: FilterSearchParam = {
      search_searchname: { value: '', op: 'like', type: 'string' },
    }
    const result = await getConditionList(1, searchParam, 2)
    const { data } = result
    if (data[0]) {
      AdvanceFilterRef.value.setCurrentlySelectedAdvanced(data[0].searchname)
      setTimeout(() => {
        filterHandler(data[0].id)
      }, 1000)
      // filterHandler(data[0].id);
    }
    // pagination.pageNo += 1
  }
  catch (error) {
    return []
  }
  // currentlySelectedAdvanced.value="邱霞"
}
function handleKeydown(event) {
  if (event.key === 's')
    setShowSearch(true)
}
// 滚动容器，让key对应模块处于可视区域
function scrollHandler(key: string) {
  const element = document.querySelector(`#${key}`)
  element?.scrollIntoView(true)
}
// 选择某个过滤配置，刷新图片墙
function filterHandler(searchId: string) {
  emitter.emit('filter', searchId)
}
function showModal(modalRef: any) {
  const modal = unref(modalRef)! as any
  modal.showModal()
}
// 当前显示的模块，按照数组顺序显示
const showItems = shallowRef<{ key: string, config: AsideEntity }[]>([])
const filterModalRef: any = ref(null)
const newFilterModalRef = ref(null)
const customModalRef = ref(null)
function editFilter(filter: any) {
  const modal = unref(newFilterModalRef)! as any
  modal.showModal()
  modal.edit(filter)
}
const configStore = useConfig()
function newFilterOk() {
  filterModalRef.value.query(
    filterModalRef.value.pagination.page,
    filterModalRef.value.pagination.pageSize,
  )
  filterModalRef.value.closeModal()
}
onBeforeMount(async () => {
  configStore.fetchConfig()
  configStore.fetchCustomConfig()
})
function setAsideItemName(text) {
  taskListRef.value.setStatusName(text)
}

defineExpose({
  setAsideItemName,
})

function initSerach() {
  if (searchContent) {
    setShowSearch(true)
    const id_param = searchContent.match(/-\d+-/)
    if (id_param) {
      search.value = id_param[0].slice(1, -1)
      inputHandler(id_param[0].slice(1, -1))
    }
  }
}
initSerach()

function handleOk(item: any) {
  if (item) {
    AdvanceFilterRef.value.setCurrentlySelectedAdvanced(item.searchname)
    filterHandler(item.id)
  }
  else {
    AdvanceFilterRef.value.setCurrentlySelectedAdvanced('高级筛选')
    filterHandler('')
  }
}
</script>

<template>
  <div
    class="aside"
    :style="asideStyle"
    @mouseenter="asideEnter = true"
    @mouseleave="asideEnter = false"
  >
    <div v-show="showCollapse" class="aside-collapse">
      <div class="aside-collapse-btn" @click="collapseHandler">
        <SvgIcon :name="collapseIcon" size="40" />
      </div>
    </div>

    <div class="aside-header" :style="`display:${asideWidth == 0 ? 'none' : ''}`">
      <!-- <div v-show="!showSearch" class="warpper">
        <div class="left">
          <svg-icon name="all-worksheet" size="32" />
          <span style="margin-left: 8px">所有请求</span>
        </div>
        <div class="right">
          <SvgIcon
            style="cursor: pointer; margin-left: 10px"
            size="18"
            name="magnifying-1"
            @click="setShowSearch(true)"
          />
          <SvgIcon
            style="cursor: pointer; margin-left: 10px"
            size="18"
            name="filter"
            @click="showFilter"
          />
        </div>
      </div> -->
      <!-- 高级筛选 -->
      <AdvanceFilter
      :icontype=1
        v-show="!showSearch"
        ref="AdvanceFilterRef"
        :type="2"
        toolipvalue="请输入任务id、任务名称、提报人"
        @select="filterHandler"
        @update:search="setShowSearch(true)"
        @show-custom="showModal(CustomFieldModalRef)"
        @show-filter="showModal(filterModalRef)"
      />

      <div v-show="showSearch" class="warpper">
        <n-input
          v-model:value="search"
          style="flex: 1; height: 32px"
          placeholder="请输入任务id、任务名称、提报人"
          @input="inputHandler"
        >
          <template #suffix>
            <SvgIcon size="14px" name="magnifying-1" />
          </template>
        </n-input>
        <SvgIcon
          size="16px"
          style="margin-left: 6px; cursor: pointer"
          name="clear"
          @click="setShowSearch(false)"
        />
      </div>
    </div>
    <TaskList
      ref="taskListRef"
      :show-field-list="showFieldList"
      style="height: 811px"
      class="work-sheet-list"
    />
    <!-- calc(100vh - 146px) -->
    <CustomFieldModal
      ref="CustomFieldModalRef"
      :review-type="reviewType"
      @on-ok="getshowFieldList"
    />
    <!-- 过滤列表 -->
    <FilterModalVue
      ref="filterModalRef"
      :type="2"
      @edit-filter="editFilter"
      @show-new-filter="showModal(newFilterModalRef)"
      @handle-ok="handleOk"
    />
    <!-- 新增过滤 -->
    <NewFilterModalVue ref="newFilterModalRef" @on-ok="newFilterOk" />
  </div>
</template>

<style lang="less" scoped>
.aside {
  display: flex;
  position: relative;
  flex-direction: column;
  background: #fff;
  border: 1px solid rgb(239, 239, 245);
  border-radius: 3px;
  box-sizing: border-box;
   margin-left: 16px;
    margin-right: 16px;

  &-header {
    padding: 12px 16px;
    width: 100%;
    overflow: hidden;
    border-bottom: 1px solid #e8e8e8;
    height: 58px;

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

    &-title {
      margin-left: 8px;
      color: #333333;
      font-size: 16px;
      font-weight: bold;
    }

    .left {
      display: flex;
      align-items: center;
      overflow: hidden;
    }

    .right {
      display: flex;
      align-items: center;
      overflow: hidden;
    }
  }

  &-divider {
    margin-left: 16px;
    width: 292px;
    height: 1px;
    background-color: #e8e8e8;
  }

  &-collapse {
    width: 2px;
    height: 100%;
    background: #507afd;
    position: absolute;
    right: -2px;
    top: 0;
  }

  &-collapse-btn {
    position: absolute;
    cursor: pointer;
    width: 40px;
    height: 40px;
    top: calc(15%);
    right: -20px;
    z-index: 10;
  }
}
::v-deep(.aside-header){
      padding-bottom: 47px !important;
}
 ::v-deep(.list){
    height: calc(100vh - 253px);
            background: #fff
  }

  @media (max-height: 900px) {
  ::v-deep(.list){
    height: calc(100vh - 234px);
            background: #fff
  }}
   ::v-deep(.wrapper-left-popover){
    left: -25px !important;
  }
</style>

