<!-- 应急物资分类表 -->
<template>
  <basic-container class="container">
    <el-form :inline="true" :model="QueryForm" :rules="formRules" ref="queryForms" label-suffix=":">
      <el-form-item label="物资名称" prop="materialTree">
        <el-cascader
          :options="wzOptions"
          filterable
          :disabled="props.type == 'look'"
          v-model="QueryForm.materialTree"
          style="width: 350px"
          @change="handleChange"
          :props="{ value: 'id', label: 'name' }"
          placeholder="请选择物资名称"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="入库日期" prop="entryDate">
        <el-select
          v-model="QueryForm.entryDate"
          :disabled="props.type == 'look'"
          @change="handleChangeDate"
          style="width: 200px"
        >
          <el-option
            v-for="item in TimeOptions"
            :key="item.deptId"
            placeholder="请选择入库日期"
            :label="item.inboundTime"
            :value="item.inboundTime"
            clearable
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单价(元)" prop="unitPrice">
        <el-select
          v-model="QueryForm.unitPrice"
          :disabled="props.type == 'look'"
          @change="handleChangePrice"
          style="width: 200px"
        >
          <el-option
            v-for="item in dj_Options"
            :key="item.deptId"
            placeholder="请选择单价"
            :label="item.unitPrice"
            :value="item.unitPrice"
            clearable
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-form label-width="0" :rules="formRules1" :model="formData" ref="queryForms1">
      <el-table :data="formData.tableData" border>
        <el-table-column prop="inboundTime" label="维护保养时间" align="center">
          <template #default="scope">
            <el-form-item
              v-if="props.type != 'look'"
              :prop="'tableData.' + scope.$index + '.maintenanceTime'"
              :rules="formRules1.maintenanceTime"
            >
              <el-date-picker
                clearable
                size="small"
                style="width: 100%"
                v-model="scope.row.maintenanceTime"
                type="date"
                placeholder="请选择维护保养时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              >
              </el-date-picker>
            </el-form-item>
            <span v-else>{{ scope.row.maintenanceTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceUnit" label="维护保养单位" align="center">
          <template #default="scope">
            <el-form-item
              v-if="props.type != 'look'"
              :prop="'tableData.' + scope.$index + '.maintenanceUnit'"
              :rules="formRules1.maintenanceUnit"
            >
              <el-input
                v-model="scope.row.maintenanceUnit"
                size="small"
                placeholder="请输入维护保养单位"
                clearable
              ></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.maintenanceUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="maintenancePerson" label="维护保养人" align="center">
          <template #default="scope">
            <el-form-item
              v-if="props.type != 'look'"
              :prop="'tableData.' + scope.$index + '.maintenancePerson'"
              :rules="formRules1.maintenancePerson"
            >
              <el-input
                v-model="scope.row.maintenancePerson"
                size="small"
                placeholder="请输入维护保养人"
                :disabled="props.type == 'look'"
              ></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.maintenancePerson }}</span>
          </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"
                :on-preview="handlePreview"
                multiple
                :on-remove="handleRemove"
                :before-remove="(response:any, file:any, index:number) => beforeRemove(response, file, scope.$index)"
                :on-success="(response:any, file:any, index:number) => 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 v-else @click="handlePreviewDetail(scope.row.filePart)" style="cursor: pointer; color: #409eff">
              {{ scope.row.fileName }}
            </p>
          </template>
        </el-table-column>
        <el-table-column v-if="props.type != 'look'" label="操作" align="center" fixed="right" width="102">
          <template #default="scope">
            <el-button @click="deleteTableData(scope.$index)" type="danger" :icon="Delete" circle />
            <el-button @click="addTableData(scope.$index)" type="success" :icon="Plus" circle />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!---审核记录-->
    <el-table
      :data="materialMaintenanceStatuses"
      v-if="props.type === 'look'"
      style="width: 100%; margin-top: 30px"
      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="props.type == 'look' ? '附件' : '附件上传'" align="center">
        <template #default="scope">
          <p @click="handlePreviewDetail(scope.row.filePart)" style="cursor: pointer; color: #409eff">
            {{ scope.row.fileName }}
          </p>
        </template>
      </el-table-column>
    </el-table>
    <div class="operationbox">
      <el-button type="success" @click="saveSubmit('1')" v-if="props.type != 'look'">保存</el-button>
      <el-button type="primary" @click="saveSubmit('2')" v-if="props.type != 'look'">提交</el-button>
      <el-button @click="returnPage">返回</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, FormRules } from "element-plus";
