<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="prefixCls">
        <a-table :columns="columns" :data-source="formData.list" :pagination="false" size="middle">
          <template #headerCell="{ column }">
            <div class="header-cell__custom-title">{{ column.title }}</div> </template
          ><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 { cloneDeep } from 'lodash-es';
  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';
  import { useDesign } from '/@/hooks/web/useDesign';
  const { prefixCls } = useDesign('basic-table');
  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;
      },
      align: 'center',
    },
    {
      title: t('表单名称'),
      dataIndex: 'formName',
      key: 'formName',
      align: 'center',
    },
    {
      title: t('表单ID'),
      dataIndex: 'formId',
      key: 'formId',
      align: 'center',
    },
    {
      title: t('表单类别'),
      key: 'formType',
      dataIndex: 'formType',
      align: 'center',
    },
    {
      title: t('所属节点'),
      key: 'nodeName',
      dataIndex: 'nodeName',
      align: 'center',
    },
    {
      title: t('更新状态'),
      key: 'status',
      align: 'center',
    },
    {
      title: t('备注'),
      key: 'remark',
      dataIndex: 'remark',
      align: 'center',
    },
  ];
  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, processInfo } = 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(cloneDeep(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  合并新数据与旧数据
      }
    }
    if (processInfo.summaryInfo?.length) {
      //更新流程摘要
      processInfo.summaryInfo = processInfo.summaryInfo.filter((info) => {
        if (info.formKey === 'basicInfo') return true;
        const key = info.formKey.split('_');
        if (!formInfoData.get(key[1])) {
          return false;
        } else {
          const data = formInfoData
            .get(key[1])
            ?.children?.find((res) => res.fieldId === info.fieldId);
          if (data) {
            info.fieldName = data.fieldName;
          }
          return data;
        }
      });
    }
  }
</script>

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

  .box-head {
    margin: 10px 0;
  }

  .bpmn-button {
    width: 82px;
    padding: 0;
    border-radius: 4px;
  }
</style>
