<script setup lang="ts">
import { useAttrs, reactive, onMounted, computed, watch } from 'vue'
import { usePropBind, LABEL_KEY } from './common'
import GdFormItem from './GdFormItem.vue';
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
import { getAllDeptTree, getAllDept, getDeptName } from '@/api/workflowManagement/index'

const { propValue, handleChange } = usePropBind()
const attrs = <any>useAttrs()

const props = withDefaults(defineProps<{
  label: string,
  type: string
  rules?: [],
  multiple?: boolean,
  multipleLimit?: number,
  onlyDept?: boolean,
  cascader?: boolean
}>(), { label: '' })

const state = reactive(<{ list: any[], selectedList: any[], selectedLabel: string }>{
  list: [],
  selectedList: [],
  selectedLabel: ''
})
const emit = defineEmits<{
  (e: 'selectionChange', val: any[]): void
}>();
defineExpose({ state })

const SELECTION_API: any = {
  organize: {
    action: getAllDeptTree,
    filterable: true,
    params: () => ({ i_enable: 'Y' })
  },
  company: {
    action: getAllDept,
    filterable: true,
    params: () => ({ i_key: '-', i_enable: 'Y' })
  }
}

const setLabel = (obj: any, item: any) => {
  obj[item.value] = item.label
  if (item.children) {
    item.children.forEach((row: any) => setLabel(obj, row))
  }
}

const getPage = async () => {
  const { action, params } = SELECTION_API[props.type]
  
  const res = await action({ ...params() })
  if (res.resultCode !== '0') {
    return
  }

  state.list = res.dataList
  if (props.onlyDept) {
    state.list.forEach(item => item.disabled = true)
  }
}
onMounted(async () => await getPage())

// 过滤筛选
const filterNodeMethod = (value: any, data: any) => data.label.toString().toLowerCase().includes(value.toString().toLowerCase());

const propValueTransfer = computed(() => {
  if (props.multiple) {
    return propValue.value ? propValue.value.split(',') : []
  }
  return propValue.value
})
const handlePropValueChange = (value: any) => {
  if (Array.isArray(value)) {
    value = value?.join(',')
  }
  handleChange(value)
}

// 维护当前选中项目
watch(propValue, async (val: any, prev: any) => {
  if (!val || val === '') {
    state.selectedList = []
  } else {
    state.selectedList = val.split(',')
  }
  getDeptName({ i_sch_field: val }).then((res: any) => {
    state.selectedLabel = res.dataList.map((item: any) => item.label).join(',')
  })
  emit('selectionChange', state.selectedList)
}, { immediate: true })

</script>

<template>
  <GdFormItem :label="props.label" :rules="props.rules">
    <span class="viewer-content" v-if="attrs.viewerMode">{{ state.selectedLabel }}</span>
    <el-cascader v-else-if="cascader" :model-value="propValueTransfer" @update:model-value="handlePropValueChange" :options="state.list"
                 :placeholder="`${$t('placeholder_prefix_select')?.replace(LABEL_KEY, props.label)}`" :default-expanded-keys="['-']"
                 :filter-node-method='filterNodeMethod' :render-after-expand='false'
                 :props="{multiple: multiple, checkStrictly: true, emitPath:false,}"
                 :show-all-levels="false" filterable clearable collapse-tags collapse-tags-tooltip class="gd-tree-select" v-bind="attrs">
      <template #default="{ node, data }">
        <el-tooltip :content="data.label" placement="top-start">
          <span>{{data.label}}</span>
        </el-tooltip>
      </template>
    </el-cascader>
    <el-tree-select v-else :model-value="propValueTransfer" @update:model-value="handlePropValueChange" :data="state.list"
      :placeholder="`${$t('placeholder_prefix_select')?.replace(LABEL_KEY, props.label)}`" :default-expanded-keys="['-']"
      :filter-node-method='filterNodeMethod' :render-after-expand='false'
      :check-strictly="true" filterable show-checkbox clearable collapse-tags collapse-tags-tooltip class="gd-tree-select"
      :multiple="multiple" :multipleLimit="multipleLimit" v-bind="attrs">
      <template #default="{ node, data }">
        <el-tooltip :content="data.label" placement="top-start">
          <span>{{data.label}}</span>
        </el-tooltip>
      </template>
    </el-tree-select>
  </GdFormItem>
</template>

<style lang="scss">
.gd-form .gd-tree-select.el-cascader {
  width: 100%;
}
 .el-cascader-menu {
  width: 150px;
}

.search-form .gd-tree-select.el-tree-select {
  width: 200px;
}
</style>
