<!-- 应急物资分类表 -->
<template>
  <basic-container class="container">
    <el-table :data="tableData" border>
      <el-table-column prop="warehouse" label="库点简称" align="center" />
      <el-table-column prop="materialGroupVo" label="物资大类" align="center" />
      <el-table-column prop="materialTypeVo" label="物资类别" align="center" />
      <el-table-column prop="materialNameVo" label="物资名称" align="center" />
      <el-table-column prop="entryDate" label="入库日期" align="center" />
      <el-table-column prop="unitPrice" label="单价(元)" align="center" />
      <el-table-column prop="maintenanceUnit" label="维护保养单位" align="center" width="200" />
      <el-table-column prop="maintenancePerson" label="维护保养人" align="center" width="114" />
      <el-table-column prop="maintenanceTime" label="维护保养时间" align="center" width="140" />
      <el-table-column prop="fileName" label="附件上传" align="center" width="114">
        <template #default="scope">
          <!-- <el-form-item v-if="props.type != 'look'" :prop="'materialMaintenanceStatuses.' + scope.$index + '.fileName'">
            <el-upload
              :disabled="props.type == 'look'"
              v-model:file-list="scope.row.filePartList"
              class="upload-demo"
              style="width: 100%"
              :action="fileUrl"
              :data="paramsData"
              :headers="myHeader"
              multiple
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="(response, file, index) => getFileInfo(response, file, scope.$index)"
              :on-error="errorUpload"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-button v-if="props.type != 'look'" size="small" type="primary">选择文件</el-button>
            </el-upload>
          </el-form-item> -->
          <p @click="handlePreview(scope.row.filePart)" style="cursor: pointer; color: #409eff">
            {{ scope.row.fileName }}
          </p>
        </template>
      </el-table-column>
    </el-table>
    <!---审核记录-->
    <el-table
      :data="materialMaintenanceStatuses"
      v-if="props.type === 'look'"
      style="width: 100%; margin-top: 50px"
      stripe
      border
    >
      <el-table-column prop="warehouse" label="审核部门" align="center" />
      <el-table-column prop="opinion" label="审核意见" align="center" />
      <el-table-column prop="auditingTime" label="审核时间" align="center" />
      <el-table-column prop="status" label="审核状态" align="center">
        <template #default="scope">
          {{ scope.row.status ? showCh(scope.row.status, maintenance_auditing_status) : scope.row.status }}
        </template>
      </el-table-column>
      <el-table-column prop="fileName" label="附件" align="center">
        <template #default="scope">
          <!-- <el-form-item v-if="props.type != 'look'" :prop="'materialMaintenanceStatuses.' + scope.$index + '.fileName'">
            <el-upload
              :disabled="props.type == 'look'"
              v-model:file-list="scope.row.filePartList"
              class="upload-demo"
              style="width: 100%"
              :action="fileUrl"
              :data="paramsData"
              :headers="myHeader"
              multiple
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="(response, file, index) => getFileInfo(response, file, scope.$index)"
              :on-error="errorUpload"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-button v-if="props.type != 'look'" size="small" type="primary">选择文件</el-button>
            </el-upload>
          </el-form-item> -->
          <p @click="handlePreview(scope.row.filePart)" style="cursor: pointer; color: #409eff">
            {{ scope.row.fileName }}
          </p>
        </template>
      </el-table-column>
    </el-table>
    <el-row v-else>
      <el-col :span="24" style="margin-top: 30px">
        <el-form :model="formData" ref="queryForms" :rules="formRules">
          <el-form-item label="审核意见：" prop="opinion">
            <el-input
              type="textarea"
              required
              :rows="4"
              style="width: 100%"
              placeholder="请输入审核意见"
              v-model="formData.opinion"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="附件上传：">
            <el-upload
              :disabled="props.type == 'look'"
              v-model:file-list="formData.file"
              class="upload-demo"
              style="width: 100%"
              :action="fileUrl"
              :data="paramsData"
              :headers="myHeader"
              multiple
              :on-preview="handlePreview1"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="(response, file) => getFileInfo(response, file)"
              :on-error="errorUpload"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-button v-if="props.type != 'look'" size="small" type="primary">选择文件</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <div class="operationbox">
      <el-button type="success" @click="saveSubmit('0')" v-if="props.type != 'look'">通过</el-button>
      <el-button type="danger" @click="saveSubmit('1')" v-if="props.type != 'look'">驳回</el-button>
      <el-button @click="returnPage" v-if="props.type === 'look'">返回</el-button>
    </div>
  </basic-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Delete, Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
import router from "@/router";
import { lookInData, Auditing } from "@/api/upkeep/in";
import { useDict } from "@/hooks/dict";
// import { closeTagAndOpenLastTag } from '@/router/Routermethods';
import store from "@/store";
import { getQuery } from "@/hooks/detailQuery/index";
import { useGetters } from "@/hooks/storeHooks";
const { access_token } = useGetters(["access_token"]);
import { decimalMul, decimalDev } from "@/global/decimalCompute";
import { dictTree, sysFile } from "@/api/inAndOut/formationFilling/in";

const { maintenance_auditing_status } = useDict("maintenance_auditing_status");

