<template>
  <Dialog
    v-model="visible"
    diaTitle="上传交付物"
    :width="'70%'"
    :height="'70%'"
    :zIndex="101"
    @close="handleCloseFun"
    show-footer
  >
    <div class="page-content">
      <div class="table-box">
        <BaseTable
          tableName="TASK_DELIVERABLE"
          ref="baseTableRef"
          showCheckbox
          :actionList="actionList"
          :hide-pagination="true"
        >
          <template #leftOptions>
            <el-form :model="templateFormData" inline>
              <el-form-item label="审核模版：">
                <el-select v-model="templateFormData.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>
                <el-button type="primary" @click="uploadFileFun('RUN_RESULT_IMAGE_TABLE')"
                  >上传图片文件</el-button
                >
                <el-button type="primary" @click="uploadFileFun('RUN_RESULT_CANVAS_TABLE')"
                  >上传曲线文件</el-button
                >
                <el-button type="primary" @click="uploadFileFun('RUN_RESULT_REPORT_TABLE')"
                  >上传报告文件</el-button
                >
              </el-form-item>
            </el-form>
          </template>
          <template>
            <el-tag type="info">待审批</el-tag>
          </template>
        </BaseTable>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseFun">取消</el-button>
        <el-button type="primary" @click="createSuccessFun">提交评审</el-button>
      </span>
    </template>
  </Dialog>

  <el-drawer
    v-model="uploadFileVisible"
    :title="`文件上传`"
    :size="500"
    :close-on-click-modal="false"
    @close="handleCloseFun"
  >
    <TableForm ref="tableFormRef" :tableName="tableName" />
    <template #footer>
      <div>
        <el-button @click="uploadFileVisible = false">关闭</el-button>
        <el-button type="primary" @click="submitFun">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import { systemApproveQueryApproveFlowTempalteApi } from '@/api/system/systemApprove';
import BaseTable from '@/components/common/table/baseTable.vue';
import TableForm from '@/components/common/table/tableForm.vue';
import { batchAddSimulationKeyResultApi } from '@/api/project/run';
import emitter from '@/utils/eventBus';
import { ElMessage } from 'element-plus';

const props = defineProps({
  curentTaskInfo: {
    type: Object,
    default: () => {},
  },
});
const emits = defineEmits(['close', 'update']);

const visible = ref(true);
const uploadFileVisible = ref(false);
const tableFormRef = ref();
const baseTableRef = ref();
const tableName = ref('RUN_RESULT_IMAGE_TABLE');
const templateList = ref<any>([]);
const keyResultType = ref('1');
const tableData = ref<any>([]);

const templateFormData = reactive<any>({
  templateId: '',
});

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

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

  if (!tableData.value.length) {
    ElMessage.warning('未选择交付物文件上传，无法发起流程！');
    return;
  }

  const templateName = templateList.value.find((item: any) => {
    return item.templateId === templateFormData.templateId;
  })?.templateName;
  const param: any = {
    keyResultList: [],
    uploadTaskId: new Date().getTime(),
    taskId: props.curentTaskInfo?.uuid,
    templateId: templateFormData.templateId,
    templateName,
  };

  for (let i = 0; i < tableData.value.length; i++) {
    param.keyResultList.push({
      fileName: tableData.value[i].fileName,
      fileSize: tableData.value[i].fileSize,
      fileType: tableData.value[i].fileType,
      keyResultType: tableData.value[i].keyResultType,
      name: tableData.value[i].name,
      quantityType: 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: tableData.value[i].xQuantityType,
      xUnits: tableData.value[i].xUnits,
      yQuantityType: 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].uploadFile[0].raw,
        data: {
          // 接口返回的文件目录信息，包括配置信息
          ...item,
          isApprove: 1, // 0否 1是
          taskType: 4, // 4交付物
        },
      });
    });
  }

  if (res.code === 200) {
    emits('update');
  }
};

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

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

const uploadFileFun = (flag: string) => {
  tableName.value = flag;

  if (tableName.value === 'RUN_RESULT_IMAGE_TABLE') {
    keyResultType.value = '1';
  }
  if (tableName.value === 'RUN_RESULT_CANVAS_TABLE') {
    keyResultType.value = '2';
  }
  if (tableName.value === 'RUN_RESULT_REPORT_TABLE') {
    keyResultType.value = '3';
  }

  uploadFileVisible.value = true;
  nextTick(() => {
    tableFormRef.value.resetFun();
  });
};

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

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

const submitFun = async () => {
  const valid = await tableFormRef.value.validateFun();
  if (valid) {
    const fromData = tableFormRef.value.getFormDataFun();
    const file = fromData.uploadFile[0].raw;
    const name = file.name;
    const paramData: any = {};
    paramData.originalName = name;
    paramData.fileName = name;
    paramData.name = name;
    paramData.fileSize = file.size;
    paramData.uploadId = new Date().getTime();
    for (const key in fromData) {
      paramData[key] = fromData[key];
    }
    paramData.keyResultType = keyResultType.value;
    paramData.fileType = '8';
    tableData.value.push(paramData);
    baseTableRef.value.setDataFun(tableData.value);
    uploadFileVisible.value = false;
  }
};

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

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

  .mw200 {
    width: 200px;
  }
}
</style>
