<script setup>
import { reactive, ref, watch } from 'vue'
import { SearchIcon, Icon } from 'tdesign-icons-vue-next';
import { apiETAChart } from '@/api/etaChart'
import { apiSystemCommon } from '@/api/system'
import { useClassify } from '../hooks/useClassify'

const emits = defineEmits(['change', 'filter'])

const userProps = {
  label: 'RealName',
  value: 'AdminId',
  children: 'ChildrenList'
}
const userOpts = ref([])
const { userVal } = useClassify()
async function getCompanyUserData() {
  const res = await apiSystemCommon.companyUserList()
  if (res.Ret === 200) {
    userOpts.value = res.Data.List || []
  }
}
getCompanyUserData()
watch(
  ()=>userVal.value,
  (n)=>{
    emits('filter')
    getClassify()
  }
)
// 2024-4-26 目前组件库change事件有bug会触发多次
// function handleUserChange(value,context) {
//   emits('filter')
//   getClassify()
// }

const searchSelectKeys = {
  value: 'ChartInfoId',
  label: 'ChartName'
}
const searchVal = ref('')
const searchOpts = ref([])
const searchLoading = ref(false)
let searchPage = 1
const searchPageSize = 20
let finished = false
function handleSearchChart(keyword) {
  finished = false
  searchPage = 1
  searchOpts.value = []
  handleGetSearchChartList(keyword)
}
async function handleGetSearchChartList(keyword) {
  searchLoading.value = true
  const res = await apiETAChart.chartSearch({
    PageSize: searchPageSize,
    CurrentIndex: searchPage,
    SysUserIds: userVal.value?.join(','),
    Keyword: keyword
  })
  searchLoading.value = false
  if (res.Ret === 200) {
    const arr = res.Data.List || []
    searchOpts.value = [...searchOpts.value, ...arr]
    finished = res.Data.Paging.IsEnd
  }
}
async function handleLoadMoreChart() {
  if (finished || searchLoading.value) return
  handleGetSearchChartList()
}
function handleSelectChart(value, context) {
  if (value) {
    emits('change', context.option)
  }
}




//分类列表
const classifyTreeKeys = {
  label: 'ChartClassifyName',
  children: 'Children',
  value: 'ChartClassifyId'
}
const classifyList = ref([])
const { classifyActived } = useClassify()
async function getClassify() {
  const res = await apiETAChart.classifyList({
    ParentId: -1,
    SysUserIds: userVal.value?.join(',')
  })
  if (res.Ret === 200) {
    const arr = res.Data.AllNodes || []
    classifyList.value = arr.map(item => {
      return {
        ...item,
        Children: true
      }
    })
  }
}
getClassify()
// 懒加载分类
async function classifyLoad(node) {
  return new Promise(async (resolve) => {
    let nodes = []
    const res = await apiETAChart.classifyList({
      ParentId: node.data.ChartClassifyId,
      SysUserIds: userVal.value?.join(',')
    })
    if (res.Ret === 200) {
      const arr = res.Data.AllNodes || []
      nodes = arr.map(item => {
        return {
          ...item,
          Children: item.ChartInfoId ? [] : true,
          ChartClassifyId: item.ChartInfoId ? item.UniqueCode : item.ChartClassifyId,//如果是指标则将分类id设置为图表UniqueCode
        }
      })
    }
    resolve(nodes);
  });
}
//点击目录树
function handleClassifyActiveChange({ node }) {
  classifyActived.value = [node.data.ChartClassifyId]
  if (node.data.ChartInfoId) {//选择的是图表
    emits('change', node.data)
  } else {
    emits('filter')
  }
}


</script>

<template>
  <div class="bg-white classify-wrap">
    <div class="select-wrap">
      <t-cascader
        v-model="userVal"
        :options="userOpts"
        :keys="userProps"
        multiple
        :minCollapsedNum="1"
        clearable
        filterable
        :showAllLevels="false"
        placeholder="创建人"
      />
    </div>
    <t-select
      v-model="searchVal"
      placeholder="请输入图表名称"
      clearable
      filterable
      :keys="searchSelectKeys"
      :options="searchOpts"
      :loading="searchLoading"
      @search="handleSearchChart"
      @change="handleSelectChart"
      :popup-props="{ 'on-scroll-to-bottom': handleLoadMoreChart }"
    >
      <template #prefixIcon>
        <search-icon />
      </template>
    </t-select>
    <div class="classify-list-box">
      <t-tree
        :actived="classifyActived"
        :data="classifyList"
        activable
        transition
        lazy
        :load="classifyLoad"
        value-mode="all"
        :keys="classifyTreeKeys"
        check-strictly
        :onClick="handleClassifyActiveChange"
      >
        <template #icon="{ node }">
          <t-icon
            name="add-rectangle"
            v-if="node.getChildren() && !node.expanded"
          />
          <t-icon
            name="minus-rectangle"
            v-if="node.getChildren() && node.expanded"
          />
        </template>
      </t-tree>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.classify-wrap {
  width: 300px;
  flex-shrink: 0;
  padding: 20px;

  .select-wrap {
    display: flex;
    gap: 0 10px;
    margin-bottom: 10px;
  }
  .classify-list-box {
    padding-top: 10px;
    height: calc(100vh - 260px);
    overflow-y: auto;
  }
}
</style>