<script setup name="orgTree">
import { getOrgTree } from '@/http/apis/systemManage/unitManage'
import { getOrgLine } from '@/http/apis/commonApi'
import { nextTick, ref, watch } from 'vue'

const props = defineProps({
    visible: {
      type: Boolean,
      default: false
    },
    showCheckbox: {
      type: Boolean,
      default: false
    }, // 是否多选
    defaultData: Array, // 用于回显数据,
    // 获取数据的参数
    params: {
      type: Object,
      default: () => {}
    },
    // 是否选择到人
    isPerson: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '单位'
    },
    // 展开节点
    defaultExpandedkeys: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 数据结构
    defaultProps: {
      type: Object,
      default: () => {
        return {
          children: 'children',
          label: 'title',
          value: 'key',
          isLeaf: 'isLeaf'
        }
      }
    },
    type: {
      type: String,
      default: 'UNIT' // LINE：条线   UNIT:单位
    }

  }),
  emits = defineEmits(['close', 'getSelectUnit']), // close 关闭 getSelectUnit:获取数据
  handleClose = () => {
    emits('close')
    inputText.value = ''
  },
  submit = () => {
    emits('getSelectUnit', selectData.value)
    handleClose()
  }
const filterText = ref('')
const inputText = ref('')
const treeRef = ref()
const loadNode = async (node, resolve) => {
  if (node.level) {
    let res
    if (props.type === 'LINE') {
      res = await getOrgLine({
        ...props.params,
        parentCode: node.data.businessStripCode
      })
      if (res.data) {
        let nodeData
        if (props.isPerson && props.showCheckbox) {
          nodeData = res.data.map(i => ({ ...i, disabled: i.type === 'ORGANIZATION', isLeaf: i.type === 'MEMBER' }))
        } else {
          nodeData = res.data.map(i => ({ ...i, isLeaf: i.type === 'MEMBER' }))
        }
        resolve(nodeData)
      } else {
        resolve([])
      }
    } else {
      let nodeData
      if (node?.data?.children?.length) {
        if (props.isPerson && props.showCheckbox) {
          nodeData = node?.data?.children.map(i => ({ ...i, disabled: i.type === 'ORGANIZATION', isLeaf: i.type === 'MEMBER' }))
        } else {
          nodeData = node?.data?.children.map(i => ({ ...i, isLeaf: i.type === 'MEMBER' }))
        }
        resolve(nodeData)
      } else {
        res = await getOrgTree({
          ...props.params,
          organizationCode: node.data.key
        })

        if (res.data?.[0]?.children) {
          if (props.isPerson && props.showCheckbox) {
            nodeData = res.data?.[0]?.children.map(i => ({ ...i, disabled: i.type === 'ORGANIZATION', isLeaf: i.type === 'MEMBER' }))
          } else {
            nodeData = res.data?.[0]?.children.map(i => ({ ...i, isLeaf: i.type === 'MEMBER' }))
          }
          resolve(nodeData)
        } else {
          resolve([])
        }
      }
    }
  }
  nextTick(() => {
    if (props.showCheckbox) {
      if (selectData.value && selectData.value.length) {
        treeRef.value && treeRef.value.setCheckedNodes(selectData.value)
      } else {
        treeRef.value && treeRef.value.setCheckedKeys([])
      }
    } else {
      if (selectData.value && selectData.value.length) {
        treeRef.value && treeRef.value.setCurrentKey(selectData.value[0].key)
      } else {
        treeRef.value && treeRef.value.setCurrentKey(null)
      }
    }
  })
}
watch(
  () => props.visible,
  val => {
    if (val) {
      nextTick(async () => {
        await getTreeData()
        if (props.defaultData && props.defaultData.length) {
          selectData.value = [...props.defaultData]
        } else {
          filterText.value = undefined
          selectData.value = []
        }
      })
    }
  }
)

// 搜索
// watch(filterText, async val => {
//   await getTreeData()
//   nextTick(() => {
//     treeRef.value && treeRef.value.filter(val)
//   })
// })
const search = async () => {
  await getTreeData(filterText.value)
  nextTick(() => {
    treeRef.value && treeRef.value.filter(filterText.value)
  })
}
const expandAll = ref(false),
  filterNode = (value, data) => {
    if (!value) return true
    return true
  }
