<template>
  <!-- 我确认的 -->
  <div class="gl-page-content">
    <demandTable
      :row-config="{keyField:'uuid'}"
      showCheckbox
      showIndex
      ref="tableRef"
      tableName="SIMULATION_TASK_DEMAND_CONFIRM"
      :params="{type:1}"
      :api="demandListApi"
      exportFileName="我确认的需求"
    >
      <template #leftOptions>
        <el-button icon="position" type="primary" @click="batchSendFun">批量分发</el-button>
      </template>
      <template #bindTasks="slotProps">
        <el-link type="primary" @click="sendTaskFun((slotProps as any).row)">查看任务</el-link>
      </template>
      <template #tableActions="slotProps">
        <div class="gl-table-actions">
          <el-link type="primary" @click="sendTaskFun((slotProps as any).row)">分发</el-link>
        </div>
      </template>
    </demandTable>
    <!-- <BaseTable
      showCheckbox
      showIndex
      tableName="SIMULATION_TASK_DEMAND_CONFIRM"
      :params="{type:1}"
      :api="demandListApi"
      :searchLimitNum="3"
    >
      <template #leftOptions>
        <el-button type="primary" @click="bachSendVisible = true">批量分发</el-button>
      </template>
      <template #demandStatus="{row}">
        {{ DEMAND_STATUS_MAP[row.demandStatus as keyof typeof DEMAND_STATUS_MAP] }}
      </template>
      <template #achieveStatus="{row}">
        {{ TASK_CALCULATE_STATUS_OBJ[row.achieveStatus as keyof typeof DEMAND_STATUS_MAP] || '未分析' }}
      </template>
      <template #progress="{ row }">
        {{ row.progress }}%
      </template>
      <template #approvalStatus="{ row }">
        {{ row.approvalStatus || '未审批' }}
      </template>
      <template #attachment="{ row }">
        <el-link type="primary" @click="seeAttachments(row.id)">附件</el-link>
      </template>
      <template #projectId="{ row }">
        {{ row.projectName }}
      </template>
      <template #phaseId="{ row }">
        {{ row.phaseName }}
      </template>
      <template #demandType="{row}">
        {{ DEMAND_TYPE.O[row.demandType] }}
      </template>
      <template #simType="{row}">
        {{ disposeSimType(row.demandType,row.simType) }}
      </template>
      <template #tableActions="{ row }">
        <div class="gl-table-actions">
          <el-link type="primary" @click="sendTaskFun(row)">分发</el-link>
        </div>
      </template>
    </BaseTable> -->
    <batchSendTask v-if="bachSendVisible" :checkedList="checkedList" v-model:diaVisible="bachSendVisible"></batchSendTask>
    <Dialog
      v-model="sendVisible"
      :loading="loadingInterface"
      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-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>
        <!-- {{ insertTaskMode }}
        {{ insertTaskMode === 'lib' }}
        {{ insertTaskMode }} -->
        <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="true"
          >
            <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>
        <el-form-item label="计划开始时间">
          <el-date-picker
            v-model="sendForm.beginTime"
            type="datetime"
            placeholder="选择日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="计划结束时间">
          <el-date-picker
            v-model="sendForm.endTime"
            type="datetime"
            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>
      <!-- <TableForm ref="tableFormRef" tableName="SIMULATION_TASK_DEMAND_CONFIRM" >
      </TableForm> -->
      <template #footer>
        <div>
          <el-button @click="closeSendFun">取消</el-button>
          <el-button type="primary" @click="sendTaskConfirmFun">确认</el-button>
        </div>
      </template>
    </Dialog>
    <attachments :demandId="demandInfo.id" v-model:visible="attachmentsVisible" ></attachments>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import { demandListApi, issuedTaskApi } from '@/api/project/demand';
import attachments from '@/views/task/simulationTask/components/attachments.vue';
// import { CommonStore } from '@/stores/common';
import UserSelect from '@/components/common/userSelect/index.vue';
import { getAllTaskPoolApi, getTaskPoolLoadcasesApi, getTaskPoolVersionsApi } from '@/api/task/taskpool';
import { ElMessage } from 'element-plus';
import demandTable from '../components/demandTable.vue';
import { getTaskTreeFun } from '../../projectDetail/components/projectApi';
import { tagSortList } from '@/utils/enum/node';
import { filterTask, getIdMap } from '../../projectDetail/components/project';
import batchSendTask from './components/batchSendTask.vue';
import { getMemberListIds } from '@/utils/task';
// const commonStore = CommonStore();

