<!-- 应急物资分类表 -->
<template>
  <basic-container class="container">
    <el-form label-width="0" :rules="rules" ref="ruleForms" :model="formData">
      <el-table :data="formData.tableData" border>
        <el-table-column prop="inboundType" label="入库类型" align="center" width="120">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.inboundType'" :rules="rules.inboundType">
              <el-select
                v-model="scope.row.inboundType"
                style="width: 100%"
                size="small"
                :disabled="props.type == 'look'"
                clearable
              >
                <el-option v-for="item in indound_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="materialTree" label="物资名称" align="center" width="360">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.materialTree'" :rules="rules.materialTree">
              <el-cascader
                :disabled="props.type == 'look'"
                clearable
                filterable
                size="small"
                v-model="scope.row.materialTree"
                placeholder="请选择物资"
                :options="wzOptions"
                :props="{ value: 'id', label: 'name' }"
                style="width: 100%"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="specs" label="规格" align="center">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.specs'">
              <el-input
                v-model="scope.row.specs"
                size="small"
                placeholder="请输入"
                :disabled="props.type == 'look'"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" align="center" width="120">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.quantity'">
              <el-input
                v-model="scope.row.quantity"
                size="small"
                placeholder="请输入"
                clearable
                :disabled="props.type == 'look'"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="inboundTime" label="入库日期" align="center" width="140">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.inboundTime'">
              <el-date-picker
                :disabled="props.type == 'look'"
                clearable
                size="small"
                style="width: 100%"
                v-model="scope.row.inboundTime"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              >
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价(元)" align="center" width="114">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.unitPrice'">
              <el-input
                v-model="scope.row.unitPrice"
                size="small"
                placeholder="请输入"
                :disabled="props.type == 'look'"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="价值(万元)" align="center" width="114">
          <template #default="scope">
            <span v-if="scope.row.materialTree && wanJson.indexOf(scope.row.materialTree[3]) == -1">
              {{ decimalDev(decimalMul(scope.row.quantity, scope.row.unitPrice), 10000) || 0 }}
            </span>
            <span v-else>
              {{ decimalMul(scope.row.quantity, scope.row.unitPrice) || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="isAvailable" label="是否可用" align="center" width="120">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.isAvailable'">
              <el-select
                v-model="scope.row.isAvailable"
                style="width: 90px"
                size="small"
                :disabled="props.type == 'look'"
                clearable
              >
                <el-option v-for="item in is_available" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="filePart" label="附件上传" align="center" width="114">
          <template #default="scope">
            <el-upload
              :disabled="props.type == 'look'"
              v-model:file-list="scope.row.filePartList"
              class="upload-demo"
              v-if="props.type != 'look'"
              style="width: 100%"
              :action="fileUrl"
              :data="paramsData"
              :headers="myHeader"
              multiple
              :on-preview="handlePreview"
              :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>
            <p v-else @click="handlePreviewDetail(scope.row.filePart)" style="cursor: pointer; color: #409eff">
              {{ scope.row.fileName }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" align="center" width="114">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.remarks'">
              <el-input
                v-model="scope.row.remarks"
                size="small"
                placeholder="请输入"
                :disabled="props.type == 'look'"
              ></el-input>
            </el-form-item>
          </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-row v-if="auditData && auditData.length > 0" style="margin-top: 20px">
      <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>
    <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 } from "element-plus";
import router from "@/router";
import { addInData, updateInData, lookInData, dictTree, sysFile } from "@/api/inAndOut/formationFilling/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 { number } from "echarts";

const { indound_type, is_available, province_ch } = useDict("indound_type", "is_available", "province_ch");

// const props = defineProps(['id','type'])
const props = getQuery("/InformationFilling/enterWarehouseInfoDetail");
// 价值计算带万
const wanJson = ["118", "122", "124", "132", "182", "184"];

// const tableData = ref([{}]);
const wzOptions = ref([]);
const ruleForms = ref();
const auditData = ref();
const formData = reactive({
  tableData: []
});
const rules = reactive({
  inboundType: [
    {
      required: true,
      message: "请选择入库类型",
      trigger: "change"
    }
  ],
  materialTree: [
    {
      required: true,
      message: "请选择物资名称",
      trigger: "change"
    }
  ]
  // inboundTime: [
  //   {
  //     required: true,
  //     message: "请选择入库日期",
  //     trigger: "change"
  //   }
  // ],
  // isAvailable: [
  //   {
  //     required: true,
  //     message: "请选择是否可用",
  //     trigger: "change"
  //   }
  // ],
  // quantity: [
  //   {
  //     required: true,
  //     message: "请输入数量",
  //     trigger: "blur"
  //   }
  // ],
  // unitPrice: [
  //   {
  //     required: true,
  //     message: "请输入单价",
  //     trigger: "blur"
  //   }
  // ]
});

// 下拉数据
const getSelect = () => {
  dictTree().then((res: any) => {
    if (res.code === 0) {
      wzOptions.value = res.data;
    }
  });
};
const handleChange = (value: string) => {
  console.log(JSON.stringify(value));
};
// 新增一行
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.inboundMaterial;
      getData.forEach((item: any) => {
        item.filePartList = item.filePart ? [{ name: item.fileName, filePart: item.filePart }] : [];
      });
      formData.tableData = getData;
      auditData.value = res.data.inboundStatus;
    }
  });
};
/** 保存、提交 */
const saveSubmit = (status: any) => {
  ruleForms.value.validate((valid: any) => {
    if (valid) {
      const tabData0 = formData.tableData[0];
      let postData = {
        inboundId: props.id,
        status: status,
        inboundType: tabData0.inboundType,
        materialGroup: tabData0.materialTree[0],
        materialType: tabData0.materialTree[1],
        materialName: tabData0.materialTree[2],
        quantity: tabData0.quantity,
        inboundTime: tabData0.inboundTime,
        isAvailable: tabData0.isAvailable,
        inboundMaterialInfos: formData.tableData
      };
      postData.inboundMaterialInfos = formData.tableData.map(function ({ filePartList, ...item }) {
        let totalPrice = decimalMul(item.quantity, item.unitPrice) || 0;
        if (wanJson.indexOf(item.materialTree[3]) == -1) {
          totalPrice = decimalDev(decimalMul(item.quantity, item.unitPrice), 10000) || 0;
        }
        let returnData = {
          ...item,
          materialGroup: item.materialTree[0],
          materialType: item.materialTree[1],
          materialName: item.materialTree[2],
          unit: item.materialTree[3],
          totalPrice: totalPrice
        };
        return returnData;
      });
      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: "新增成功！",
              type: "success"
            });
          }
        });
      }
    } else {
      console.log("error submit!");
    }
  });
};

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);
};
/** 返回 */
const returnPage = () => {
  // closeTagAndOpenLastTag()
  store.commit("DEL_TAG", store.getters.tag);
  router.push({
    path: "/InformationFilling/enterWarehouseInfo"
    // query: {random: Math.random()}
  });
};

//附件部分
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;
};
const handleRemove = (file: any, uploadFiles: any) => {
  console.log(file, uploadFiles);
};
const handlePreview = (file: any) => {
  const url = file.response.data.fileName;
  if (url) {
    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 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: any) => {
  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;
}
</style>
