<template>
  <div class="w-full tree" :style="{ height: props.record?.itemHeight ? props.record?.itemHeight + 'px' : 'auto' }">
    <div class="tree-content">
      <a-spin tip="Loading..." :spinning="apiLoading" :delay="100">
        <div v-show="dictList && dictList.length > 0" class="left-tree">
          <!-- 树形组件 -->
          <a-directory-tree
            v-if="props.record?.itemMultipleChoiceFlag"
            v-model:expandedKeys="expandedKeys"
            v-model:checkedKeys="checkedKeys"
            :tree-data="dictList"
            :checkable="true"
            :show-icon="false"
            @check="treeCheck"
            :disabled="readonly || disabled"
            :multiple="true"
            :checkStrictly="props.record?.formItemSelect?.treeCheckStrictly"
            :fieldNames="{
              children: 'children',
              title: 'name',
              key: valueType == 1 ? 'id' : 'code',
              value: valueType == 1 ? 'id' : 'code'
            }"
          ></a-directory-tree>
          <a-directory-tree
            v-if="!props.record?.itemMultipleChoiceFlag"
            v-model:selectedKeys="dataValue"
            v-model:expandedKeys="expandedKeys"
            :show-icon="false"
            :tree-data="dictList"
            @select="selectNode"
            :disabled="readonly || disabled"
            :multiple="false"
            :fieldNames="{
              children: 'children',
              title: 'name',
              key: valueType == 1 ? 'id' : 'code',
              value: valueType == 1 ? 'id' : 'code'
            }"
          ></a-directory-tree>
        </div>
        <a-empty v-show="dictList && dictList.length == 0" class="empty" />
      </a-spin>
    </div>
  </div>
</template>

<script setup name="FormTree">
import { ref, onMounted, watch } from 'vue';
import Request from '@/utils/request/request-util';

const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  //当前行配置
  record: {
    type: Object,
    default: {}
  },
  // 当前行数据
  formData: {
    type: Object,
    default: {}
  },
  //是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  },
  // 是否是设计
  isDesgin: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:value', 'onChange']);

// 下拉取值 1: id;2: code
const valueType = ref(1);
// 数据来源
const dataFromType = ref(1);

// 选中的值
const dataValue = ref([]);

// 可选中列表
const dictList = ref([]);

// 是否有关联字段
const linkFieldCode = ref('');

// 加载动画
const apiLoading = ref(false);

// 展开列表
const expandedKeys = ref([]);

// 多选
const checkedKeys = ref([]);

onMounted(() => {
  if (props.record?.formItemSelect?.valueType == 2) {
    valueType.value = 2;
  }
  if (props.record?.formItemSelect?.linkFieldCode) {
    linkFieldCode.value = props.record.formItemSelect.linkFieldCode;
  }
  if (props.record?.formItemSelect?.dataFromType) {
    dataFromType.value = props.record.formItemSelect.dataFromType;
  }
  getDictList();
  setValueData();
});

// 获取选择列表
const getDictList = searchText => {
  if (props.isDesgin || dataFromType.value != 1 || !props.record.formItemSelect.backendUrl) return;
  apiLoading.value = true;
  let params = {
    searchText: searchText
  };
  if (linkFieldCode.value) {
    params[linkFieldCode.value] = props.formData[linkFieldCode.value];
    params.valueType = valueType.value;
  }
  Request.get(props.record.formItemSelect.backendUrl, params)
    .then(res => {
      props.record.dictList = res.data;
    })
    .finally(() => {
      apiLoading.value = false;
    });
};

// 单选选中事件
const selectNode = (selectedKeys, metadata) => {
  dataValueChange();
};

// 树形多选事件
const treeCheck = (checkedKeys, { checked, checkedNodes, node }) => {
  if (props.record?.formItemSelect?.treeCheckStrictly) {
    dataValue.value = checkedKeys.checked;
  } else {
    dataValue.value = checkedKeys;
  }

  dataValueChange();
};

// 更改值
const dataValueChange = () => {
  let data = JSON.stringify(dataValue.value);
  emits('update:value', data);
  emits('onChange', props.record);
};

const setValueData = () => {
  if (props.value) {
    dataValue.value = JSON.parse(props.value);
  } else {
    dataValue.value = [];
  }
  if (props.record?.itemMultipleChoiceFlag) {
    checkedKeys.value = dataValue.value;
  }
};

watch(
  () => props.formData[linkFieldCode.value],
  val => {
    getDictList();
  },
  { deep: true }
);

watch(
  () => props.value,
  val => {
    setValueData();
  },
  { deep: true }
);

watch(
  () => props.record.dictList,
  val => {
    if (val) {
      dictList.value = val;
    }
  },
  { deep: true, immediate: true }
);
</script>

<style scoped lang="less">
@import url('@/styles//commonTree.less');
.tree-content {
  height: 100%;
}
.empty {
  margin-top: 0;
}
.tree {
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>
