<template>
  <el-cascader
    clearable
    ref="cascader"
    v-model="value"
    class="org-cascader"
    :options="options"
    :show-all-levels="showAllLevels"
    @change="handleCascaderChange"
    :props="{
      expandTrigger: 'hover',
      checkStrictly: true,
      value: 'id',
      label: 'name',
      children: 'chirldren',
    }"
  ></el-cascader>
</template>

<script>
const portal = window.context.portal
export default {
  props: {
    placeholder: {
      type: String,
      default: '请选择',
    },
    fullPath: {
      type: Array,
      default: () => ['1766017468444450816'],
    },
    allIds: {
      type: Boolean,
      default: false, //是否收集所有子节点id、默认false采集最后一级无子节点Id
    },
    searchCompany: {
      type: Boolean,
      default: true, //查询时是否需要上次公司
    },
    showAllLevels: {
      type: Boolean,
      default: true, //是否显示完整路径
    },
    getOrgId: {
      type: Boolean,
      default: false, //是否显示完整路径
    },
  },
  data() {
    return {
      //  默认根节点
      defaultRoot: {
        isDelete: '0',
        id: '1766017468444450816',
        name: '全国',
        parentId: '1765985726257963008',
        code: '100101',
        grade: '2',
        orgKind: 'ogn',
        demId: '1726849603896352768',
        orderNo: 145,
        isMaster: 0,
        path: '1726849603896352768.1765985726257963008.1766017468444450816.',
        pathName: '/中国铁建昆仑投资集团/高速公路运营管理公司',
        limitNum: 0,
        exceedLimitNum: 0,
        disabled: false,
        chirldren: [],
      },
      options: [],
      value: this.fullPath,
      lastPath: '',
      orgIds: [],
      tempOrg: '',
    }
  },
  watch: {
    fullPath(newVal) {
      this.value = newVal
    },
  },
  created() {
    this.initRoadData()
  },
  methods: {
    initRoadData() {
      this.loadData()
        .then((res) => {
          let data = res || []
          this.deepSetChildren(data) // 设置路段的children为null
          this.defaultRoot.chirldren = data
          this.options = [this.defaultRoot]
        })
        .catch((err) => {
          this.$message.warning(err)
        })
    },
    loadData() {
      return new Promise((resolve, reject) => {
        this.$http
          .get(portal + '/bizBaseRoad/v1/roadTree')
          .then((res) => resolve(res?.data || {}))
          .catch((err) => reject(err))
      })
    },
    // 选择变化触发父级数据更新
    handleCascaderChange(val) {
      if (val && val.length) {
        this.value = val
        this.lastPath = val[val.length - 1]
        let selectedList = this.$refs.cascader.getCheckedNodes()
        this.orgIds = this.collectIds([selectedList[0].data])
        // 小于两级查询要追加公司id
        if (val.length <= 2 && this.searchCompany) {
          this.orgIds.push('1766017468444450816')
        }
        if (val.length === 5 && this.getOrgId) {
          this.lastPath = this.getRoadOrgId(this.lastPath, this.options)
        }
      } else {
        // 如果清空选择就默认为根节点
        this.value = ['1766017468444450816']
        this.lastPath = '1766017468444450816'
        this.orgIds = this.collectIds(this.options)
        if (this.searchCompany) {
          this.orgIds.push('1766017468444450816')
        }
      }

      this.$emit('fullPath', this.value) // 选中节点全路径

      this.$emit('lastPath', this.lastPath, this.orgIds) // 选中节点路径
      this.$emit('orgIds', this.orgIds) // 选中节点下子节点id集合（路段id）
    },
    // 路段根据路段id获取路段orgid
    getRoadOrgId(id, data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === id) {
          this.tempOrg = data[i].orgId
          break
        } else if (data[i].chirldren && data[i].chirldren.length) {
          this.tempOrg = this.getRoadOrgId(id, data[i].chirldren)
        }
      }
      return this.tempOrg
    },
    // 递归收集最后一级无子节点的id（路段id） | allIds true 收集所有节点id
    collectIds(data) {
      let ids = []
      data.forEach((item) => {
        if (item.chirldren) {
          if (this.allIds) ids.push(item.id)
          const cIds = this.collectIds(item.chirldren)
          ids.push(...cIds)
        } else {
          ids.push(item.id)
        }
      })
      return ids
    },
    // 格式化数据：节点chirldren字段无下级则为空
    deepSetChildren(data) {
      data.forEach((i) => {
        let child = i.chirldren
        if (child && child.length !== 0) {
          return this.deepSetChildren(child)
        } else {
          i.chirldren = null
        }
      })
      return data
    },
  },
}
</script>

<style lang="scss" scoped>
.org-cascader {
  width: 100%;
  margin-right: 10px;
}
</style>
