<!--
 * @Author: 曹捷
 * @Date: 2020-04-14 16:28:00
 * @LastEditors: 曹捷
 * @LastEditTime: 2022-04-12 11:03:58
 * @Description: 改造cascader modal  是数组，实际使用是最后一级
 -->
<template>
  <a-cascader :disabled="disabled" :options="options" :placeholder="placeholder" :fieldNames="pData" :show-all-levels="false" :load-data="cptLoadData" :changeOnSelect="changeOnSelect" clearable
    v-if="loading" v-model:value="cascValue" :popupVisible="popupVisible" :defaultValue="cascValue">
  </a-cascader>
</template>

<script>
import { watch, reactive, inject, toRefs, onMounted } from "vue";
import util from "./../../utils/utils.js";
// import { Cascader } from 'ant-design-vue'

export default {
  components: {
    // ACascader: Cascader
  },
  emits: ['update:fullList', 'update:value', 'update:fullNameList', 'update:currValue'],
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    currValue: {
      type: [Object, String],
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // 数据tree
    options: {
      type: Array,
      default: [],
    },
    // 子集字段名
    children: {
      type: String,
      default: "children",
    },
    // value 值字段名
    valueName: {
      type: String,
      default: "value",
    },
    // 展示字段名
    label: {
      type: String,
      default: "label",
    },
    // 上级id 字段名
    parentId: {
      type: String,
      default: "parentId",
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    changeOnSelect: {
      type: Boolean,
      default: false,
    },
    /**
     * 自定义加载数据  支持异步加载数据
     * 注意 异步加载的数据  属性字段  isLeaf  必须为false
     */
    sysnLoadData: {
      type: Function,
    },
    popupVisible: {
      type: Boolean,
      default: undefined
    },
  },
  setup (props, context) {
    let _data = reactive({
      cascValue: [],
      casList: [],
      loading: false,
      pData: { expandTrigger: "click", checkStrictly: true },
    });
    let _methods = {
      cptLoadData (selectedOptions) {
        if (props.sysnLoadData) {
          props.sysnLoadData(selectedOptions);
        }
      },
      cascChange (param) {
        let value = param.slice(-1)[0];
        context.emit("update:value", value);
        context.emit("update:fullList", _data.cascValue);
        _methods.initCasList()
        let item = _data.casList.find(el => el[props.valueName] == value)
        if (item) {
          context.emit('update:currValue', item)
        }
        if (_data.casList && _data.casList.length > 0) {
          let nameList = _data.cascValue.reduce((list, element) =>
            list.concat([_data.casList.find(el => el[props.valueName] == element)[props.label]]), [])
          context.emit("update:fullNameList", nameList);
        }
      },
      // 将tree数据转为1维数组
      initCasList () {
        let arr = util.util.cloneObj(props.options);

        let list = [].concat(arr);
        let childrenName = props.children;
        function getCasList (arr) {
          arr.forEach((element) => {
            if (element[childrenName] && element[childrenName].length > 0) {
              list = list.concat(element[childrenName]);
              getCasList(element[childrenName]);
            }
          });
        }
        getCasList(arr);
        list.forEach((element) => {
          element[props.children] = [];
        });
        _data.casList = list;
      },
      // 在1维数组里面 遍历找上级id
      getParentIdList (value) {
        if (!value) {
          return [];
        }
        let list = [value];
        function getParentId (value) {
          let item = _data.casList.find((el) => el[props.valueName] == value);
          if (item) {
            let parent = _data.casList.find(
              (el) => el[props.valueName] == item[props.parentId]
            );
            if (parent) {
              list.unshift(item[props.parentId]);
              getParentId(item[props.parentId]);
            }
          }
        }
        getParentId(value);
        return list;
      },
    };
    // watch ---------------------------------------------
    watch(() => props.value, (newValue, oldValue) => {
      if (!oldValue && newValue) {
        _data.cascValue = _methods.getParentIdList(newValue);
      } else if (!newValue) {
        _data.cascValue = [];
      }
    }
    );
    watch(() => _data.cascValue, (value) => {
      _methods.cascChange(value);
    }
    );
    watch(() => props.options, () => {
      _methods.initCasList();
      _data.cascValue = _methods.getParentIdList(props.value);
    }
    );
    onMounted(() => {
      _data.pData.value = props.valueName;
      _data.pData.label = props.label;
      _data.pData.children = props.children;
      _data.loading = true;
      _methods.initCasList();
      _data.cascValue = _methods.getParentIdList(props.value);
    });
    return {
      ...toRefs(_data),
      ..._methods,
    };
  },
};
</script>

<style>
</style>