<template>
  <div :class="$style.unitSelect">
    <a-select
      ref="select"
      v-model="onKeys"
      mode="multiple"
      :max-tag-count="2"
      @focus="focus"
      @change="selectChange"
    >
      <a-select-option v-for="(item, i) in mockData" :key="i" :value="item.key">{{
        item.title
      }}</a-select-option>
    </a-select>
    <a-modal v-model="showTree" title="请选择" @ok="ok" @cancel="cancel">
      <!-- 单选 -->
      <div :class="$style.tree">
        <a-input-search
          style="margin-bottom: 8px"
          placeholder="搜索"
          allow-clear
          @change="onChange"
        />
        <a-radio-group v-if="single" v-model="onGroupKey">
          <a-tree
            v-model="checkedKeys"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            :load-data="onLoadData"
            :default-expanded-keys="['100000']"
            :default-expand-parent="true"
            multiple
            show-icon
            @expand="onExpand"
            @select="onSelect"
            @check="onCheck"
          >
            <template slot="custom" slot-scope="{ key }">
              <a-radio :value="key"></a-radio>
            </template>
          </a-tree>
        </a-radio-group>
        <!-- 多选 -->
        <a-checkbox-group v-else v-model="onCheckBoxGroupKey">
          <a-tree
            v-model="checkedKeys"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            :load-data="onLoadData"
            :default-expanded-keys="['100000']"
            :default-expand-parent="true"
            multiple
            show-icon
            @expand="onExpand"
            @select="onSelect"
            @check="onCheck"
          >
            <template slot="custom" slot-scope="{ key }">
              <a-checkbox :value="key"></a-checkbox>
            </template>
          </a-tree>
        </a-checkbox-group>
      </div>
    </a-modal>
  </div>
  <!-- 分级数据 -->
</template>

