<template>
  <div>
    <h-tree-select
      v-model:value="selectValue"
      style="width: 100%"
      :tree-data="treeData"
      allow-clear
      :showSearch="showSearch"
      multiple
      :disabled="disabled"
      :placeholder="t(placeholder)"
      :labelInValue="true"
      :fieldNames="{ value: 'key', label: 'tableDesc' }"
      :showCheckedStrategy="SHOW_PARENT"
      @change="changeHandler"
    />
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, watch, computed } from 'vue';
import type { ITreeSelectShowCheckedStrategy } from '@crami/ui-types';
import { useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';

const SHOW_PARENT: ITreeSelectShowCheckedStrategy = 'SHOW_ALL';

const selector = {
  value: {
    type: Array,
    default: () => {
      return [];
    },
  },
  params: {
    type: Array,
    default: () => {
      return {};
    },
  },
  showSearch: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  placeholder: {
    type: String,
    default: '',
  },
};
export default defineComponent({
  emits: ['change'],
  props: selector,
  setup(props, { emit }) {
    const { t } = useI18n();
    // 是否需要输入框查询
    const showSearch = computed(() => props.showSearch);
    // 是否disabled状态
    const disabled = computed(() => props.disabled);
    const placeholder = computed(() => props.placeholder);
    // treeselect双向绑定的数据
    const selectValue = ref<string[]>([]);

    //根据前端生成的key获取后端给的key(EID)
    const handleTreeData = (list: any) => {
      list.forEach((row: any) => {
        row.key = row.parentTableCode + ':' + row.tableCode + ':' + row.level;
        if (row.children?.length) {
          handleTreeData(row.children);
        }
      });
      return list;
    };

    const treeData = ref([]);
    // 获取传入的接口参数
    const params: any = computed(() => {
      return props.params || {};
    });

    watch(params, (newVal, oldVal) => {
      if (params.value && params.value?.value) {
        getData(params.value.value);
        if (newVal?.value && oldVal?.value && newVal?.value != oldVal?.value) {
          // 切换主模型数据，清楚关联模型数据和已选数据
          clearData();
        }
      } else {
        clearData();
      }
    });

    const selectData: any = computed(() => {
      return props.value || [];
    });

    // 监听select数据变化，更新数据label显示
    watch(selectData, () => {
      if (selectData.value?.length) {
        const selectKeys = [];
        getSelectKeys(selectData.value, selectKeys, null);
        selectValue.value = selectKeys;
      } else {
        selectValue.value = [];
      }
    });

    // 获取数据
    const getData = async value => {
      const data = await useHttp({
        method: 'post',
        url: `/api/commonquery/commonQuery/manage/getRefModelListT/${value}`,
        params: {
          lang: 'zhs',
        },
      });
      if (data.code == 200 && data?.data?.length) {
        treeData.value = handleTreeData(data?.data);
      }
    };

    onMounted(() => {
      if (params.value && params.value.value) {
        getData(params.value.value);
      }
    });

    // 获取宜选中数据的key
    const getSelectKeys = (data: any[], filters: any[], target?: any) => {
      if (data && data.length) {
        for (const item of data) {
          if (item.children && item.children?.length) {
            if (target) {
              item.label = target.label + '-' + item.tableDesc;
              for (const itemElement of item.children) {
                itemElement.label = item.label + '-' + itemElement.tableDesc;
              }
            } else {
              item.label = item.tableDesc;
            }
            getSelectKeys(item.children, filters, item);
          } else {
            if (target) {
              item.label = target.label + '-' + item.tableDesc;
            }
            filters.push({
              ...item,
              label: item.label ? item.label : item.tableDesc,
              value: item?.parentTableCode + ':' + item?.tableCode + ':' + item.level,
            });
          }
        }
      }
    };

    // 从子集向上查找,处理保存数据
    function funRecursionSave(list, id) {
      for (let i in list) {
        if (list[i].key == id) {
          return {
            ...list[i],
            children: [],
          };
        }
        if (list[i].children && list[i].children.length) {
          let node = funRecursionSave(list[i].children, id);
          if (node !== undefined) {
            return {
              ...list[i],
              children: [node],
            };
          }
        }
      }
    }

    // 监听数据切换，更换数据展示格式
    const changeHandler = value => {
      const submitData = [];
      value.map(item => {
        const selectItemData = funRecursionSave(treeData.value, item.value);
        submitData.push(selectItemData);
      });
      // 通过emit change事件更新form表单，通过formMethod.getData()可以获取数据
      emit('change', submitData);
    };

    // 接口请求失败，或者为空时情况选项数据
    const clearData = () => {
      treeData.value = [];
      selectValue.value = [];
      emit('change', []);
    };

    return {
      selectValue,
      treeData,
      SHOW_PARENT,
      changeHandler,
      showSearch,
      disabled,
      placeholder,
      t,
    };
  },
});
</script>
