<template>
  <div class="task-performance-page">
    <BaseTable
      tableName="TASK_DELIVERABLE"
      ref="baseTableRef"
      :api="queryKeyResultAndTaskInfoApi"
      showCheckbox
      :params="{
        taskId: taskId,
        fileType: 8,
      }"
      :full-height="true"
      :actionList="actionList"
    >
      <template #leftOptions v-if="taskInfo.status != 3">
        <!-- <el-button @click="addApproveFun">发起评审</el-button> -->
        <el-button type="primary" @click="uploadDeliverFileFun('img')">上传图片</el-button>
        <el-button type="primary" @click="uploadDeliverFileFun('canvas')">上传曲线</el-button>
        <el-button type="primary" @click="uploadDeliverFileFun('report')">上传报告</el-button>
        <div v-if="showFilter">
          <el-select v-model="currentId" class="select-style">
            <el-option
              v-for="item in taskRunList"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </div>
      </template>

      <template #type="{ row }">
        <span>{{ getfileType(row) }}</span>
      </template>
      <template #fileSize="{ row }">
        <span>{{ formatFileSize(row.fileSize) }}</span>
      </template>
    </BaseTable>

    <FilePreview v-model="previewVisible" :fileId="currentRow?.fileId" />
  </div>

  <Teleport to="body">
    <!-- <uploadDeliverableFilePage v-if="uploadFileVisible" :curentTaskInfo="taskInfo" @close="uploadFileVisible = false" @update="updateTableDataFun"></uploadDeliverableFilePage> -->

    <Dialog
      v-model="uploadFileVisible"
      diaTitle="上传交付物"
      :width="'70%'"
      :height="'70%'"
      :zIndex="101"
      @close="closeFun"
      show-footer
    >
      <BaseTable
        v-if="uploadFileVisible"
        :tableName="tableName"
        ref="baseUploadTableRef"
        :actionList="uploadActionList"
        :hidePagination="true"
      >
        <template #leftOptions>
          <el-upload
            :show-file-list="false"
            :accept="accept"
            multiple
            :before-upload="beforeUploadFun"
          >
            <el-button>上传文件</el-button>
          </el-upload>
        </template>

        <template #quantityType="{ row }">
          <el-select
            v-model="row.quantityType"
            filterable
            @change="getQuantityUnitFun(row, 'quantityType', 'unitsList')"
          >
            <el-option
              v-for="item in quantityTypeList"
              :key="item.id"
              :label="item.label"
              :value="item.name"
            ></el-option>
          </el-select>
        </template>
        <template #units="{ row }">
          <el-select v-model="row.units" filterable>
            <el-option
              v-for="item in row.unitsList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </template>
        <template #max="{ row }">
          <el-input v-model="row.max"></el-input>
        </template>
        <template #min="{ row }">
          <el-input v-model="row.min"></el-input>
        </template>
        <template #description="{ row }">
          <el-input v-model="row.description"></el-input>
        </template>
        <template #xQuantityType="{ row }">
          <el-select
            v-model="row.xQuantityType"
            filterable
            @change="getQuantityUnitFun(row, 'xQuantityType', 'xUnitsList')"
          >
            <el-option
              v-for="item in quantityTypeList"
              :key="item.id"
              :label="item.label"
              :value="item.name"
            ></el-option>
          </el-select>
        </template>
        <template #xquantityType="{ row }">
          <el-select
            v-model="row.xquantityType"
            filterable
            @change="getQuantityUnitFun(row, 'xquantityType', 'xunitsList')"
          >
            <el-option
              v-for="item in quantityTypeList"
              :key="item.id"
              :label="item.label"
              :value="item.name"
            ></el-option>
          </el-select>
        </template>
        <template #xUnits="{ row }">
          <el-select v-model="row.xUnits" filterable>
            <el-option
              v-for="item in row.xUnitsList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </template>
        <template #xunits="{ row }">
          <el-select v-model="row.xunits" filterable>
            <el-option
              v-for="item in row.xunitsList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </template>
        <template #yQuantityType="{ row }">
          <el-select
            v-model="row.yQuantityType"
            filterable
            @change="getQuantityUnitFun(row, 'yQuantityType', 'yUnitsList')"
          >
            <el-option
              v-for="item in quantityTypeList"
              :key="item.id"
              :label="item.label"
              :value="item.name"
            ></el-option>
          </el-select>
        </template>
        <template #yquantityType="{ row }">
          <el-select
            v-model="row.yquantityType"
            filterable
            @change="getQuantityUnitFun(row, 'yquantityType', 'yunitsList')"
          >
            <el-option
              v-for="item in quantityTypeList"
              :key="item.id"
              :label="item.label"
              :value="item.name"
            ></el-option>
          </el-select>
        </template>
        <template #yUnits="{ row }">
          <el-select v-model="row.yUnits" filterable>
            <el-option
              v-for="item in row.yUnitsList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </template>
        <template #yunits="{ row }">
          <el-select v-model="row.yunits" filterable>
            <el-option
              v-for="item in row.yunitsList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </template>
      </BaseTable>

      <template #footer>
        <div>
          <el-button @click="closeFun">关闭</el-button>
          <el-button type="primary" @click="submitFun">确定</el-button>
        </div>
      </template>
    </Dialog>

    <Dialog
      v-model="approvaVisable"
      diaTitle="发起评审"
      :width="'400px'"
      :height="'30%'"
      :zIndex="101"
      @close="closApprovalFun"
      show-footer
    >
      <el-form :model="approvalFormData">
        <el-form-item label="评审模板：">
          <el-select v-model="approvalFormData.templateId" class="mw200">
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.templateName"
              :value="item.templateId"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="难度系数：">
          <el-select v-model="approvalFormData.difficult">
            <el-option
              v-for="item in difficultyTypeList"
              :key="item.dictName"
              :label="item.dictName"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div>
          <el-button @click="closApprovalFun">关闭</el-button>
          <el-button type="primary" @click="submitApprovalFun">确定</el-button>
        </div>
      </template>
    </Dialog>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, reactive } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import { formatFileSize } from '@/utils/file';