import router from "@/router";
import { dictTree, sysFile } from "@/api/inAndOut/formationFilling/in";

import { getInOptions, addInData, lookInData, updateInData } 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"]);
const { maintenance_auditing_status } = useDict("maintenance_auditing_status");

const props = getQuery("/upkeep/ReportDetail");
let materialMaintenanceStatuses = ref([]);
const queryForms = ref();
const queryForms1 = ref();
const wzOptions = ref([]);
const TimeOptions: any = ref([{}]);
const dj_Options: any = ref([]);
const QueryForm = reactive({
  materialGroup: "",
  materialTree: [],
  inboundTime: "",
  entryDate: "",
  unitPrice: ""
});
const queryInfo = reactive({
  materialGroup: "",
  materialType: "",
  materialName: "",
  entryDate: "",
  materialUnit: "",
  unitPrice: "",
  materialTree: []
});

const formRules = reactive({
  materialTree: [{ required: true, message: "请选择物资名称", trigger: "change" }],
  unitPrice: [{ required: true, message: "请选择单价", trigger: "change" }],
  entryDate: [{ required: true, message: "请选择入库日期", trigger: "change" }]
});
const formRules1 = reactive({
  maintenanceUnit: [{ required: true, message: "请填写单位", trigger: "blur" }],
  maintenancePerson: [{ required: true, message: "请填写保养人", trigger: "blur" }],
  maintenanceTime: [{ required: true, message: "请选择维护保养日期", trigger: "change" }],
  fileName: [{ required: true, message: "请上传附件", trigger: "change" }]
});

const formData = reactive({
  tableData: [
    {
      maintenanceTime: "",
      maintenancePerson: "",
      maintenanceUnit: "",
      filePart: "",
      fileName: "",
      filePartList: [{ url: "", name: "" }]
    }
  ]
});
// 根据码回显中文
const showCh = (value, option) => {
  const filterItem = option.filter((item) => item.value == value);
  return filterItem.length ? filterItem[0].label : "-";
};
// 下拉数据
const getSelect = () => {
  dictTree().then((res: any) => {
    if (res.code === 0) {
      wzOptions.value = res.data;
    }
  });
};

//获取物资下拉数据
const getOption = (data: any) => {
  getInOptions(data).then((res: any) => {
    if (res.code === 0) {
      if (data.entryDate) {
        dj_Options.value = res.data;
      } else {
        TimeOptions.value = res.data;
      }
    }
  });
};
const handleChange = (value: string) => {
  let wz_name = JSON.parse(JSON.stringify(value));
  console.log(wz_name, "wz_name");
  if (wz_name && wz_name.length == 4) {
    queryInfo.materialGroup = wz_name[0];
    queryInfo.materialType = wz_name[1];
    queryInfo.materialName = wz_name[2];
    queryInfo.materialUnit = wz_name[3];
    queryInfo.materialTree = wz_name;
    QueryForm.entryDate = "";
    queryInfo.entryDate = "";
    queryInfo.unitPrice = "";
    QueryForm.unitPrice = "";
    getOption(queryInfo);
  } else {
    ElMessage({
      message: "物资名称选择有误！",
      type: "warning"
    });
  }
};
const handleChangeDate = (value: string) => {
  queryInfo.entryDate = value;
  queryInfo.unitPrice = "";
  QueryForm.unitPrice = "";
  getOption(queryInfo);
};
const handleChangePrice = (value: string) => {
  queryInfo.unitPrice = value;
  QueryForm.unitPrice = value;
};

