<template>
  <Dialog
    v-model="visible"
    :diaTitle="pageTitle"
    :width="'30%'"
    :height="'50%'"
    @close="handleCloseFun"
    show-footer
  >
    <!-- <el-drawer
    v-model="visible"
    :title="pageTitle"
    :size="600"
    :close-on-click-modal="false"
    @close="handleCloseFun"
  > -->
    <el-form
      v-loading="createLoading"
      label-width="120"
      ref="formRef"
      :model="runInfoFormData"
      @submit.prevent=""
    >
      <el-form-item label="拼接工况信息：" v-if="operateType != 'editRun'">
        <el-radio-group v-model="runInfoFormData.isJointProjectInfo" @change="changeJoinFun">
          <el-radio :value="true">是</el-radio>
          <el-radio :value="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="算例名称：" prop="runNames">
        <el-input
          ref="runNameRef"
          placeholder="例：V1"
          v-model="runInfoFormData.runNames"
          :disabled="operateType === 'editRun'"
        />
      </el-form-item>
      <el-form-item
        label="流程模板："
        prop="templateName"
        :rules="[
          {
            required: true,
            pattern: /\S/,
            message: '请选择模板',
            trigger: 'check',
          },
        ]"
      >
        <el-select v-model="runInfoFormData.templateName" filterable @change="templateChangeFun">
          <el-option
            v-for="item in templateNameList"
            :key="item.uuid"
            :value="item.uuid"
            :label="item.templateName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="父级算例：" v-if="operateType === 'createChildRun'">
        <el-select v-model="runInfoFormData.parentRunVision" filterable>
          <el-option
            v-for="item in runAllVersion"
            :key="item.id"
            :value="item.id"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="算例说明：">
        <el-input
          rows="4"
          :autosize="{ minRows: 2, maxRows: 6 }"
          type="textarea"
          v-model="runInfoFormData.descript"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseFun">取消</el-button>
        <el-button type="primary" @click="createSuccessFun">确认</el-button>
      </span>
    </template>
    <!-- </el-drawer> -->
  </Dialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive, onMounted } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import { NODE_TYPE } from '@/utils/enum/node';
import { ElMessage } from 'element-plus';
import { queryFlowTemplateApi } from '@/api/capability/flow';
import { getRunVersionApi, getTaskRunVersionApi, queryTaskRunApi } from '@/api/project/run';

const props = defineProps({
  divInfo: {
    type: Object,
    default: () => {},
  },
  operateFlag: {
    type: String,
    default: 'createRun',
  },
});

const visible = ref(true);
const createLoading = ref(false);

const runInfoFormData = reactive<any>({
  isJointProjectInfo: true,
  runNames: '',
  templateName: '',
  parentRunVision: '',
  descript: '',
});

const templateNameList = ref<any>([]);

const templateChangeFun = () => {};

const runAllVersion = ref<any>([]);

const emits = defineEmits(['close', 'comfirm', 'update']);

const pageTitle = ref('创建算例');
const operateType = ref('');
const handleCloseFun = () => {
  emits('close');
};

// 确认事件
const createSuccessFun = () => {
  if (!runInfoFormData.templateName) {
    // runInfoFormData.templateName = 1;

    ElMessage.warning('未选择流程模板，无法新建算例！');
    return;
  }

  if (operateType.value != 'editRun') {
    emits('comfirm', {
      info: runInfoFormData,
      flag: operateType.value,
    });
  } else {
    emits('update', {
      info: runInfoFormData,
      flag: operateType.value,
    });
  }
};

// 拼接改变
const changeJoinFun = async () => {
  const version = await getRunDetailInfoFun(props.divInfo.uuid, operateType.value);
  if (runInfoFormData.isJointProjectInfo) {
    runInfoFormData.runNames = (props.divInfo.nodeName || props.divInfo.runName) + '_V' + version;
  } else {
    runInfoFormData.runNames = '算例_' + 'V' + version;
  }
};

