<template>
  <div class="comp-content">
    <Dialog
      :loading="loadingInterface"
      v-model="dialogVisible"
      :diaTitle="
        dialogType === FLOW_OPERATION_TYPE.CREATE
          ? '新增流程'
          : dialogType === FLOW_OPERATION_TYPE.COPY
            ? '复制流程'
            : dialogType === FLOW_OPERATION_TYPE.UPGRADE
              ? '升版流程'
              : '编辑流程'
      "
      :width="500"
      :height="400"
      @close="closeFun"
      show-footer
    >
      <TableForm
        ref="tableFormRef"
        tableName="SIMULATION_FLOW_LIB_LIST"
        :showDisabled="dialogType === 'upgrade'"
        v-model:data="editRowInfo"
      >
        <template #form-templateVersion>
          <div class="template-version">
            {{
              dialogType === FLOW_OPERATION_TYPE.CREATE
                ? 'V1.0'
                : dialogType === FLOW_OPERATION_TYPE.EDIT
                  ? templateVersion
                  : dialogType === FLOW_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" @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 } from 'vue';
import TableForm from '@/components/common/table/tableForm.vue';
import PoolTaskSelect from '@/components/pool/poolTaskSelect.vue';
import { addFlowTemplateDraftApi, updateFlowTemplateDraftApi } from '@/api/capability/flow';
import { ElMessage } from 'element-plus';
import { FLOW_OPERATION_TYPE } from '@/utils/enum/flow';

const props = defineProps<{
  showDialog: boolean;
  dialogType: FLOW_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();
    flowForm.simulationPoolInfoList = simulationPoolInfoList.value;
    if (
      props.dialogType === FLOW_OPERATION_TYPE.CREATE ||
      props.dialogType === FLOW_OPERATION_TYPE.COPY
    ) {
      if (props.dialogType === FLOW_OPERATION_TYPE.COPY) {
        flowForm.viewContent = props.flowContent.viewContent;
        flowForm.templateContent = props.flowContent.templateContent;
      }
      const flowRes = await createFlow(flowForm);
      if (flowRes?.uuid) {
        emits('confirm', { type, uuid: flowRes.uuid, tVersion: flowRes.templateVersion });
      }
    } else {
      await editFlow(flowForm);
      emits('confirm', { type, uuid: flowForm.uuid, tVersion: props.templateVersion });
    }
    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 addFlowTemplateDraftApi(params);
  if (res && res.code === 200) {
    if (res.data?.uuid) {
      ElMessage.success('创建流程成功！');
      closeFun();
    } else {
      ElMessage.warning(res.data);
    }
    return res.data;
  } else {
    ElMessage.warning(res.message || '创建流程失败');
  }
};

const editFlow = async (params: any) => {
  let editFlag = false;
  for (const key in oldFormData.value) {
    if (oldFormData.value[key] !== params[key]) {
      editFlag = true;
      break;
    }
  }
  if (editFlag) {
    const res: any = await updateFlowTemplateDraftApi(params);
    if (res && res.code === 200) {
      ElMessage.success('更新流程基本属性成功！');
      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({});

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);
};

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