import FilePreview from '@/components/common/filePreview/index.vue';
import Dialog from '@/components/common/dialog/index.vue';
import emitter from '@/utils/eventBus';
import {
  batchAddSimulationKeyResultApi,
  deliverableApproveApi,
  listQuantitiesApi,
  listUnitsApi,
  queryKeyResultAndTaskInfoApi,
} from '@/api/project/run';
import { systemApproveQueryApproveFlowTempalteApi } from '@/api/system/systemApprove';
import { ElMessage } from 'element-plus';
import { downloadFileById } from '@/utils/file';
import { getDictionaryDataApi } from '@/api/system/systemData';
import { FILE_TYPE } from '@/utils/enum/file';

const props = defineProps({
  taskId: {
    type: Number,
    default: 100,
  },
  taskInfo: {
    type: Object,
    default: () => {},
  },
  showFilter: {
    type: Boolean,
    default: false,
  },
});

const accept = ref('');
const baseTableRef = ref();
const baseUploadTableRef = ref();
const currentId = ref<any>(props.taskId);
const uploadFileVisible = ref(false);
const approvaVisable = ref(false);
const tableName = ref('RUN_RESULT_IMAGE_TABLE');
const keyResultType = ref('1');
const taskRunList = ref<any>([]);
const getTaskRunInfoFun = () => {
  taskRunList.value = [
    {
      name: '当前任务',
      id: props.taskId,
    },
  ];
  currentId.value = taskRunList.value[0].id;
};

const getfileType = (data: any) => {
  const fileType = data.originalName?.split('.').pop();
  return fileType;
};
const currentRow = ref();
const previewVisible = ref(false);

const previewFileFun = (row: any) => {
  currentRow.value = row;
  previewVisible.value = true;
};

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

const actionList = ref([
  {
    title: '下载',
    type: 'primary',
    click: (row: any) => {
      downloadFileById(row.fileId);
    },
  },
  {
    title: '预览',
    type: 'primary',
    click: (row: any) => {
      previewFileFun(row);
    },
  },
]);

const uploadActionList = ref([
  {
    title: '删除',
    type: 'danger',
    click: (row: any) => {
      tableData.value = tableData.value.filter((item: any) => {
        return item.uploadId != row.uploadId;
      });

      baseUploadTableRef.value.setDataFun(tableData.value);
    },
  },
]);

const fileType = ref(FILE_TYPE.PNG_FILE);
const uploadDeliverFileFun = (flag: any) => {
  if (flag === 'img') {
    keyResultType.value = '1';
    tableName.value = 'RUN_RESULT_IMAGE_TABLE';
    accept.value = '.jpg,.jpeg,.png,.gif';
    fileType.value = FILE_TYPE.PNG_FILE;
  } else if (flag === 'canvas') {
    keyResultType.value = '2';
    tableName.value = 'RUN_RESULT_CANVAS_TABLE';
    accept.value = '.csv';
    fileType.value = FILE_TYPE.CANVAS_FILE;
  } else {
    tableName.value = 'RUN_RESULT_REPORT_TABLE';
    accept.value = '.ppt,.pptx,.doc,.docx,.pdf';
    fileType.value = FILE_TYPE.REPORT_FILE;

    keyResultType.value = '3';
  }

  uploadFileVisible.value = true;
};
const num = ref(1);
const beforeUploadFun = (file: any) => {
  num.value++;
  const { name, size } = file;
  const obj = {
    name: name,
    fileName: name,
    fileSize: size,
    size,
    file,
    id: new Date().getTime() + num.value,
    quantityType: '',
    units: '',
    max: '',
    min: '',
    description: '',
    xQuantityType: '',
    xquantityType: '',
    xUnits: '',
    xunits: '',
    yQuantityType: '',
    yquantityType: '',
    yUnits: '',
    yunits: '',
    fileType: fileType.value,
    keyResultType: keyResultType.value,
  };

  tableData.value.push(obj);

  nextTick(() => {
    baseUploadTableRef.value.setDataFun(tableData.value);
  });
};

