<template>
  <Dialog
    :loading="loadingInterface"
    v-model="diaVisible"
    diaTitle="分发任务"
    :width="500"
    :height="500"
    @close="closeSendFun"
    show-footer
  >
    <el-form ref="sendFormRef" :rules="sendFormRules" :model="sendForm" label-width="auto">
      <el-form-item label="上层节点：" prop="insertIndex">
        <el-tree-select
          ref="taskTreeRef"
          filterable
          :check-strictly="true"
          v-model="sendForm.insertIndex"
          :data="indexTreeData"
          node-key="uuid"
          :props="{ label: 'nodeName', value: 'uuid' }"
          default-expand-all
          :render-after-expand="false"
        >
          <template #default="{ data: { nodeName } }">
            {{ nodeName }}
          </template>
        </el-tree-select>
      </el-form-item>
      <el-form-item label="所属学科：">
        <el-select class="loadcase-lib" :teleported="false" v-model="sendForm.discipline">
          <el-option
            v-for="item in disciplineList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <div class="" v-if="formDemandAndNotFiniteElement">
        <el-form-item label="场景选择：">
          <el-select class="loadcase-lib" :teleported="false" v-model="sendForm.scenario">
            <el-option
              v-for="item in scenarioList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <div v-else>
        <el-form-item label="插入模式：">
          <el-radio-group v-model="insertTaskMode">
            <el-radio value="lib" size="large">从工况库选任务</el-radio>
            <el-radio value="custom" size="large">自定义任务名称</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="库名称：" prop="currentLoadcaseLib" v-if="insertTaskMode === 'lib'">
          <el-select
            class="loadcase-lib"
            :teleported="false"
            v-model="sendForm.currentLoadcaseLib"
            :props="{ label: 'poolName', value: 'value' }"
            value-key="poolName"
            :fit-input-width="true"
            @change="changeLoadcaseLibFun"
          >
            <el-option
              v-for="item in loadcaseLibList"
              :key="item.value"
              :label="item.poolName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="版本："
          prop="currentLoadcaseLibVersion"
          v-if="insertTaskMode === 'lib'"
        >
          <el-select
            class="version"
            :teleported="false"
            v-model="sendForm.currentLoadcaseLibVersion"
            :props="{ label: 'poolVersion', value: 'value' }"
            value-key="poolVersion"
            :fit-input-width="true"
            @change="changeLoadcaseVersionFun"
          >
            <el-option
              v-for="item in loadcaseLibVersionList"
              :key="item.value"
              :label="item.poolVersion"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择工况：" prop="chooseTaskList" v-if="insertTaskMode === 'lib'">
          <el-select-v2
            v-model="sendForm.chooseTaskList"
            :options="libTaskList"
            placeholder="请选择"
            filterable
            clearable
            value-key="uuid"
            :multiple="false"
          >
            <template #default="{ item }">
              <div class="flex items-center">
                <img class="loadcase-img" src="@/assets/imgs/projectTree/loadcase.png" alt="" />
                <span>{{ item.label }}</span>
              </div>
            </template>
          </el-select-v2>
        </el-form-item>
        <el-form-item label="任务名称：" prop="taskName" v-if="insertTaskMode === 'custom'">
          <el-input v-model="sendForm.taskName"></el-input>
        </el-form-item>
      </div>
      <el-form-item label="计划时间">
        <el-date-picker
          v-model="sendForm.planTime"
          type="datetimerange"
          placeholder="选择日期"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="仿真执行人：" prop="eMemberList">
        <UserSelect v-model="sendForm.eMemberList" :multiple="true" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="closeSendFun">取消</el-button>
        <el-button :loading="loadingInterface" type="primary" @click="sendTaskConfirmFun"
          >确认</el-button
        >
      </div>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getMemberListIds, getTagMapList } from '@/utils/task';