// const props = defineProps(['id','type'])
const props = getQuery("/upkeep/AuditingDetail");
// 价值计算带万
const wanJson = ["118", "122", "124", "132", "182", "184"];
let materialMaintenanceStatuses = ref([]);
const tableData: any = ref();
const queryForms = ref();
const formData = reactive({
  opinion: "",
  filePart: "",
  fileName: "",
  file: [],
  filePartList: [{ url: "", name: "" }]
});
const formRules = reactive({
  // opinion: [
  //   {
  //     required: true,
  //     message: "请填写审核意见",
  //     trigger: "blur"
  //   }
  // ]
});
// 根据码回显中文
const showCh = (value, option) => {
  const filterItem = option.filter((item) => item.value == value);
  return filterItem.length ? filterItem[0].label : "-";
};
// 详情获取数据
const lookData = () => {
  lookInData(props.id).then((res: any) => {
    if (res.code === 0) {
      let getData = res.data.materialMaintenanceDetails;
      tableData.value = getData.map((item: any) => ({
        ...item,
        filePartList: item.filePart ? [{ name: item.fileName, filePart: item.filePart }] : [],
        warehouse: res.data.warehouse,
        materialGroupVo: res.data.materialGroupVo,
        materialTypeVo: res.data.materialTypeVo,
        materialNameVo: res.data.materialNameVo,
        entryDate: res.data.entryDate,
        unitPrice: res.data.unitPrice
      }));
      materialMaintenanceStatuses.value = res.data.materialMaintenanceStatuses.map((item: any) => ({
        ...item,
        filePartList: [{ url: item.filePart, name: item.fileName }]
      }));
    }
  });
};
/** 保存、提交 */
const saveSubmit = (status: any) => {
  queryForms.value.validate((valid: any) => {
    if (valid) {
      let data = {
        maintenanceId: props.id,
        opinion: formData.opinion,
        audi: status,
        filePart: formData.filePart,
        fileName: formData.fileName
      };
      Auditing(data).then((res: any) => {
        if (res.code === 0) {
          if (status === "0") {
            ElMessage({
              message: "审核通过！",
              type: "success"
            });
          } else {
            ElMessage({
              message: "驳回成功！",
              type: "success"
            });
          }
          returnPage();
        } else {
          ElMessage({
            message: "审核失败！",
            type: "error"
          });
        }
      });
    } else {
      ElMessage({
        message: "请填写必填项！",
        type: "warning"
      });
    }
  });
};
/** 返回 */
const returnPage = () => {
  router.push({
    path: "/upkeep/Auditing"
  });
};

//附件部分
const fileUrl = "/admin/sysFile/uploadVoucher";
let paramsData = reactive({
  bucket: "bound"
});
const myHeader = { Authorization: "Bearer " + access_token.value };
// 附件相关
const getFileInfo = (res: any, file: any) => {
  formData.filePart = res.data.fileName;
  formData.fileName = file.name;
};
const handleRemove = (file: any, uploadFiles: any) => {
  console.log(file, uploadFiles);
};
const handlePreview = (url: string) => {
  sysFile(url).then((res: any) => {
    const blob = new Blob([res], { type: "application/pdf;charset=UTF-8" });
    const bFile = URL.createObjectURL(blob);
    window.open(bFile);
  });
};

const handlePreview1 = (file: any) => {
  if (file.url) {
    sysFile(file.url).then((res: any) => {
      const blob = new Blob([res], { type: "application/pdf;charset=UTF-8" });
      const bFile = URL.createObjectURL(blob);
      window.open(bFile);
    });
  }
};

const handleExceed = (files: any, uploadFiles: any) => {
  ElMessage.warning(`限制上传一个文件`);
};
const beforeRemove = (uploadFile: any, uploadFiles: any) => {
  // return ElMessageBox.confirm(`确定移除 ${uploadFile.name} ?`).then(
  //   () => true,
  //   () => false
  // );
};
const errorUpload = (err: any, file: any, fileList: any) => {
  ElMessage.error("文件上传失败，UploadAjaxError：" + JSON.parse(JSON.stringify(err)).status);
};
// 上传前对附件进行的操作
const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  // const typeList = ".pdf.jpg.png.gif.jpeg.PDF.JPG.PNG.GIF.JPEG";
  const typeList = ".pdf"; //限制为pdf格式
  const { name, type } = fileNameDispose(file.name);
  if (!typeList.includes(type)) {
    ElMessage.error("仅支持pdf类型文件，请重新上传。");
    return false;
  }
  if (name.length > 30) {
    ElMessage.error("文件名不可超30字，请重新命名后再上传。");
    return false;
  }
  const isLt20M = file.size / 1024 / 1024 < 100;
  if (!isLt20M) {
    ElMessage.error("文件大小不可超过 100MB。");
    return false;
  }
  return true;
};
// 获取上传附件的名字和类型
const fileNameDispose = (name: string) => {
  const arr = name.split(".");
  if (arr.length === 2) {
    return { name: arr[0], type: arr[1] };
  } else {
    const type = arr.splice(arr.length - 1, 1)[0];
    const name = arr.join(".");
    return { name, type };
  }
};
/** -----------------附件结束--------------- */
/** 初始化 **/
onMounted(() => {
  //getSelect();
  if (props.type) {
    lookData();
  } else {
    tableData = [{}];
  }
});
</script>

<style lang="scss" scoped>
.operationbox {
  text-align: center;
  margin-top: 30px;
}
</style>
