<template>
  <div>
    <div @click="show"><slot></slot></div>
    <ModalPanel
      :visible="visible"
      :width="400"
      :title="t('表单字段配置')"
      @submit="submit"
      @close="close"
    >
      <div class="title">
        <NodeHead :node-name="t('表单字段列表')" />
      </div>
      <div class="list-box">
        <a-tree
          checkable
          :tree-data="nodes.treeData"
          autoExpandParent
          defaultExpandAll
          v-model:checkedKeys="checkedKeys"
        />
      </div>
    </ModalPanel>
  </div>
</template>

<script setup lang="ts">
  import { inject, reactive, ref, onMounted } from 'vue';
  import { MemberType } from '/@/enums/workflowEnum';
  import { MemberConfig } from '/@/model/workflow/memberSetting';
  import { ModalPanel } from '/@/components/ModalPanel/index';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { isValidJSON } from '/@/utils/event/design';
  import { useI18n } from '/@/hooks/web/useI18n';
  const separator = '-';
  const { t } = useI18n();
  const emits = defineEmits(['change']);
  const widgetForm = inject('widgetForm') as any;
  const props = withDefaults(
    defineProps<{
      memberList: Array<MemberConfig>;
    }>(),
    {
      memberList: () => {
        return [];
      },
    },
  );

  const visible = ref(false);
  const memberType = MemberType.FORM_FIELD;
  let nodes = reactive({
    treeData: [] as any,
  });
  const checkedKeys = ref<string[]>([]);
  let selectedList: { list: Array<MemberConfig> } = reactive({ list: [] });
  onMounted(() => {
    if (!!widgetForm?.value) {
      initTreeData();
    }
  });
  function show() {
    checkedKeys.value = [];
    if (props.memberList.length > 0) {
      selectedList.list = props.memberList.filter((ele: MemberConfig) => {
        if (ele.memberType === memberType) return ele;
      });
    }
    if (selectedList.list.length > 0) {
      checkedKeys.value = selectedList.list.map((ele) => {
        return ele.id;
      });
    }
    visible.value = true;
  }
  function submit() {
    let list: Array<MemberConfig> = [];
    if (props.memberList.length > 0) {
      list = props.memberList.filter((ele: MemberConfig) => {
        if (ele.memberType != memberType) return ele;
      });
    }
    for (const item of checkedKeys.value) {
      let arr = item.split(separator);
      let index = arr[arr.length - 1];
      let { bindField } = JSON.parse(nodes.treeData[index].value);
      list.push({
        memberType: memberType,
        id: '0-' + index,
        name: nodes.treeData[index].title,
        formFieldConfig: { nodeId: '', formId: '', formField: bindField, formKey: '' },
      });
    }
    emits('change', [...list]);
    close();
  }
  function close() {
    visible.value = false;
  }
  function initTreeData() {
    widgetForm?.value?.hiddenComponent?.map((com) => {
      let obj = {
        bindField: com.bindField,
        bindTable: '',
        tableKey: '',
        fieldKey: com.key,
      };
      nodes.treeData.push({
        title: com.label,
        value: JSON.stringify(obj),
      });
    });
    if (widgetForm?.value?.list.length) {
      getSelectedList(widgetForm.value.list);
    }
  }
  const filterComps = ['divider', 'upload', 'image', 'qrcode', 'button', 'map', 'opinion', 'title','ai-answer'];
  const getSelectedList = (list, bindTable?, key?) => {
    list?.map((item) => {
      if (['tab', 'grid', 'card'].includes(item.type)) {
        for (const child of item.layout!) {
          getSelectedList(child.list);
        }
      } else if (item.type == 'one-for-one') {
        getSelectedList(item.children, item.bindTable, item.key);
      } else if (item.type !== 'form' && !filterComps.includes(item.type)) {
        let params: string[] = [];
        if (item.options.datasourceType == 'api' && item.options.apiConfig.apiParams) {
          item.options.apiConfig.apiParams.forEach((p) => {
            p.tableInfo &&
              p.tableInfo.forEach((o) => {
                const value = isValidJSON(o.value);
                if (value) params.push(value.fieldKey);
              });
          });
        }
        // if (item.key !== props.formItem?.key && !params.includes(props.formItem?.key)) {
        let bindField = item.bindField;
        if (item.type == 'time-range' || item.type == 'date-range') {
          bindField = item.bindStartTime + ',' + item.bindEndTime;
        }
        let obj = {
          bindField: bindField,
          bindTable: bindTable,
          tableKey: key,
          fieldKey: item.key,
        };
        nodes.treeData.push({
          title: item.label,
          value: JSON.stringify(obj),
        });
        // }
      }
    });
  };
</script>

<style scoped>
  .title {
    display: flex;
    justify-content: space-between;
    height: 40px;
    font-size: 16px;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 10px;
  }

  .list-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    overflow: auto;
  }

  :deep(.ant-tree-treenode) {
    margin-left: 8px;
    margin-bottom: 10px;
  }

  :deep(.ant-tree-list) {
    height: 460px;
  }
</style>