import { computed, nextTick, reactive, ref } from 'vue';
import { getTaskTreeFun } from '../../projectDetail/components/projectApi';
import { filterTask } from '../../projectDetail/components/project';
import { tagSortList } from '@/utils/enum/node';
import { ElMessage } from 'element-plus';
import Dialog from '@/components/common/dialog/index.vue';
import {
  getAllTaskPoolApi,
  getTaskPoolLoadcasesApi,
  getTaskPoolVersionsApi,
} from '@/api/task/taskpool';
// import { useDict } from '@/utils/useDict';
import { onMounted } from 'vue';
import UserSelect from '@/components/common/userSelect/index.vue';
import { modifyNodeTaskPerformanceApi } from '@/api/project/node';
import { CommonStore } from '@/stores/common';
import { batchUpdateTaskStatusApi } from '@/api/project/task';
import { getUserSimulationType } from '@/tenants/lyric/views/task/lyricTask';
import { enableConfigByTenant, TENANT_ENUM } from '@/tenants/tenant';

const props = defineProps({
  diaVisible: {
    type: Boolean,
    default: false,
  },
  taskInfo: {
    type: Object,
  },
});

const emits = defineEmits(['update:diaVisible', 'refreshTable']);

// const { DISCIPLINE_TYPE } = useDict('DISCIPLINE_TYPE');

const diaVisible = computed({
  get() {
    return props.diaVisible;
  },
  set(val) {
    emits('update:diaVisible', val);
  },
});

const sendForm = reactive<any>({
  beginTime: '',
  endTime: '',
  taskName: '',
  eMemberList: '',
  chooseTaskList: [],
  currentLoadcaseLibVersion: '',
  currentLoadcaseLib: '',
});

const loadingInterface = ref(false);

const closeSendFun = () => {
  emits('update:diaVisible', false);
  loadingInterface.value = false;
};
/**
 * lib 工况库
 * custom 自定义
 */
const insertTaskMode = ref('lib');

const loadcaseLibList = ref<any[]>([]);
const loadcaseLibVersionList = ref();

const changeLoadcaseLibFun = (lib: any) => {
  sendForm.currentLoadcaseLib = lib;
  queryLoadcaseLibVersionsFun();
};

const changeLoadcaseVersionFun = () => {
  getLoadcaseList();
};

const queryPoolListFun = async () => {
  const res: any = await getAllTaskPoolApi({ bCurrent: true });
  if (res.code === 200 && Array.isArray(res.data)) {
    loadcaseLibList.value = res.data.reverse();
  } else {
    loadcaseLibList.value = [];
  }
  if (loadcaseLibList.value.length > 0) {
    sendForm.currentLoadcaseLib = loadcaseLibList.value[0];
    queryLoadcaseLibVersionsFun();
  }
};

const queryLoadcaseLibVersionsFun = async () => {
  const req = {
    poolName: sendForm.currentLoadcaseLib.poolName,
  };
  const res: any = await getTaskPoolVersionsApi(req);
  if (res.code === 200 && res.data && Array.isArray(res.data) && res.data.length > 0) {
    loadcaseLibVersionList.value = res.data;
    if (loadcaseLibVersionList.value.length > 0) {
      sendForm.currentLoadcaseLibVersion = loadcaseLibVersionList.value[0];
    }
  } else {
    loadcaseLibVersionList.value = [];
  }
  // await queryTaskPoolFun();
  getLoadcaseList();
};

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

const getLoadcaseList = async () => {
  const res: any = await getTaskPoolLoadcasesApi({
    poolName: sendForm.currentLoadcaseLib.poolName,
    version: sendForm.currentLoadcaseLibVersion.poolVersion,
  });
  if (res.code === 200) {
    libTaskList.value = res.data.map((item: any) => {
      return {
        label: item.nodeName,
        value: item,
      };
    });
  }
};

const sendFormRef = ref();