// 计算
// const handleChangeNum = (value: string) => {
//   if (value) {
//     let num = decimalMul(value, QueryForm.unitPrice);
//     formData.tableData[0].maintenanceUnit = num;
//   }
// };

// 新增一行
const addTableData = (rowIndex: number) => {
  const newRow = {};
  formData.tableData.splice(rowIndex + 1, 0, newRow);
};
// 删除
const deleteTableData = (rowIndex: number) => {
  if (formData.tableData.length > 1) {
    formData.tableData.splice(rowIndex, 1);
  } else {
    ElMessage({
      message: "最后一条不可删除！",
      type: "warning"
    });
  }
};
// 详情获取数据
const lookData = () => {
  lookInData(props.id).then((res: any) => {
    if (res.code === 0) {
      let getData = res.data.materialMaintenanceDetails;
      formData.tableData = getData.map((item: any) => ({
        ...item,
        filePartList: item.filePart ? [{ name: item.fileName, filePart: item.filePart }] : []
      }));
      QueryForm.materialGroup = res.data.materialGroup;
      QueryForm.materialType = res.data.materialType;
      QueryForm.materialName = res.data.materialName;
      QueryForm.materialUnit = res.data.materialUnit;
      QueryForm.unitPrice = res.data.unitPrice;
      QueryForm.entryDate = res.data.entryDate;
      QueryForm.materialTree = res.data.materialTree;
      queryInfo.materialGroup = res.data.materialGroup;
      queryInfo.materialType = res.data.materialType;
      queryInfo.materialName = res.data.materialName;
      queryInfo.entryDate = res.data.entryDate;
      queryInfo.materialUnit = res.data.materialUnit;
      queryInfo.unitPrice = res.data.unitPrice;
      queryInfo.materialTree = res.data.materialTree;
      materialMaintenanceStatuses.value = res.data.materialMaintenanceStatuses;
      console.log(materialMaintenanceStatuses, "materialMaintenanceStatuses");
    }
  });
};
/** 保存、提交 */
const saveSubmit = (status: any) => {
  queryForms.value.validate((valid: any) => {
    queryForms1.value.validate((valid1: any) => {
      if (valid && valid1) {
        let postData = {
          ...queryInfo,
          status,
          id: props.id,
          materialMaintenanceDetails: formData.tableData
        };
        if (props.id) {
          updateInData(postData).then((res: any) => {
            if (res.code === 0) {
              returnPage();
              ElMessage({
                message: "修改成功！",
                type: "success"
              });
            }
          });
        } else {
          addInData(postData).then((res: any) => {
            if (res.code === 0) {
              returnPage();
              ElMessage({
                message: status === "1" ? "新增成功！" : "提交成功！",
                type: "success"
              });
            }
          });
        }
      } else {
        console.log("error submit!");
      }
    });
  });
};
/** 返回 */
const returnPage = () => {
  store.commit("DEL_TAG", store.getters.tag);
  router.push({
    path: "/upkeep/report"
  });
};

//附件部分
const fileUrl = "/admin/sysFile/uploadVoucher";
let paramsData = reactive({
  bucket: "bound"
});
const myHeader = { Authorization: "Bearer " + access_token.value };
// 附件相关
const getFileInfo = (res: any, file: any, index: number) => {
  formData.tableData[index].filePart = res.data.fileName;
  formData.tableData[index].fileName = file.name;
  formData.tableData[index].filePartList = [{ url: res.data.fileName, name: file.name }];
};
const handleRemove = (file: any, uploadFiles: any) => {
  console.log(file, uploadFiles);
};
const handlePreview = (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 handlePreviewDetail = (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 handleExceed = (files: any, uploadFiles: any) => {
  ElMessage.warning(`限制上传一个文件`);
};
const beforeRemove = (uploadFile: any, uploadFiles: any, index: number) => {
  formData.tableData[index].filePart = "";
  formData.tableData[index].fileName = "";
};
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 {
    formData.tableData = [{}];
  }
});
</script>

<style lang="scss" scoped>
.operationbox {
  text-align: center;
  margin-top: 30px;
}
>>> .whole_form .w-200 {
  width: 200px !important;
}
</style>
