<template>
  <Dialog
    v-model="visible"
    diaTitle="生成报告"
    :width="'80%'"
    :height="'80%'"
    :zIndex="100"
    @close="handleCloseFun"
  >
    <div class="report-page">
      <div class="form-box">
        <el-form :model="reportFormData" inline>
          <el-form-item label="报告名称：">
            <el-input class="w180" v-model="reportFormData.reportName"></el-input>
          </el-form-item>
          <el-form-item label="申请部门：">
            <el-input class="w180" v-model="reportFormData.department"></el-input>
          </el-form-item>
          <el-form-item label="申请人员：">
            <el-input class="w180" v-model="reportFormData.applicants"></el-input>
          </el-form-item>
          <el-form-item label="申请日期：">
            <el-date-picker
              class="w180"
              v-model="reportFormData.date"
              type="datetime"
              placeholder="申请日期"
              format="YYYY-MM-DD hh:mm:ss"
              value-format="YYYY-MM-DD hh:mm:ss"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="项目编号：">
            <el-input class="w180" v-model="reportFormData.projectNum"></el-input>
          </el-form-item>
          <el-form-item label="工位编号：">
            <el-input class="w180" v-model="reportFormData.workspaceNum"></el-input>
          </el-form-item>
          <el-form-item label="工位名称：">
            <el-input class="w180" v-model="reportFormData.workspace"></el-input>
          </el-form-item>
          <el-form-item label="分析类型：">
            <el-select class="w180" v-model="reportFormData.taskType" @change="taskTypeChangeFun">
              <el-option
                v-for="item in taskTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
            <!-- <el-tooltip
              class="box-item"
              effect="dark"
              :content="
                '该类型包含的图片文件名称为：' + taskTypeImgFileMap[reportFormData.taskType]
              "
              placement="top-start"
            >
              <el-icon class="ml5"><InfoFilled /></el-icon>
            </el-tooltip> -->
          </el-form-item>
          <el-form-item label="报告版本：">
            <el-input class="w180" v-model="reportFormData.reportVer"></el-input>
          </el-form-item>
          <el-form-item label="文件编号：">
            <el-input class="w180" v-model="reportFormData.fileNum"></el-input>
          </el-form-item>
          <el-form-item label="拟定时间：">
            <el-date-picker
              class="w180"
              v-model="reportFormData.formulateTime"
              type="datetime"
              placeholder="拟定时间"
              format="YYYY-MM-DD hh:mm:ss"
              value-format="YYYY-MM-DD hh:mm:ss"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="检查时间：">
            <el-date-picker
              class="w180"
              v-model="reportFormData.checkTime"
              type="datetime"
              placeholder="检查时间"
              format="YYYY-MM-DD hh:mm:ss"
              value-format="YYYY-MM-DD hh:mm:ss"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="审批时间：">
            <el-date-picker
              class="w180"
              v-model="reportFormData.approveTime"
              type="datetime"
              placeholder="审批时间"
              format="YYYY-MM-DD hh:mm:ss"
              value-format="YYYY-MM-DD hh:mm:ss"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="任务名称：">
            <el-input class="w180" v-model="reportFormData.loadcaseName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="createSuccessFun">生成</el-button>
            <el-button type="">刷新</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="content-box">
        <el-form>
          <el-form-item label="图片选择：">
            <div class="img-content">
              <template v-for="item in resultImgList" :key="item.id">
                <div class="img-item" v-if="item.show">
                  <el-checkbox v-model="item.checkImg" class="check-style" size="large" />
                  <!-- :preview-src-list="[item.url]" -->
                  <el-image
                    class="img-style"
                    title="点击预览图片"
                    :src="item.url"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    show-progress
                    :initial-index="4"
                    fit="cover"
                  />
                </div>
              </template>
            </div>
          </el-form-item>
          <el-form-item label="指标选择：">
            <taskPerformance
              ref="taskPerformanceRef"
              :task-info="currentNodeInfo"
              :run-info="currentNodeInfo"
              :param-type="currentNodeInfo?.nodeType"
            ></taskPerformance>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import dayjs from 'dayjs';
import taskPerformance from '@/components/taskDetail/taskPerformance.vue';
import { generateReportApi, listSimulationKeyResultApi } from '@/api/project/run';
import { getUserData } from '@/utils/user';
import { cloneDeep } from 'lodash-es';

const env = import.meta.env;

const props = defineProps({
  currentNodeInfo: {
    type: Object,
    default: () => {},
  },
  parentNodeInfo: {
    type: Object,
    default: () => {},
  },
  workspaceInfo: {
    type: Object,
    default: () => {},
  },
});

const emits = defineEmits(['close']);
const visible = ref(true);
const taskPerformanceRef = ref();
const reportFormData = reactive<any>({
  reportName: '',
  department: '',
  applicants: '',
  date: '',
  projectNum: '',
  workspaceNum: '',
  workspace: '',
  taskType: 'statics',
  reportVer: '',
  fileNum: '',
  formulateTime: '',
  checkTime: '',
  approveTime: '',
  isBatch: false,
  loadcaseName: '',
});