const sendFormRules = reactive<any>({
  insertIndex: [{ required: true, message: '请选择上层节点', trigger: 'change' }],
  currentLoadcaseLib: [{ required: true, message: '请选择工况库', trigger: 'change' }],
  currentLoadcaseLibVersion: [{ required: true, message: '请选择工况库版本', trigger: 'change' }],
  chooseTaskList: [{ required: true, message: '请选择分发的任务', trigger: 'change' }],
  eMemberList: [{ required: true, message: '请选择仿真执行人', trigger: 'change' }],
  taskName: [{ required: true, message: '请填写任务名称', trigger: 'blur' }],
});

const taskTreeRef = ref();

const simulationType = getUserSimulationType();

/** 来自需求的任务，且非有限元仿真 */
const formDemandAndNotFiniteElement = computed(() => {
  return (
    props.taskInfo?.tag9 === 'FROM_DEMAND' &&
    simulationType.indexOf('有限元') === -1 &&
    simulationType.indexOf('DISCIPLINE_TYPE') === -1
  );
});

const sendTaskConfirmFun = () => {
  sendFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // if (insertTaskMode.value === 'lib') {
      //   if (sendForm.chooseTaskList.value.length === 0) {
      //     ElMessage.error('请选择任务');
      //     return;
      //   }
      // }
      loadingInterface.value = true;
      const parentNodeInfo = taskTreeRef.value.getCurrentNode();
      const tagProperty: { [key: string]: any } = {};
      tagSortList.forEach((item: any) => {
        // tagProperty[item] = parentNodeInfo[item] ? parentNodeInfo[item].split(',') : [];
        tagProperty[item] = parentNodeInfo[item] ? parentNodeInfo[item] : '';
      });
      let params: any = {};
      const pMemberListStr = getMemberListIds(sendForm.pMemberList);
      const payAttentionMemberStr = getMemberListIds(sendForm.payAttentionMemberList);
      let hasRepeatTask = false;
      // 手动再添加一下工况的指标
      const performanceList: any[] = [];
      if (insertTaskMode.value === 'lib' && !formDemandAndNotFiniteElement.value) {
        const chooseTaskList = [sendForm.chooseTaskList];
        const addTaskList = chooseTaskList.map((item: any) => {
          if (parentNodeInfo?.taskList?.length > 0) {
            parentNodeInfo?.taskList.forEach((task: any) => {
              if (task.nodeName === item.nodeName) {
                // 利元亨会基于同名任务再次分发，如果当前任务uuid与已有任务uuid相同，则可以继续分发
                if (enableConfigByTenant([TENANT_ENUM.LYRIC])) {
                  if (task.uuid !== sendForm.uuid) {
                    ElMessage.warning(item.nodeName + '任务已存在，无法再创建！');
                    hasRepeatTask = true;
                  }
                } else {
                  ElMessage.warning(item.nodeName + '任务已存在，无法再创建！');
                  hasRepeatTask = true;
                }
              }
            });
          }
          item.children.forEach((child: any) => {
            performanceList.push({
              ...child,
              pid: sendForm.uuid,
              parentId: sendForm.uuid,
            });
          });
          return {
            taskName: item.nodeName,
            nodeName: item.nodeName,
            // 基于已有uuid任务，将工况任务信息复制到已有任务上
            taskId: sendForm.uuid,
            ...item,
            ...tagProperty,
            beginTime: sendForm.planTime ? sendForm.planTime[0] : '',
            endTime: sendForm.planTime ? sendForm.planTime[1] : '',
            pMemberList: pMemberListStr,
            payAttentionMemberList: payAttentionMemberStr,
            eMemberList: sendForm.eMemberList,
            aMemberList: getMemberListIds(sendForm.aMemberList),
            discipline: sendForm.discipline,
          };
        });
        if (hasRepeatTask) {
          loadingInterface.value = false;
          return;
        }
        params = addTaskList[0];
      } else {
        parentNodeInfo?.taskList.forEach((task: any) => {
          if (task.nodeName === sendForm.nodeName) {
            // 利元亨会基于同名任务再次分发，如果当前任务uuid与已有任务uuid相同，则可以继续分发
            if (enableConfigByTenant([TENANT_ENUM.LYRIC])) {
              if (task.uuid !== sendForm.uuid) {
                ElMessage.warning(sendForm.nodeName + '任务已存在，无法再创建！');
                hasRepeatTask = true;
              }
            } else {
              ElMessage.warning(sendForm.nodeName + '任务已存在，无法再创建！');
              hasRepeatTask = true;
            }
          }
        });

        if (hasRepeatTask) {
          loadingInterface.value = false;
          return;
        }
        params = {
          // 从需求来，且不是有限元仿真
          taskName: formDemandAndNotFiniteElement.value ? sendForm.scenario : sendForm.taskName,
          nodeName: formDemandAndNotFiniteElement.value ? sendForm.scenario : sendForm.taskName,
          taskId: sendForm.uuid,
          nodeId: parentNodeInfo.uuid,
          ...tagProperty,
          beginTime: sendForm.planTime ? sendForm.planTime[0] : '',
          endTime: sendForm.planTime ? sendForm.planTime[1] : '',
          pMemberList: pMemberListStr,
          payAttentionMemberList: payAttentionMemberStr,
          eMemberList: sendForm.eMemberList,
          aMemberList: getMemberListIds(sendForm.aMemberList),
          discipline: sendForm.discipline,
        };
      }
      if (params.id) {
        delete params.id;
      }
      if (params.uuid) {
        delete params.uuid;
      }
      const res: any = await batchUpdateTaskStatusApi({
        req: [{ ...props.taskInfo, ...params }],
      });

      if (res.code === 200) {
        ElMessage.success('任务分发成功！');
        if (performanceList.length > 0) {
          modifyNodeTaskPerformanceApi({
            addNodeList: performanceList,
            tagMap: getTagMapList(),
          });
        }
        emits('refreshTable');
        closeSendFun();
      } else {
        ElMessage.error('任务分发失败！');
      }
      loadingInterface.value = false;
    }
  });
};

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

