<template>
  <div class="comp-content">
    <Dialog
      :loading="loadingInterface"
      v-model="dialogVisible"
      :diaTitle="
        dialogType === REPORT_OPERATION_TYPE.CREATE
          ? '新增报告模板'
          : dialogType === REPORT_OPERATION_TYPE.COPY
            ? '复制报告模板'
            : dialogType === REPORT_OPERATION_TYPE.UPGRADE
              ? '升版报告模板'
              : '编辑报告模板'
      "
      :width="500"
      :height="450"
      @close="closeFun"
      show-footer
    >
      <TableForm
        ref="tableFormRef"
        tableName="SIMULATION_REPORT_LIB_LIST"
        :showDisabled="dialogType === 'upgrade'"
        v-model:data="editRowInfo"
      >
        <template #form-templateVersion>
          <div class="template-version">
            {{
              dialogType === REPORT_OPERATION_TYPE.CREATE
                ? 'V1.0'
                : dialogType === REPORT_OPERATION_TYPE.EDIT
                  ? templateVersion
                  : dialogType === REPORT_OPERATION_TYPE.UPGRADE
                    ? templateVersion
                    : 'V1.0'
            }}
          </div>
        </template>
        <template #form-simulationPoolInfoList>
          <PoolTaskSelect v-model="simulationPoolInfoList" layout="vertical" />
        </template>
      </TableForm>
      <template #footer>
        <div>
          <el-button @click="closeFun">取消</el-button>
          <el-button
            type="primary"
            v-if="dialogType !== REPORT_OPERATION_TYPE.UPGRADE"
            @click="confirmFun('ok')"
            :loading="loadingInterface"
            >确定</el-button
          >
          <el-button type="primary" @click="confirmFun('next')" :loading="loadingInterface"
            >下一步</el-button
          >
        </div>
      </template>
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import Dialog from '@/components/common/dialog/index.vue';
// import { ElMessage } from 'element-plus';
import { computed, ref, watch } from 'vue';
import TableForm from '@/components/common/table/tableForm.vue';
import PoolTaskSelect from '@/components/pool/poolTaskSelect.vue';
import { ElMessage } from 'element-plus';
import { createReportTemplateApi, updateReportTemplateApi } from '@/api/capability/report';
import { REPORT_OPERATION_TYPE } from '@/utils/enum/report';
import { getFileBaseInfoApi } from '@/api/data/data';

const props = defineProps<{
  showDialog: boolean;
  dialogType: REPORT_OPERATION_TYPE;
  flowContent: any;
  templateVersion: string;
}>();

const tableFormRef = ref();
const simulationPoolInfoList = ref<any[]>([]);

const loadingInterface = ref(false);

const dialogVisible = computed(() => {
  return props.showDialog;
});
const emits = defineEmits(['update:showDialog', 'confirm']);
// const projectForm = reactive<any>({
//   nodeName: '',
//   nodeCode: '',
//   nodeSubType: '',
//   memberList: [],
//   beginTime: '',
//   endTime: '',
//   description: '',
// });

const confirmFun = async (type: string) => {
  if (await tableFormRef.value.validateFun()) {
    loadingInterface.value = true;
    const flowForm = tableFormRef.value.getFormDataFun();
    if (
      props.dialogType === REPORT_OPERATION_TYPE.CREATE ||
      props.dialogType === REPORT_OPERATION_TYPE.COPY
    ) {
      const formData = new FormData();
      formData.append('templateVersion', 'V1.0');
      for (const key in flowForm) {
        if (key === 'file') {
          if (props.dialogType === REPORT_OPERATION_TYPE.COPY) {
            formData.append('copyFlag', 'Y');
            formData.append('fileId', flowForm.fileId);
          } else {
            formData.append(key, flowForm[key][0].raw);
          }
        } else {
          if (
            key !== 'templateVersion' &&
            key !== 'type' &&
            key !== 'templateStatus' &&
            key !== 'creatorName' &&
            key !== 'createTime' &&
            key !== 'approveType'
          ) {
            formData.append(key, flowForm[key] ? flowForm[key] : '');
          }
        }
      }
      const flowUuid = await createFlow(formData);
      emits('confirm', { type, uuid: flowUuid });
    } else if (props.dialogType === REPORT_OPERATION_TYPE.UPGRADE) {
      emits('confirm', {
        type,
        uuid: flowForm.uuid,
        comment: flowForm.comment,
        file: flowForm.file,
        fileId: flowForm.file[0].id,
      });
    } else {
      await editReport(flowForm);
      emits('confirm', { type, uuid: flowForm.uuid });
    }
    loadingInterface.value = false;
  }
};

