<script setup name="indexTree">
import { nextTick, ref, watch } from 'vue'
import { tagFuzzyMatch } from '@/http/apis/performanceEvaluation/indicatorTemplate'

const props = defineProps({
    visible: {
      type: Boolean,
      default: false
    },
    showCheckbox: {
      type: Boolean,
      default: false
    }, // 是否多选
    defaultData: Array, // 用于回显数据,
    // 获取数据的参数
    params: {
      type: Object,
      default: () => {}
    },
    title: {
      type: String,
      default: '一级指标'
    },
    // 展开节点
    defaultExpandedkeys: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 数据结构
    defaultProps: {
      type: Object,
      default: () => {
        return {
          children: 'projectIndexes',
          label: 'name',
          value: 'indexId',
          isLeaf: 'isLeaf'
        }
      }
    }
  }),
  emits = defineEmits(['close', 'getSelectData']), // close 关闭 getSelectIndex:获取数据
  handleClose = () => {
    emits('close')
    inputText.value = ''
  },
  submit = () => {
    emits('getSelectData', selectData.value)
    handleClose()
  }
const filterText = ref('')
const inputText = ref('')
const treeRef = ref()
watch(
  () => props.visible,
  val => {
    if (val) {
      nextTick(async () => {
        if (props.defaultData && props.defaultData.length) {
          selectData.value = [...props.defaultData]
        } else {
          filterText.value = undefined
          selectData.value = []
        }
        await getTreeData()
      })
    }
  }
)

// 搜索
// 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) => {
    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 = []
    const res = await tagFuzzyMatch({ ...props.params, name: filterText || undefined })
    const nodeData = changeData(res.data.filter(i => i.projectIndexes?.length))
    treeData.value = nodeData
    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].indexId)
        } else {
          treeRef.value && treeRef.value.setCurrentKey(null)
        }
      }
    })
  },
  changeData = (data) => {
    const arr = []
    data.forEach(i => {
      arr.push({
        ...i,
        name: i.name || i.indexName,
        disabled: !i.indexLevel,
        indexId: i.id,
        projectIndexes: i.projectIndexes?.length && changeData(i.projectIndexes) || undefined
      })
    })
    return arr
  }
</script>
<template>
  <el-dialog
    :model-value="props.visible"
    :title="`选择${title}`"
    width="80%"
    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
              "
              :expand-on-click-node="true"
              :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.id, item.type)"
          >
            {{ item.name }}
          </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>