const sendTaskFun = async (row: any) => {
  // props.diaVisible = true;

  nextTick(() => {
    if (sendFormRef.value) {
      sendFormRef.value.resetFields();
    }
  });

  insertTaskMode.value = 'lib';
  sendForm.currentLoadcaseLib = '';
  sendForm.currentLoadcaseLibVersion = '';
  sendForm.chooseTaskList = [];
  sendForm.taskName = '';
  sendForm.beginTime = '';
  if (row.beginTime && row.endTime) {
    sendForm.planTime = [row.beginTime, row.endTime];
  } else {
    sendForm.planTime = null;
  }
  sendForm.endTime = '';
  sendForm.eMemberList = '';
  // sendForm.aMemberList = row.aMemberList;
  if (row.simType) {
    sendForm.discipline = row.simType;
  }

  const taskTree = await getTaskTreeFun(row.newTag1, row.newTag2, 1);
  indexTreeData.value = filterTask(taskTree);
  sendForm.insertIndex = row.newTag5;
  taskTreeRef.value.setCurrentKey(row.newTag5, true);

  await queryPoolListFun();

  // for (const key in sendForm) {
  //   sendForm[key] = '';
  // }

  for (const key in row) {
    if (key !== 'eMemberList') {
      sendForm[key] = row[key];
    }
  }

  sendForm.taskName = row.demandName;
  sendForm.eMemberList = getMemberListIds(row.eMemberList);
};

const commonStore = CommonStore();
const scenarioList = ref<any[]>([]);
const disciplineList = ref<any[]>([]);
onMounted(() => {
  sendTaskFun(props.taskInfo);
  disciplineList.value = commonStore.getDictData(simulationType).A;
  if (formDemandAndNotFiniteElement.value) {
    // 从角色获取
    scenarioList.value = commonStore.getDictData(simulationType + '场景').A;
  }
});
</script>
<style lang="less" scoped></style>