const submitFun = async () => {
  const param: any = {
    keyResultList: [],
    uploadTaskId: new Date().getTime(),
    taskId: props.taskInfo?.uuid,
    templateId: '',
    templateName: '',
    type: 0,
  };

  for (let i = 0; i < tableData.value.length; i++) {
    param.keyResultList.push({
      fileName: tableData.value[i].name,
      fileSize: tableData.value[i].fileSize,
      fileType: tableData.value[i].fileType,
      keyResultType: tableData.value[i].keyResultType,
      name: tableData.value[i].name,
      quantityType: getQuantityTypeNameFun(tableData.value[i].quantityType),
      units: tableData.value[i].units,
      max: tableData.value[i].max,
      min: tableData.value[i].min,
      description: tableData.value[i].description,
      xQuantityType: getQuantityTypeNameFun(tableData.value[i].xQuantityType),
      xUnits: tableData.value[i].xUnits,
      yQuantityType: getQuantityTypeNameFun(tableData.value[i].yQuantityType),
      yUnits: tableData.value[i].yUnits,
    });
  }

  const res: any = await batchAddSimulationKeyResultApi(param);
  if (res && res.code === 200) {
    res.data.forEach((item: any, index: any) => {
      emitter.emit('ADD_UPLOAD_FILE', {
        file: tableData.value[index].file,
        data: {
          // 接口返回的文件目录信息，包括配置信息
          ...item,
          isApprove: 0, // 0否 1是
          taskType: 4, // 4交付物
        },
      });
    });
  }

  if (res.code === 200) {
    uploadFileVisible.value = false;
    baseTableRef.value.resetFun();
  }
};

const closeFun = () => {
  tableData.value = [];
  uploadFileVisible.value = false;
};

//
const approvalFormData = reactive<any>({
  difficult: '1',
  templateId: '',
});

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

// 发起审批
// const addApproveFun = () => {
//   approvaVisable.value = true;
// };

const closApprovalFun = () => {
  approvaVisable.value = false;
};

const systemApproveQueryApproveFlowTempalteFun = async () => {
  const res: any = await systemApproveQueryApproveFlowTempalteApi({});

  if (res && res.code === 200) {
    templateList.value = res.data;
  } else {
    templateList.value = [];
  }
};

const submitApprovalFun = async () => {
  if (!approvalFormData.templateId) {
    ElMessage.warning('未选择流程模板，无法发起流程！');
    return;
  }

  if (!approvalFormData.difficult) {
    ElMessage.warning('未选择难度系数，无法发起流程！');
    return;
  }

  const templateName = templateList.value.find((item: any) => {
    return item.templateId === approvalFormData.templateId;
  })?.templateName;

  const res: any = await deliverableApproveApi({
    taskId: props.taskInfo.uuid,
    difficult: approvalFormData.difficult,
    templateId: approvalFormData.templateId,
    templateName,
  });

  if (res && res.code === 200) {
    ElMessage.success('已发起评审！');
  }

  approvaVisable.value = false;
};

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

const getQuantityTypeFun = async () => {
  const res: any = await listQuantitiesApi();
  if (res && res.code === 200) {
    quantityTypeList.value = res.data;
  }
};

const getQuantityUnitFun = async (row: any, name: any, flag: any) => {
  if (name) {
    const res: any = await listUnitsApi({ quantityType: row[name] });
    if (res && res.code === 200) {
      row[flag] = res.data;
    } else {
      row[flag] = [];
    }
  } else {
    row[flag] = [];
  }
};

const getQuantityTypeNameFun = (type: any) => {
  const name =
    quantityTypeList.value.find((item: any) => {
      return item.name === type;
    })?.label || '';

  return name;
};
const difficultyTypeList = ref<any>([]);

const getDifficultyTypeFun = async () => {
  const res: any = await getDictionaryDataApi({ dictClass: 'DIFFICULTY_COEFFICIENT' });
  if (res && res.code === 200) {
    difficultyTypeList.value = res.data;
  } else {
    difficultyTypeList.value = [];
  }
};

onMounted(async () => {
  await systemApproveQueryApproveFlowTempalteFun();
  await getQuantityTypeFun();
  await getDifficultyTypeFun();
  getTaskRunInfoFun();
});
</script>

<style lang="scss" scoped>
.task-performance-page {
  width: 100%;
  height: 100%;

  .select-style {
    width: 120px;
  }
}
</style>
