<!-- 出库信息审核-详情页 -->
<template>
  <basic-container>
    <el-row style="min-height: 300px">
      <el-table :data="tableData" style="width: 100%" stripe border>
        <el-table-column prop="outboundType" label="出库类型" header-align="center" align="center">
          <template #default="scope">
            {{ scope.row.outboundType ? showCh(scope.row.outboundType, outdound_type) : scope.row.outboundType }}
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="物资名称" header-align="center" align="center" width="360">
          <template #default="scope">
            {{ scope.row.materialGroup + "/" + scope.row.materialType + "/" + scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" header-align="center" align="center" />
        <el-table-column prop="quantity" label="数量" header-align="center" align="center" />
        <el-table-column prop="outboundTime" label="出库日期" header-align="center" align="center" />
        <el-table-column prop="inboundTime" label="入库日期" align="center" />
        <el-table-column prop="unitPrice" label="单价（元）" header-align="center" align="center" />
        <el-table-column prop="totalPrice" label="价值（万元）" header-align="center" align="center" />
        <el-table-column prop="isAvailable" label="是否可用" header-align="center" align="center">
          <template #default="scope">
            {{ scope.row.isAvailable ? showCh(scope.row.isAvailable, is_available) : scope.row.isAvailable }}
          </template>
        </el-table-column>
        <el-table-column label="附件上传" header-align="center" align="center" width="160">
          <template #default="scope">
            <span class="fileName" @click="fileDownload(scope.row.filePart, scope.row.fileName)">{{
              scope.row.fileName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" header-align="center" align="center" />
      </el-table>
    </el-row>
    <div style="padding: 30px 40px 0">
      <el-row v-if="auditData && auditData.length > 0">
        <el-table :data="auditData" style="width: 100%" stripe border>
          <el-table-column prop="warehouse" label="审核部门" header-align="center" align="center" />
          <el-table-column prop="opinion" label="审核意见" header-align="center" align="center" />
          <el-table-column label="附件" header-align="center" align="center">
            <template #default="scope">
              <span class="fileName" @click="fileDownload(scope.row.filePart, scope.row.fileName)">{{
                scope.row.fileName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="auditingTime" label="审核时间" header-align="center" align="center" />
        </el-table>
      </el-row>
      <el-form :model="formData" v-if="!isShow" label-width="100px" class="whole_form">
        <el-row class="audit-form" style="margin-top: 50px">
          <el-col :span="24">
            <el-form-item label="审核意见：">
              <el-input
                type="textarea"
                rows="4"
                v-model="formData.opinion"
                placeholder="请输入"
                style="width: 100%"
              /> </el-form-item
          ></el-col>
          <el-col :span="24">
            <el-form-item label="附件上传：">
              <el-upload
                v-model:file-list="formData.fileList"
                class="upload-demo"
                style="width: 100%"
                :action="fileUrl"
                :data="paramsData"
                :headers="myHeader"
                multiple
                :before-upload="beforeUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="getFileInfo"
                :on-error="errorUpload"
                :limit="1"
                :on-exceed="handleExceed"
              >
                <el-button v-if="formData.fileList.length == 0" style="margin-top: 10px" type="primary"
                  >选择文件</el-button
                >
              </el-upload>
            </el-form-item></el-col
          >
        </el-row>
      </el-form>
      <div style="text-align: center; padding: 50px 0 20px">
        <!-- <button class="bottom-btn" v-if="!isShow" style="background-color: #676fe8" @click="handleAgree">通 过</button>
        <button class="bottom-btn" v-if="!isShow" style="background-color: #e13434" @click="handleReturn">退 回</button>
        <button class="bottom-btn" style="background-color: #89aac4" @click="handleBack">返 回</button> -->
        <el-button type="success" v-if="!isShow" @click="handleAgree" style="background-color: #676fe8; border: none"
          >通过</el-button
        >
        <el-button type="primary" v-if="!isShow" @click="handleReturn" style="background-color: #e13434; border: none"
          >退回</el-button
        >
        <el-button @click="handleBack">返回</el-button>
      </div>
    </div>
  </basic-container>
</template>

<script setup lang="ts">
import { reactive, toRefs, onMounted } from "vue";
import { getInAuditDetail, audit } from "@/api/inAndOut/outAudit/index";
import { getDictItemList } from "@/api/admin/index";
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { useDict } from "@/hooks/dict";
// import { closeTagAndOpenLastTag } from "@/router/Routermethods";
import store from "@/store";
import { useGetters } from "@/hooks/storeHooks";
import { getQuery } from "@/hooks/detailQuery/index";

const { access_token } = useGetters(["access_token"]);
const { outdound_type, is_available, province_ch } = useDict("outdound_type", "is_available", "province_ch");
const queryData = getQuery("outWarehouseAuditDetail");

const router = useRouter();
const route = useRoute();
const data = reactive({
  tableData: [],
  auditData: [],
  isShow: false,
  fileUrl: "/admin/sysFile/uploadVoucher",
  myHeader: { Authorization: "Bearer " + access_token.value }
});
let page = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
});
let formData = reactive({
  opinion: "",
  filePart: "",
  fileName: "",
  fileList: []
});
let paramsData = reactive({
  bucket: "bound"
});

let { tableData, auditData, isShow, fileUrl, myHeader } = toRefs(data);

// 获取列表
const getList = () => {
  if (queryData.type == "show") {
    isShow.value = true;
  } else {
    isShow.value = false;
  }
  getInAuditDetail(queryData.id).then((res: any) => {
    if (res.code === 0) {
      tableData.value = res.data.outboundMaterial;
      auditData.value = res.data.outboundStatus;
    }
  });
};
// 根据码回显中文
const showCh = (value: any, option: any) => {
  const filterItem = option.filter((item: any) => item.value == value);
  return filterItem.length ? filterItem[0].label : "-";
};
// 通过
const handleAgree = () => {
  ElMessageBox.confirm("是否确认通过?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let data = { ...formData, audi: "0", outboundId: queryData.id };
      audit(data).then((res: any) => {
        if (res.code === 0) {
          ElMessage({
            type: "success",
            message: "提交成功"
          });
          router.push("/InformationAudit/outWarehouseAudit");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消提交"
      });
    });
};
// 退回
const handleReturn = () => {
  ElMessageBox.confirm("是否确认退回?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let data = { ...formData, audi: "1", outboundId: queryData.id };
      audit(data).then((res: any) => {
        if (res.code === 0) {
          ElMessage({
            type: "success",
            message: "提交成功"
          });
          router.push("/InformationAudit/outWarehouseAudit");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消提交"
      });
    });
};
// 返回
const handleBack = () => {
  store.commit("DEL_TAG", store.getters.tag);
  router.push("/InformationAudit/outWarehouseAudit");
  // closeTagAndOpenLastTag();
};

// 附件相关
const getFileInfo = (res: any, file: any, fileList: any) => {
  if (fileList.length > 0) {
    formData.filePart = fileList[0].response ? fileList[0].response.data.fileName : "";
    formData.fileName = fileList[0].name;
  }
};
const handleRemove = (file: any, uploadFiles: any) => {
  console.log(file, uploadFiles);
};
const handlePreview = (uploadFile: any) => {
  console.log(uploadFile);
};
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 };
  }
};
const fileDownload = (filePart: any, fileName: string) => {
  function createObjectURL(object: any) {
    return window.URL ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
  }
  var xhr = new XMLHttpRequest();
  var formData = new FormData();
  xhr.open("get", "/admin/sysFile/" + filePart);
  xhr.setRequestHeader("Authorization", "Bearer " + access_token.value);
  xhr.responseType = "blob";
  xhr.onload = function (e) {
    if (this.status == 200) {
      var blob = this.response;
      console.log(this.response);
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        var a = document.createElement("a");
        var url = createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      }
    }
  };
  xhr.send(formData);
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.bottom-btn {
  width: 150px;
  height: 44px;
  line-height: 44px;
  color: #ffffff;
  border: none;
  border-radius: 15px;
}

.bottom-btn + .bottom-btn {
  margin-left: 20px;
}
.el-form-item {
  align-items: center;
}
.fileName {
  color: #4281e6;
  text-decoration: underline;
  cursor: pointer;
}
</style>
