<!-- 入库信息审核-详情页 -->
<template>
  <basic-container>
    <el-row style="min-height: 300px">
      <el-table :data="tableData" style="width: 100%" stripe border>
        <el-table-column prop="inboundType" label="入库类型" header-align="center" align="center">
          <template #default="scope">
            {{ scope.row.inboundType ? showCh(scope.row.inboundType, indound_type) : scope.row.inboundType }}
          </template>
        </el-table-column>
        <el-table-column prop="materialGroup" label="物资大类" header-align="center" align="center" />
        <el-table-column prop="materialType" label="物资类别" header-align="center" align="center" />
        <el-table-column prop="materialName" label="物资名称" header-align="center" align="center" />
        <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="inboundTime" label="入库日期" header-align="center" 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-row v-if="1">
        <el-table :data="auditData" style="width: 100%" stripe border>
          <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
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="getFileInfo"
                :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>
      </div>
    </div>
  </basic-container>
</template>

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

const { indound_type, is_available } = useDict("indound_type", "is_available");
const router = useRouter();
const route = useRoute();
const data = reactive({
  tableData: [],
  auditData: [],
  isShow: false,
  fileUrl: "/admin/sysFile/uploadVoucher",
  myHeader: { Authorization: "Bearer " + sessionStorage.getItem("access_token") }
});
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 (route.query.type == "show") {
    isShow.value = true;
  } else {
    isShow.value = false;
  }
  getInAuditDetail(route.query.id).then((res: any) => {
    if (res.code === 0) {
      tableData.value = res.data.inboundMaterial;
      auditData.value = res.data.inboundStatus;
    }
  });
};
// 根据码回显中文
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", inboundId: route.query.id };
      audit(data).then((res: any) => {
        if (res.code === 0) {
          ElMessage({
            type: "success",
            message: "提交成功"
          });
          router.push("/InformationAudit/enterWarehouseAudit");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消提交"
      });
    });
};
// 退回
const handleReturn = () => {
  ElMessageBox.confirm("是否确认退回?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let data = { ...formData, audi: "1", inboundId: route.query.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/enterWarehouseAudit");
  // closeTagAndOpenLastTag()
};

// 附件相关
const getFileInfo = (res: any, file: any, fileList: any) => {
  if (fileList.length > 0) {
    formData.filePart = fileList[0].response
      ? fileList[0].response.data.bucketName + "/" + 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 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 " + sessionStorage.getItem("access_token"));
  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>
