<template>
  <div class="comp-content">
    <Dialog
      :loading="loadingInterface"
      v-model="dialogVisible"
      :diaTitle="dialogType === 'create'?'新增流程':dialogType === 'copy'?'复制流程':'编辑流程'"
      :width="500"
      :height="500"
      @close="closeFun"
      show-footer
    >
      <TableForm
        ref="tableFormRef"
        tableName="SIMULATION_FLOW_LIB_LIST"
        :showDisabled="dialogType === 'upgrade'"
      >
        <template #form-templateVersion>
          <div>
            {{ dialogType === FLOW_OPERATION_TYPE.CREATE?'V1.0':
              dialogType === FLOW_OPERATION_TYPE.EDIT?templateVersion:
              dialogType === FLOW_OPERATION_TYPE.UPGRADE?templateVersion:'V1.0'
            }}
          </div>
        </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, nextTick, ref } from 'vue';
import TableForm from '@/components/common/table/tableForm.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 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) => {
  console.log('tableFormRef.value', tableFormRef.value, await tableFormRef.value.validateFun());
  if (await tableFormRef.value.validateFun()) {
    loadingInterface.value = true;
    const flowForm = tableFormRef.value.getFormDataFun();
    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 });
      }
    } else {
      // console.log('编辑项目', projectForm);
      await editFlow(flowForm);
      emits('confirm', { type, uuid: flowForm.uuid });
    }
    loadingInterface.value = false;
  }
};

const createFlow = async(params: any) => {
  // console.log('projectForm', projectForm);
  // const memberList = projectForm.memberList.map((item: any) => {
  //   return JSON.parse(item);
  // });
  console.log('projectForm', tableFormRef.value.getFormDataFun());
  // const projectForm = tableFormRef.value.getFormDataFun();

  // const tagKeyMap = getTagKeyMap();
  const res:any = await addFlowTemplateDraftApi(params);
  if (res && res.code === 200) {
    ElMessage.success('创建流程成功！');
    closeFun();
    return res.data;
  } else {
    ElMessage.error(res.msg || '创建流程失败');
  }
};

const editFlow = async(params: any) => {
  console.log('oldFormData', oldFormData.value);
  console.log('params', params);
  console.log('json', JSON.stringify(oldFormData.value) === JSON.stringify(params));
  let editFlag = false;
  for (const key in oldFormData.value) {
    if (oldFormData.value[key] !== params[key]) {
      console.log('oldFormData.value[key]', key, 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.msg || '编辑流程基本属性失败！');
    }
  } else {
    closeFun();
  }
};

const closeFun = () => {
  console.log('关闭弹窗');
  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 setEditForm = (val: any) => {
  console.log('val', val, tableFormRef.value);
  oldFormData.value = val;
  nextTick(() => {
    tableFormRef.value.setFormDataFun({ ...val });
  });
};

const resetForm = () => {
  // projectForm.nodeName = '';
  // projectForm.nodeCode = '';
  // projectForm.nodeSubType = '';
  // projectForm.memberList = [];
  // projectForm.beginTime = '';
  // projectForm.endTime = '';
  // projectForm.description = '';

  tableFormRef.value.resetFun();
};

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

defineExpose({
  // projectForm,
  setEditForm,
  resetForm,
  setOptionsFun,
});
</script>