// const taskTypeImgFileMap = ref<any>({
//   statics: [
//     'model.png',
//     'stand_distance.png',
//     'stand_stress.png',
//     'forklift_stress.png',
//     'forklift_distance.png',
//     'forklift_max_stress.png',
//   ],
//   dynamics: [
//     'square_stress_img0.png',
//     'square_stress_img1.png',
//     'square_distance_img1.png',
//     'square_stress_img2.png',
//     'actuat_distance_img1.png',
//     'actuat_stress_img1.png',
//     'square_x_curve_distance.png',
//     'square_y_curve_distance.png',
//     'square_z_curve_distance.png',
//     'square_stress_img3.png',
//     'actuat_x_curve_distance.png',
//     'actuat_y_curve_distance.png',
//     'actuat_z_curve_distance.png',
//     'actuat_stress_img2.png',
//   ],
//   fluid: [
//     'fluid_img1.png',
//     'fluid_img2.png',
//     'velocity_contour.png',
//     'fluid_img3.png',
//     'fluid_img4.png',
//     'fluid_img5.png',
//     'fluid_img6.png',
//     'luid_img7.png',
//     'luid_img8.png',
//     'fluid_img9.png',
//   ],
//   thermal: ['img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png'],
// });

const taskTypeList = ref([
  {
    name: '静力学',
    value: 'statics',
  },
  {
    name: '动力学',
    value: 'dynamics',
  },
  {
    name: '流体 ',
    value: 'fluid',
  },
  {
    name: '热分析',
    value: 'thermal',
  },
]);

const handleCloseFun = () => {
  emits('close');
};

const createSuccessFun = async () => {
  const performanceList = taskPerformanceRef.value.baseTableRef.tableRef.getCheckboxRecords();

  const chcekImgs = resultImgList.value.filter((item: any) => {
    return item.checkImg;
  });
  const imageFileIdList = chcekImgs.map((item: any) => {
    return item.fileId;
  });
  const taskInfo = cloneDeep(props.parentNodeInfo);
  for (const key in taskInfo) {
    if (key.includes('tag')) {
      delete taskInfo[key];
    }
  }
  delete taskInfo.children;
  const fileName = reportFormData.reportName + '.docx';
  await generateReportApi({
    performanceList,
    imageFileIdList,
    projecInfoReq: reportFormData,
    fileName,
  });
};

const resultImgList = ref<any>([]);
const queryDirDataFun = async () => {
  const res: any = await listSimulationKeyResultApi({
    keyResultType: '1',
    runId: props.currentNodeInfo?.uuid,
    current: 1,
    size: 999,
  });
  if (res && res.code === 200) {
    resultImgList.value = res.data.data.map((item: any) => {
      return {
        ...item,
        url: `${env.VITE_API_IMAGE_PREVIEW_URL}/data/previewImage?fileId=${item.fileId}`,
      };
    });

    showIMgFileList();
  }
};

const taskTypeChangeFun = () => {
  showIMgFileList();
};

const showIMgFileList = () => {
  for (let i = 0; i < resultImgList.value.length; i++) {
    resultImgList.value[i].checkImg = false;
    resultImgList.value[i].show = true;
  }
};

watch(
  () => props.currentNodeInfo,
  (newVal) => {
    if (newVal) {
      const runInfo = cloneDeep(newVal);
      const projectInfo = JSON.parse(
        localStorage.getItem('CURRENT_FILTER_RUN_TASK_TREE_PARAM') as string
      );
      reportFormData.reportName = '算例报告_' + dayjs().format('YYYY_MM_DD_HH_mm');
      reportFormData.applicants = getUserData().nickname;
      reportFormData.date = dayjs().format('YYYY-MM-DD HH:mm:ss');
      reportFormData.loadcaseName = runInfo.parentName;
      reportFormData.projectNum = projectInfo?.projectCode;
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

watch(
  () => props.workspaceInfo,
  (newVal) => {
    if (newVal) {
      const nodeInfo = newVal;
      reportFormData.workspaceNum = nodeInfo.nodeCode;
      reportFormData.workspace = nodeInfo.nodeName;
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

onMounted(async () => {
  await queryDirDataFun();
});
</script>

<style lang="scss" scoped>
.report-page {
  width: 100%;
  height: 100%;
  // min-height: 500px;

  .form-box {
    width: 100%;
    // height: 50px;
  }

  .content-box {
    .img-content {
      width: 100%;
      min-height: 200px;
      padding: 5px;
      display: flex;
      flex-wrap: wrap;

      .img-item {
        width: 150px;
        height: 150px;
        margin-right: 20px;
        margin-bottom: 20px;
        position: relative;
        box-sizing: content-box;
        border: 1px dashed var(--el-color-primary);

        .check-style {
          position: absolute;
          top: 0px;
          left: 5px;
        }

        .img-style {
          width: 150px;
          height: 150px;
        }
      }
    }
  }

  .ml5 {
    margin-left: 5px;
  }

  .w180 {
    width: 230px !important;
  }
  .w185 {
    width: 235px !important;
  }
}
</style>