const createFlow = async (params: any) => {
  // const memberList = projectForm.memberList.map((item: any) => {
  //   return JSON.parse(item);
  // });
  // const projectForm = tableFormRef.value.getFormDataFun();
  // const tagKeyMap = getTagKeyMap();
  const res: any = await createReportTemplateApi(params);
  if (res && res.code === 200) {
    ElMessage.success('创建流程成功！');
    closeFun();
    return res.data;
  } else {
    ElMessage.error(res.message || '创建流程失败');
  }
};

const editReport = async (params: any) => {
  let editFlag = false;
  for (const key in oldFormData.value) {
    if (oldFormData.value[key] !== params[key]) {
      editFlag = true;
      break;
    }
    // 有新文件也认定为有变更
    if (params.file && params.file.length > 0) {
      if (params.file[0].raw) {
        editFlag = true;
      }
    }
  }
  // 有变更才调接口
  if (editFlag) {
    const formData = new FormData();
    formData.append('templateVersion', params.templateVersion);
    formData.append('templateName', params.templateName);
    formData.append('templateType', params.templateType);
    formData.append('comment', params.comment);
    formData.append('uuid', params.uuid);
    formData.append('id', params.id);
    formData.append('extras', params.extras);
    formData.append('fileId', oldFormData.value.fileId);
    formData.append('templateContent', oldFormData.value.templateContent);
    if (params.file && params.file.length > 0) {
      if (params.file[0].raw) {
        formData.append('file', params.file[0].raw);
      }
    }
    const res: any = await updateReportTemplateApi(formData);
    if (res && res.code === 200) {
      ElMessage.success(res.message);
      closeFun();
    } else {
      ElMessage.error(res.message || '编辑报告基本属性失败！');
    }
  } else {
    closeFun();
  }
};

const closeFun = () => {
  emits('update:showDialog', false);
};

// const nextPageFun = () => {
//   if (hasSameValue()) return;
//   emits('update:currentProjectBaseInfo', { ...tableFormRef.value.getFormDataFun(), nodeType: NODE_TYPE.PROJECT });
//   emits('nextPageFun', 'basePage');
// };

const oldFormData = ref<any>({});

const editRowInfo = ref<any>({});

const setEditForm = (val: any) => {
  oldFormData.value = val;
  // nextTick(() => {
  simulationPoolInfoList.value = val.simulationPoolInfoList || [];
  // tableFormRef.value.setFormDataFun({ ...val });
  editRowInfo.value = { ...val };
  // });
};

const resetForm = () => {
  // projectForm.nodeName = '';
  // projectForm.nodeCode = '';
  // projectForm.nodeSubType = '';
  // projectForm.memberList = [];
  // projectForm.beginTime = '';
  // projectForm.endTime = '';
  // projectForm.description = '';
  simulationPoolInfoList.value = [];
  // tableFormRef.value.resetFun();
  editRowInfo.value = {};
};

const setOptionsFun = (key: string, options: any[]) => {
  tableFormRef.value.setOptionsFun(key, options);
};

watch(
  () => props.showDialog,
  async () => {
    if (
      props.dialogType === REPORT_OPERATION_TYPE.EDIT ||
      props.dialogType === REPORT_OPERATION_TYPE.UPGRADE ||
      props.dialogType === REPORT_OPERATION_TYPE.COPY
    ) {
      const fileInfo: any = await getFileBaseInfoApi({ fileId: editRowInfo.value.fileId });
      editRowInfo.value.file = [
        { name: fileInfo.data.originalName, size: fileInfo.data.fileSize, id: fileInfo.data.id },
      ];
    }
  }
);

defineExpose({
  // projectForm,
  setEditForm,
  resetForm,
  setOptionsFun,
});
</script>
<style lang="scss" scoped>
.template-version {
  color: #0366ff;
}
</style>