const bachSendVisible = ref(false);

const attachmentsVisible = ref(false);

const loadingInterface = ref(false);

const demandInfo = reactive({
  id: 0,
  uuid: '',
});

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

const sendVisible = ref(false);

const closeSendFun = () => {
  sendVisible.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();
  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,
      };
    })
    ;
  }

};

// SIMULATION_TASK_DEMAND_CONFIRM
// const headData = ref<any[]>([
//   { title: '任务名称', key: 'taskName', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '任务状态', key: 'taskStatus', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '风险状态', key: 'achievement', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '任务进度', key: 'progress', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '审批状态', key: 'approvalStatus', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '仿真负责人', key: 'simLeader', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '项目', key: 'project', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '学科', key: 'discipline', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '计划结束时间', key: 'endTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '实际结束时间', key: 'actualEndTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
// ]);

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 sendTaskConfirmFun = () => {
  console.log('1234', 1234);
  sendFormRef.value.validate(async(valid: boolean) => {
    if (valid) {
      // if (insertTaskMode.value === 'lib') {
      //   if (sendForm.chooseTaskList.value.length === 0) {
      //     ElMessage.error('请选择任务');
      //     return;
      //   }
      // }
      loadingInterface.value = true;
      console.log('taskTreeRef', taskTreeRef.value.getCurrentNode());
      console.log('sendForm', sendForm);
      const parentNodeInfo = taskTreeRef.value.getCurrentNode();
      const tagProperty:{[key: string]: any;} = {};
      tagSortList.forEach((item:any) => {
        tagProperty[item] = parentNodeInfo[item] ? parentNodeInfo[item].split(',') : [];
      });
      let params = {};
      const pMemberListStr = getMemberListIds(sendForm.pMemberList);
      if (insertTaskMode.value === 'lib') {
        const addTaskList = sendForm.chooseTaskList.map((item:any) => {
          return {
            ...item,
            ...tagProperty,
            beginTime: sendForm.beginTime,
            endTime: sendForm.endTime,
            pMemberList: pMemberListStr,
            eMemberList: sendForm.eMemberList,
          };
        });
        params = {
          addNodeList: addTaskList,
          demandId: sendForm.uuid,
          idMap: getIdMap(sendForm.projectId, sendForm.phaseId),
        };
      } else {
        params = {
          addNodeList: [{
            nodeName: sendForm.taskName,
            nodeId: parentNodeInfo.uuid,
            ...tagProperty,
            beginTime: sendForm.beginTime,
            endTime: sendForm.endTime,
            pMemberList: pMemberListStr,
            eMemberList: sendForm.eMemberList,
          }],
          demandId: sendForm.uuid,
          idMap: getIdMap(sendForm.projectId, sendForm.phaseId),
        };
      }
      const res:any = await issuedTaskApi({ reqList: [params] });
      if (res.code === 200) {
        ElMessage.success('任务分发成功！');
        closeSendFun();
      } else {
        ElMessage.error('任务分发失败！');
      }
      loadingInterface.value = false;
    }
  });
};

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

const sendTaskFun = async(row:any) => {
  console.log('row', row);
  sendVisible.value = true;
  const taskTree = await getTaskTreeFun(row.projectId, row.phaseId);
  indexTreeData.value = filterTask(taskTree);
  console.log('indexTreeData', indexTreeData.value);
  await queryPoolListFun();

  for (const key in row) {
    if (key !== 'eMemberList') {
      sendForm[key] = row[key];
    }
  }
  sendForm.taskName = row.demandName;
  sendForm.eMemberList = getMemberListIds(row.eMemberList);
  console.log('sendForm', sendForm, row);
};

const tableRef = ref();
const checkedList = ref();
const batchSendFun = () => {
  checkedList.value = tableRef.value.tableRef.tableRef.getCheckboxRecords();
  if (checkedList.value.length === 0) {
    return ElMessage.warning('请勾选需要分发的需求！');
  }
  bachSendVisible.value = true;
  console.log('tableRef.value.tableRef.getCheckboxRecords()', tableRef.value.tableRef.tableRef.getCheckboxRecords());
};

</script>

<style lang="scss" scoped>
  .loadcase-img {
    width: 18px;
    vertical-align: text-bottom;
    margin-right: 5px;
  }
</style>
