<template>
  <v-select :options='resoptions' placeholder='请选择'
            :value.sync="selectres"
            :multiple="isMul"
            search="true"
            :disabled="mustselect"
            :close-on-select="!isMul"
            @change="resChange"
  >
  </v-select>
</template>

<script>
import { HttpResetClass } from 'vue-client'

export default {
  title: '资源选择',
  props: {
    restype: '', // 资源类型
    resObj: {}, // 资源数据
    isMul: {
      type: Boolean,
      default: true
    },
    initresid: {
      type: Array,
      default() { return [] },
    },
    parentresid: {
      type: Array,
      default() { return [] },
    },
    mustselect: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      // 资源数据
      resObj: {},
      // 资源数据列表
      resoptions: [],
      // 选中资源数据
      selectres: [],
      // 记录已经添加过的父节点 ID
      addedParentIds: new Set(),
    }
  },
  ready() {
    // 获取资源列表
    this.getResList()
  },
  methods: {
    // 遍历树形结构并转换为列表
    findById(val) {
      if (val) {
        if (this.checkidres(val)) {
          this.treetoList(val, '')
        } else if (val.children.length > 0) {
          for (let value of val.children) {
            this.findById(value)
          }
        }
      }
    },
    // 树形结构转换为列表
    treetoList(val, parentname) {
      for (let value of val.children) {
        this.ergodicList(value, parentname)
      }
    },
    // 遍历节点列表
    ergodicList(val, parentname) {
      // Add parent node to options only if it hasn't been added before
      if (parentname && !this.addedParentIds.has(val.parentid) && parentname != "组织机构") {
        parentname = parentname.replace("组织机构", "")
        this.resoptions.push({label: parentname, value: val.parentid})
        this.addedParentIds.add(val.parentid) // Record that this parent has been added
      }

      // Process current node
      if (val.children.length > 0) {
        parentname = parentname + val.name
        this.treetoList(val, parentname)
      } else {
        // Append organization-specific information
        if (this.restype === 'organization') {
          parentname = parentname.replace("组织机构", "")
          this.resoptions.push({label: val.name + ' - ' + parentname, value: val.id})
        } else {
          this.resoptions.push({label: val.name, value: val.id})
        }
      }
    },
    // 检查 ID 是否存在
    checkidres(val) {
      let flag = false
      if (this.parentresid.length === 0 && this.restype === 'organization') {
        flag = true
      }
      this.parentresid.forEach((item) => {
        if (item === val.id) {
          flag = true
        }
      })
      return flag;
    },
    // 资源改变
    resChange(val) {
      let orgnames = []
      Object.keys(this.resoptions).forEach((key) => {
        if (this.selectres.includes(this.resoptions[key].value))
          orgnames.push(this.resoptions[key].label)
      })
      console.log('资源改变。。', val, orgnames)
      this.$dispatch('res-select', this.selectres, orgnames)
    },
    // 获取资源数据
    async getResList() {
      let http = new HttpResetClass()
      let req = await http.load('POST', '/rs/search', {
        data: {
          source: `tool.getFullTree(this.getRights().where(row.getType()==$${this.restype}$))`,
          userid: this.$login.f.id
        }
      }, {resolveMsg: null, rejectMsg: '获取组织结构数据出错'})
      this.resObj = req.data[0]
      this.dealdata()
    },
    dealdata() {
      this.resoptions = []
      this.addedParentIds.clear() // Reset addedParentIds for each data deal
      this.findById(this.resObj);
      // 赋值资源数据
      let arryselect = []
      this.resoptions.forEach((item) => {
        if (this.initresid.length > 0) {
          this.initresid.forEach((init) => {
            if (item.value == init) {
              arryselect.push(item.value)
            }
          })
        }
      })
      // 赋值资源选中初始值
      this.selectres = arryselect
    }
  },
  watch: {
    // 监听初始化资源 id
    'initresid.length'() {
      this.dealdata()
    },
    // 监听父资源 id
    'parentresid'() {
      this.dealdata()
    },
  },
}
</script>