<script>
import components from './_import-components/audit-unit-select-import'
import AuditPortraitService from './audit-portrait-service'
export default {
  name: 'AuditUnitSelect',
  metaInfo: {
    title: 'AuditUnitSelect',
  },
  components,
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    single: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      // 弹窗
      showTree: false,
      onKeys: [],

      mockData: [],
      checkedKeys: [],
      expandedKeys: ['100000'],
      autoExpandParent: true,
      selectedKeys: [],
      treeData: [],
      searchValue: '',
      onGroupKey: '',
      onCheckBoxGroupKey: [],
    }
  },
  created() {
    this.initTreeData()
  },
  methods: {
    selectChange(e) {
      this.onKeys = e
      const isArr = this.mockData.filter((val) => this.onKeys.includes(val.key))
      const arr = isArr.map((val) => ({
        orgCode: val.key + '',
        name: val.title,
      }))
      this.$emit('change', arr)
    },
    ok() {
      this.showTree = false

      // 寻找对应的name
      this.onKeys = this.single ? [this.onGroupKey] : this.onCheckBoxGroupKey

      // 遍历数组看是否有 100000
      // 如果没有则插入
      const isType = this.mockData.find((val) => val.key === '100000')
      if (!isType) {
        this.mockData.push({
          key: '100000',
          title: '国家电力投资集团有限公司',
          lev: 1,
          isLeaf: false,
          parent: 'root',
          scopedSlots: { icon: 'custom' },
        })
      }
      const isArr = this.mockData.filter((val) => this.onKeys.includes(val.key))

      const arr = isArr.map((val) => ({
        orgCode: val.key + '',
        name: val.title,
      }))

      this.$emit('change', arr)
    },
    focus() {
      this.showTree = true
      this.onCheckBoxGroupKey = this.onKeys
      this.onGroupKey = this.onKeys[0] || ''
      // 展开第一个
      this.expandedKeys = ['100000']
      // 去除焦点
      this.$refs.select.blur()
    },
    cancel() {
      this.showTree = false
      // 清空组件内数据
      this.checkedKeys = []
      this.expandedKeys = []
      this.autoExpandParent = true
      this.selectedKeys = []
      this.onGroupKey = ''
    },
    initTreeData() {
      // 100000
      const params = {
        mdgOrgCode: '100000',
        lev: 1,
      }
      // 国家电力投资集团有限公司
      AuditPortraitService.getGroupsByCode(params).then((res) => {
        this.treeData = [
          {
            key: '100000',
            title: '国家电力投资集团有限公司',
            lev: 1,
            scopedSlots: { icon: 'custom' },

            children: res.data.map((res) => {
              return {
                key: res.code,
                title: res.name,
                parent: '100000',
                isLeaf: false,
                lev: 2,
                scopedSlots: { icon: 'custom' },
              }
            }),
          },
        ]
        this.mockData = []
        this.mockData.push({
          key: '100000',
          title: '国家电力投资集团有限公司',
          lev: 1,
          isLeaf: false,
          parent: 'root',
          scopedSlots: { icon: 'custom' },
        })
        this.mockData = res.data.map((res) => {
          return {
            key: res.code + '',
            title: res.name,
            parent: '100000',
            isLeaf: false,
            lev: 2,
            scopedSlots: { icon: 'custom' },
          }
        })
        // 判断value是否有值如果有值且mock中没有该值则添加
        this.value.forEach((val) => {
          if (!this.mockData.find((item) => item.key === val.orgCode)) {
            this.mockData.push({
              key: val.orgCode + '',
              title: val.name,
              parent: '',
              isLeaf: false,
              lev: 2,
              scopedSlots: { icon: 'custom' },
            })
          }
        })
        this.$nextTick(() => {
          if (this.value.length > 0) {
            this.onKeys = [this.value[0].orgCode]
            const isArr = this.mockData.filter((val) => this.onKeys.includes(val.key))
            const arr = isArr.map((val) => ({
              orgCode: val.key + '',
              name: val.title,
            }))
            this.$emit('change', arr)
          }
        })
      })
    },
    onLoadData(treeNode) {
      return new Promise((resolve) => {
        if (treeNode.dataRef.children) {
          return resolve()
        }
        const params = {
          mdgOrgCode: treeNode.dataRef.key,
          lev: treeNode.dataRef.lev,
        }
        AuditPortraitService.getGroupsByCode(params).then((res) => {
          treeNode.dataRef.children = res.data.map((res) => {
            return {
              key: res.code + '',
              title: res.name,
              isLeaf: true,
              lev: treeNode.dataRef.lev,
              parent: treeNode.dataRef.key,
              scopedSlots: { icon: 'custom' },
            }
          })
          // 遍历遍历数组如果res.data中有value的值则删除mockData中的该值
          this.value.forEach((val) => {
            if (res.data.find((item) => item.code === val.orgCode)) {
              this.mockData = this.mockData.filter((item) => item.key !== val.orgCode)
            }
          })
          this.mockData = [
            ...this.mockData,
            ...res.data.map((res) => {
              return {
                key: res.code + '',
                title: res.name,
                parent: treeNode.dataRef.key,
                isLeaf: true,
                lev: treeNode.dataRef.lev,
                scopedSlots: { icon: 'custom' },
              }
            }),
          ]
          resolve()
        })
      })
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onSelect(selectedKeys) {
      console.log('🚀 ~ onCheck ~ checkedKeys:', selectedKeys)

      if (this.single) {
        this.onGroupKey = selectedKeys[0]
      } else {
        if (this.onCheckBoxGroupKey.includes(selectedKeys[0])) {
          this.onCheckBoxGroupKey = this.onCheckBoxGroupKey.filter(
            (item) => item !== selectedKeys[0]
          )
        } else {
          this.onCheckBoxGroupKey = [...this.onCheckBoxGroupKey, selectedKeys[0]]
        }
      }
      this.selectedKeys = []

      // this.onGroupKey = selectedKeys[0]

      // 寻找父节点 展开
      // this.expandedKeys = [
      //   '100000',
      //   ...this.mockData.filter((item) => item.key === selectedKeys[0]).map((item) => item.parent),
      // ]
      // 只能选择一个节点
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys
      if (checkedKeys.length > 1 && this.single) {
        this.checkedKeys = [this.checkedKeys[checkedKeys.length - 1]]
      } else {
        this.onCheckBoxGroupKey = checkedKeys
        this.checkedKeys = checkedKeys
      }
    },
    onChange(e) {
      const { value } = e.target

      const selectedKeys = this.mockData
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return item
          }
          return null
        })
        .filter((item) => item)
      console.log('🚀 ~ onChange ~ selectedKeys:', selectedKeys)
      const dataTree = [
        {
          key: '100000',
          title: '国家电力投资集团有限公司',
          lev: 1,
          scopedSlots: { icon: 'custom' },
          children: [],
        },
      ]
      selectedKeys.map((val) => {
        if (val.lev === 2) {
          dataTree[0].children.push(val)
        }
      })
      dataTree[0].children.forEach((val2) => {
        selectedKeys.map((val3) => {
          if (val2.lev === 3 && val2.key === val3.parent) {
            val2.children.push(val3)
          }
        })
      })
      console.log('🚀 ~ onChange ~  dataTree:', dataTree)
      this.treeData = dataTree
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.unit-select {
  min-width: 200px;
}
.tree {
  height: 500px;
  // 滚动
  overflow-y: auto;
}
</style>