// 获取选择的单位
const selectData = ref([]),

  checkChange = (data, { checkedKeys, checkedNodes }) => {
    if (props.showCheckbox) {
      if (checkedKeys.includes(data[props.defaultProps.value])) {
        selectData.value.push(data)
      } else {
        selectData.value = selectData.value.filter(i => i[props.defaultProps.value] !== data[props.defaultProps.value])
      }
    } else {
      selectData.value = [data]
    }
  },
  delData = (index, key, type) => {
    selectData.value.splice(index, 1)
    nextTick(() => {
      if (props.showCheckbox) {
        treeRef.value && treeRef.value.setChecked(key, false)
      } else {
        treeRef.value && treeRef.value.setCurrentKey(null)
      }
    })
  },
  treeData = ref(),
  getTreeData = async (filterText) => {
    treeData.value = []
    let res
    if (props.type === 'LINE') {
      res = await getOrgLine({})
    } else {
      res = await getOrgTree({ ...props.params, organizationName: !props.isPerson && filterText || undefined, employeeName: props.isPerson && filterText || undefined, parentCode: undefined })
    }
    let nodeData
    if (props.isPerson && props.showCheckbox) {
      nodeData = res.data.map(i => ({ ...i, disabled: true }))
    } else {
      nodeData = res.data.map(i => ({ ...i }))
    }
    treeData.value = nodeData
  }
</script>
<template>
  <el-dialog
    :model-value="props.visible"
    :title="`选择${title}`"
    :width="800"
    destroy-on-close
    :before-close="handleClose"
  >
    <div class="unitBox">
      <div class="left">
        <div class="title">列表</div>
        <div class="content">
          <el-input
            v-model="filterText"
            class="mb-16"
            placeholder="按名称搜索"
          >
            <template #append>
              <el-button icon="Search" @click="search" />
            </template>
          </el-input>
          <el-scrollbar>
            <el-tree
              ref="treeRef"
              :data="treeData"
              class="filter-tree"
              :node-key="defaultProps.value"
              :default-checked-keys="
                (props.defaultData &&
                  props.defaultData.length &&
                  props.defaultData
                    .map(item => item[defaultProps.value])) ||
                  []
              "
              :current-node-key="
                (props.defaultData &&
                  props.defaultData.length &&
                  props.defaultData[0][defaultProps.value]) ||
                  undefined
              "
              :load="loadNode"
              lazy
              :props="defaultProps"
              :show-checkbox="showCheckbox"
              :check-on-click-node="!showCheckbox"
              check-strictly
              :highlight-current="!showCheckbox"
              :filter-node-method="filterNode"
              :default-expand-all="expandAll"
              :default-expanded-keys="defaultExpandedkeys"
              @check="checkChange"
            />
          </el-scrollbar>
        </div>
      </div>
      <div class="right">
        <div class="title">已选{{ title }}</div>
        <div class="content">
          <el-tag
            v-for="(item, index) in selectData"
            :key="item.key"
            closable
            @close="delData(index, item.key, item.type)"
          >
            {{ type === 'LINE' ? item.businessStripName:item.title }}
          </el-tag>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="less">
.unitBox {
  display: flex;
  height: 500px;
  overflow: hidden;
  .el-tag {
    margin: 0 4px 8px;
  }
  .title {
    padding: 12px;
    border-bottom: 1px solid #ccc;
    margin-bottom: 12px;
  }
  .left,
  .right {
    flex: 1;
    border-bottom: 1px solid #ccc;
    display: flex;
    flex-flow: column;
    overflow: hidden;
    .content {
      flex: 1;
      padding: 0 12px;
      overflow: scroll;
    }
  }
  .left {
    border-top: 1px solid #ccc;
    border-left: 1px solid #ccc;
    border-right: 1px solid #ccc;
    .inputText {
      padding: 12px;
    }
  }
  .right {
    border-top: 1px solid #ccc;
    border-right: 1px solid #ccc;
  }
}
</style>
