<template>
  <div>
    <a-button type="primary" class="bpmn-button" @click="show">{{ t('更新表单') }}</a-button>

    <a-modal
      v-model:visible="visible"
      :title="t('更新表单配置')"
      :forceRender="false"
      :closable="false"
      :width="1000"
    >
      <div class="box">
        <NodeHead class="box-head" :node-name="t('更新表单配置')" />
        <a-table :columns="columns" :data-source="formData.list" :pagination="false">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-spin v-if="!record.status" />
              <span v-else>{{ t('成功') }}</span>
            </template>

            <template v-if="column.key === 'formType'">
              <span v-if="record.formType === 1">{{ t('自定义表单') }}</span>
              <span v-else>{{ t('系统表单') }}</span>
            </template>
          </template>
        </a-table>
      </div>
      <template #footer>
        <a-button key="back" @click="submit">{{ t('取消') }}</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="submit">{{
          t('确定')
        }}</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { computed, reactive, ref } from 'vue';
  import { getFormConfig, compareFormInfo } from '/@bpmn/config/formPermission';
  import { BpmnNodeKey } from '/@/enums/workflowEnum';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useBpmnStore } from '/@bpmn/store/bpmn';
  import { setProperties } from '/@bpmn/config/property';
  import {
    FormConfigItem,
    FormSettingItem,
    UpdateFormConfigItem,
  } from '/@/model/workflow/formSetting';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const visible = ref(false);
  const formData: {
    list: Array<UpdateFormConfigItem>;
    indexMap: Map<string, number>;
  } = reactive({
    okDisabled: true,
    cancelDisabled: true,
    list: [],
    indexMap: new Map(),
  });
  const columns = [
    {
      title: t('序号'),
      dataIndex: 'index',
      key: 'index',
      customRender: (column) => {
        return column.index + 1;
      },
    },
    {
      title: t('表单名称'),
      dataIndex: 'formName',
      key: 'formName',
    },
    {
      title: t('表单ID'),
      dataIndex: 'formId',
      key: 'formId',
    },
    {
      title: t('表单类别'),
      key: 'formType',
      dataIndex: 'formType',
    },
    {
      title: t('所属节点'),
      key: 'nodeName',
      dataIndex: 'nodeName',
    },
    {
      title: t('更新状态'),
      key: 'status',
    },
    {
      title: t('备注'),
      key: 'remark',
      dataIndex: 'remark',
    },
  ];
  const loading = computed(() => {
    if (
      formData.list.filter((ele) => {
        return ele.status;
      }).length == 0
    ) {
      return true;
    } else {
      return false;
    }
  });
  function show() {
    visible.value = true;
    updateFormData();
  }
  function submit() {
    formData.list = [];
    formData.indexMap = new Map();
    visible.value = false;
  }
  async function updateFormData() {
    let formInfoData = new Map(); // formId 表单数据
    const store = useBpmnStore();
    const { info, defaultFormList, setDefaultFormList } = store;
    //更新默认表单
    if (defaultFormList.length > 0) {
      let newDefaultFormList: Array<FormSettingItem> = [];
      for (let index = 0; index < defaultFormList.length; index++) {
        const element = defaultFormList[index];
        let item = {
          key: element.key,
          formId: element.formId,
          formName: element.formName,
          formType: element.formType,
        };
        try {
          let result = await getFormConfig(item);
          newDefaultFormList.push(result);
        } catch (error) {}
      }
      setDefaultFormList(newDefaultFormList);
    }

    for (const item of info.values()) {
      const showNodeTypes = [BpmnNodeKey.START, BpmnNodeKey.USER];
      if (showNodeTypes.includes(item.type)) {
        if (item.formConfigs) {
          item.formConfigs.forEach((ele, index) => {
            formInfoData.set(ele.formId, {
              key: ele.key,
              formType: ele.formType,
              formId: ele.formId,
              formName: ele.formName,
            });
            let formKey = item.id + ele.formId + index;
            let formKeyIndx = formData.list.length + 1;
            formData.indexMap.set(formKey, formKeyIndx);
            formData.list[formKeyIndx] = {
              formKey,
              formName: ele.formName,
              formId: ele.formId,
              formType: ele.formType,
              nodeName: item.name,
              status: false,
              remark: '',
            };
          });
        }
      }
    }
    for (let [formId, value] of formInfoData) {
      let item = {
        formId: formId,
        key: value.key,
        formName: value.formName,
        formType: value.formType,
      };
      try {
        let result = await getFormConfig(item);
        formInfoData.set(formId, result);
      } catch (error) {}
    }
    for (const item of info.values()) {
      const showNodeTypes = [BpmnNodeKey.START, BpmnNodeKey.USER];
      let properties = item;
      if (showNodeTypes.includes(item.type)) {
        let formConfigs: Array<FormConfigItem> = [];
        if (item.formConfigs) {
          item.formConfigs.forEach((ele, index) => {
            let formKeyIndx = formData.indexMap.get(item.id + ele.formId + index);
            if (formInfoData.has(ele.formId)) {
              let formConfig: FormConfigItem = compareFormInfo(ele, formInfoData.get(ele.formId));
              formConfigs.push(formConfig);
              if (formKeyIndx) formData.list[formKeyIndx].status = true;
            } else {
              if (formKeyIndx) formData.list[formKeyIndx].status = false;
            }
          });
        }
        if (formConfigs.length > 0) {
          properties.formConfigs = formConfigs;
        }
        setProperties(item.id, properties); // setInfo  合并新数据与旧数据
      }
    }
  }
</script>

<style scoped>
  .box {
    padding: 10px 20px;
  }

  .box-head {
    margin: 10px 0;
  }
</style>