const getRunDetailInfoFun = async (id: any, flag: any) => {
  const param: any = {};
  if (flag === 'createRun' || flag === 'copyRun') {
    param.taskId = id;
  } else {
    param.runId = id;
  }

  const res: any = await queryTaskRunApi(param);
  if (res && res.code === 200) {
    const length = res.data.length + 1 || 1;
    return length;
  }
};

const geTemplateListFun = async () => {
  const res: any = await queryFlowTemplateApi({
    current: 1,
    size: 999,
    type: 1,
  });

  if (res && res.code === 200) {
    templateNameList.value = res.data.data;
  }
};

const getRunVersionData = async (param: any) => {
  const { type, uuid }: any = param;
  let res: any = '';
  let version: any = 1;
  if (type === NODE_TYPE.TASK) {
    res = await getTaskRunVersionApi({
      taskId: uuid,
    });

    if (res && res.code === 200) {
      version = res?.data?.length + 1 || 1;
    }
  }
  if (type === NODE_TYPE.RUN) {
    res = await getRunVersionApi({
      runId: uuid,
    });

    if (res && res.code === 200) {
      version = res.data?.children?.length + 1 || 1;
    }
  }

  return version;
};

watch(
  () => props.operateFlag,
  async (newVal) => {
    await geTemplateListFun();

    if (newVal) {
      let version: any = 1;
      operateType.value = newVal;

      if (newVal === 'createRun') {
        pageTitle.value = '创建算例';

        version = await getRunVersionData({ type: NODE_TYPE.TASK, uuid: props.divInfo?.uuid });
      }

      if (newVal === 'createChildRun') {
        version = await getRunVersionData({ type: NODE_TYPE.RUN, uuid: props.divInfo?.uuid });

        pageTitle.value = '创建子算例';

        runAllVersion.value = [
          {
            id: props.divInfo?.uuid,
            label: props.divInfo?.runName,
            nodeType: 'run',
          },
        ];
        runInfoFormData.parentRunVision = props.divInfo?.uuid;
      }

      if (newVal === 'copyRun') {
        version = await getRunVersionData({ type: NODE_TYPE.TASK, uuid: props.divInfo?.taskId });

        pageTitle.value = '复制算例';
      }

      if (newVal === 'editRun') {
        pageTitle.value = '编辑算例信息';

        runInfoFormData.runNames = props.divInfo.nodeName || props.divInfo.runName;
        runInfoFormData.templateName = props.divInfo.flowTemplateName;
      } else {
        // version = await getRunDetailInfoFun(props.divInfo.uuid, operateType.value);

        // 如果是新增算例
        if (props.divInfo && props.divInfo?.nodeType === NODE_TYPE.TASK) {
          if (runInfoFormData.isJointProjectInfo) {
            runInfoFormData.runNames = props.divInfo.nodeName + '_V' + version;
          }

          const list: any = props.divInfo.flowTemplate ? props.divInfo.flowTemplate.split(',') : [];

          if (list.length) {
            runInfoFormData.templateName = templateNameList.value.find((item: any) => {
              return item.templateCode === list[0];
            })?.uuid;
          } else {
            runInfoFormData.templateName = '';
          }
        }

        // 如果是新增子算例或者复制算例
        if (props.divInfo && props.divInfo?.nodeType === NODE_TYPE.RUN) {
          if (runInfoFormData.isJointProjectInfo) {
            if (newVal === 'copyRun') {
              runInfoFormData.runNames = props.divInfo.parentName + '_V' + version;
            } else {
              runInfoFormData.runNames = props.divInfo.runName + '_V' + version;
            }
          }
          runInfoFormData.templateName = props.divInfo.flowTemplateName;
        }
      }
    }
  },
  {
    immediate: true,
  }
);

// 获取任务下所有的算例信息

onMounted(async () => {
  // runInfoFormData.templateName = props.divInfo.flowTemplate;
});
</script>

<style lang="scss" scoped></style>
