<!-- 应急物资分类表 -->
<template>
  <basic-container class="container">
    <el-form
      class="whole_form"
      :rules="rules"
      :inline="true"
      ref="ruleForms"
      label-width="80px"
      label-suffix=":"
      :model="formData"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="调令编号">
            <el-input v-model="formData.orderNo" :disabled="props.type == 'look'" style="width: 200px" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库凭证">
            <el-input v-model="formData.orderName" :disabled="props.type == 'look'" style="width: 200px" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="附件上传">
            <el-upload
              :disabled="props.type == 'look'"
              v-model:file-list="formData.filePartList"
              class="upload-demo"
              style="width: 100%"
              v-if="props.type != 'look'"
              :action="fileUrl"
              :data="paramsData"
              :headers="myHeader"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="(response, file) => getFileInfoFile(response, file)"
              :on-error="errorUpload"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
            <span v-else>{{ formData.fileName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注">
            <el-input v-model="formData.remarks" :disabled="props.type == 'look'" style="width: 100%" clearable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form :rules="rules" ref="ruleForms" :model="formData">
      <el-table :data="formData.tableData" border show-summary :summary-method="getSummaries">
        <el-table-column prop="deptId" label="调出仓库" align="center" width="120">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.deptId'" :rules="rules.deptId">
              <el-select
                v-model="scope.row.deptId"
                style="width: 100%"
                size="small"
                @change="(val:any) => getDeptName(val, scope.$index)"
                :disabled="props.type == 'look'"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dcckOptions"
                  :key="item.deptId"
                  :label="item.abbreviationName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="outboundType" label="出库类型" align="center" width="120">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.outboundType'" :rules="rules.outboundType">
              <el-select
                v-model="scope.row.outboundType"
                style="width: 100%"
                size="small"
                :disabled="props.type == 'look'"
                clearable
              >
                <el-option v-for="item in outdound_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="(val:any) => handleChange(val, scope.$index)"
              ></el-cascader> -->
              <el-cascader
                :disabled="props.type == 'look'"
                clearable
                filterable
                size="small"
                v-model="scope.row.materialTree"
                placeholder="请选择物资"
                :options="scope.row.wzOptions"
                :props="{ value: 'id', label: 'name' }"
                style="width: 100%"
                @change="(val:any) => handleChange(val, scope.$index)"
              ></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'" :rules="rules.quantity">
              <el-input
                v-model="scope.row.quantity"
                size="small"
                placeholder="请输入"
                :disabled="props.type == 'look'"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="province" label="调用省份" align="center" width="120">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.province'" :rules="rules.province">
              <el-select
                v-model="scope.row.province"
                style="width: 100%"
                size="small"
                :disabled="props.type == 'look'"
                clearable
              >
                <el-option v-for="item in province_ch" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="outboundTime" label="出库日期" align="center" width="140">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.outboundTime'" :rules="rules.outboundTime">
              <el-date-picker
                :disabled="props.type == 'look'"
                clearable
                size="small"
                style="width: 100%"
                v-model="scope.row.outboundTime"
                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="inboundTime" label="入库日期" align="center" width="140">
          <template #default="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.inboundTime'" :rules="rules.inboundTime">
              <el-select
                v-model="scope.row.inboundTime"
                :disabled="props.type == 'look'"
                size="small"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(item, index) in scope.row.rkrqAndDjOption"
                  :key="index"
                  :label="item.inboundTime"
                  :value="item.inboundTime"
                />
              </el-select>
              <!-- <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'" :rules="rules.unitPrice">
              <el-select
                v-model="scope.row.unitPrice"
                :disabled="props.type == 'look'"
                size="small"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(item, index) in scope.row.rkrqAndDjOption"
                  :key="index"
                  :label="item.unitPrice"
                  :value="item.unitPrice"
                />
              </el-select>
              <!-- <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'" :rules="rules.isAvailable">
              <el-select
                v-model="scope.row.isAvailable"
                :disabled="props.type == 'look'"
                size="small"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(item, index) in scope.row.rkrqAndDjOption"
                  :key="index"
                  :label="isAvailableLabel[Number(item.isAvailable)]"
                  :value="item.isAvailable"
                />
              </el-select>
              <!-- <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"
              v-if="props.type != 'look'"
              class="upload-demo"
              style="width: 100%"
              :action="fileUrl"
              :data="paramsData"
              :on-preview="handlePreview"
              :headers="myHeader"
              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>
            <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>
    <div class="operationbox">
      <el-button type="success" @click="saveSubmit('8')" v-if="props.type != 'look'">保存</el-button>
      <el-button type="primary" @click="saveSubmit('7')" 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, h } 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 {
  addInOrderData,
  updateOutData,
  lookOutDataNew,
  dictTree,
  materialsTree,
  getTimeAndUnitPriceForOutbound,
  getDeptTypeList
} from "@/api/inAndOut/formationFilling/out";
import { sysFile } from "@/api/inAndOut/formationFilling/in";
import { useDict } from "@/hooks/dict";
import { getQuery } from "@/hooks/detailQuery/index";
// import { closeTagAndOpenLastTag } from '@/router/Routermethods';
import store from "@/store";
import { useGetters } from "@/hooks/storeHooks";
const { access_token } = useGetters(["access_token"]);
import { decimalMul, decimalDev, decimalAdd } from "@/global/decimalCompute";
import type { TableColumnCtx } from "element-plus";

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

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

// 是否可用Label
const isAvailableLabel = ["是", "否"];

// const tableData = ref([{}]);
const wzOptions = ref([]);
const dcckOptions = ref([]);
const formData = reactive({
  orderNo: "",
  tableData: [],
  filePartList: [],
  orderName: "",
  filePart: "",
  fileName: "",
  remarks: ""
});
const ruleForms = ref();
const rules = reactive({
  deptId: [
    {
      required: true,
      message: "请选择调出仓库",
      trigger: "change"
    }
  ],
  outboundType: [
    {
      required: true,
      message: "请选择出库类型",
      trigger: "change"
    }
  ],
  materialTree: [
    {
      required: true,
      message: "请选择物资名称",
      trigger: "change"
    }
  ],
  province: [
    {
      required: true,
      message: "请选择调用省份",
      trigger: "change"
    }
  ],
  outboundTime: [
    {
      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;
    }
  });
  getDeptTypeList().then((res: any) => {
    if (res.code === 0) {
      dcckOptions.value = res.data;
    }
  });
};
const handleChange = (value, index) => {
  const postData = {
    materialGroup: value[0],
    materialType: value[1],
    materialName: value[2],
    materialUnit: value[3],
    warehouseId: formData.tableData[index].deptId
  };

  getTimeAndUnitPriceForOutbound(postData).then((res: any) => {
    if (res.code === 0) {
      formData.tableData[index].rkrqAndDjOption = res.data;
    }
  });
};

const getDeptName = (value: any, index: number) => {
  if (value) {
    const filterItem = dcckOptions.value.filter((item) => item.deptId == value);
    formData.tableData[index].warehouse = filterItem[0].abbreviationName;

    materialsTree({warehouseId:value}).then((res: any) => {
      if (res.code === 0) {
        formData.tableData[index].wzOptions = res.data;
      }
    });
  }
};


interface Product {
  id: string;
  quantity: string;
  unitPrice: number;
  totalPrice: number;
}
interface SummaryMethodProps<T = Product> {
  columns: TableColumnCtx<T>[];
  data: T[];
}
const summaryJson = ["quantity", "totalPrice"];
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  const sums: (string | VNode)[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h("div", ["合计"]);
      return;
    }
    if (summaryJson.indexOf(column.property) != -1) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return decimalAdd(prev, curr);
            // return prev + curr;
          } else {
            return prev;
          }
        }, 0)}`;
      } else {
        sums[index] = "0";
      }
    }
  });

  return sums;
};
// 计算总价
const totalPrice = (row: any) => {
  if (row.unitPrice && row.quantity) {
    row.totalPrice = decimalMul(row.unitPrice, row.quantity);
  }
};

// 新增一行
const addTableData = (rowIndex) => {
  const newRow = {};
  formData.tableData.splice(rowIndex + 1, 0, newRow);
};
// 删除
const deleteTableData = (rowIndex) => {
  if (formData.tableData.length > 1) {
    formData.tableData.splice(rowIndex, 1);
  } else {
    ElMessage({
      message: "最后一条不可删除！",
      type: "warning"
    });
  }
};
// 获取物资下拉数据
const getWzOptions = (value: any, index, itemName) => {
  if (value) {
    materialsTree({warehouseId:value}).then((res: any) => {
      if (res.code === 0) {
        formData.tableData[index].wzOptions = res.data;
        formData.tableData[index].materialTree = itemName;
      }
    });
  }
};
// 获取入库日期等下拉数据
const getRkrqAndDjOption = (value, deptId, index) => {
  const postData = {
    materialGroup: value[0],
    materialType: value[1],
    materialName: value[2],
    materialUnit: value[3],
    warehouseId: deptId
  };

  getTimeAndUnitPriceForOutbound(postData).then((res: any) => {
    if (res.code === 0) {
      formData.tableData[index].rkrqAndDjOption = res.data;
    }
  });
};
// 详情获取数据
const lookData = () => {
  lookOutDataNew(props.id).then((res: any) => {
    if (res.code === 0) {
      let getData = res.data.orderOutboundMaterialInfos;
      formData.tableData = getData.map((item: any) => ({
        ...item,
        filePartList: [{ name: item.fileName, filePart: item.filePart }]
      }));
      formData.tableData = getData.map((item: any, index) => ({
        ...item,
        filePartList: [{ name: item.fileName, filePart: item.filePart }],
        wzOptions: getWzOptions(item.deptId, index, item.materialTree),
        rkrqAndDjOption: getRkrqAndDjOption(item.materialTree, item.deptId, index)
      }));
      formData.orderNo = res.data.orderNo;
      formData.filePartList = res.data.filePartList;
      formData.orderName = res.data.orderName;
      formData.filePart = res.data.filePart;
      formData.fileName = res.data.fileName;
      formData.filePart = res.data.filePart;
      formData.remarks = res.data.remarks;
      formData.filePartList = [{ name: res.data.fileName, url: res.data.filePart }];
      console.log(formData.tableData);
    }
  });
};
/** 保存、提交 */
const saveSubmit = (status: any) => {
  ruleForms.value.validate((valid: any) => {
    if (valid) {
      let postData = { ...formData, status, orderOutboundMaterialInfos: [], orderId: null };
      formData.tableData.map((item: any) => {
        let totalPrice = decimalMul(item.quantity, item.unitPrice) || 0;
        if (wanJson.indexOf(item.materialTree[3]) == -1) {
          totalPrice = decimalDev(decimalMul(item.quantity, item.unitPrice), 10000) || 0;
        }
        item.totalPrice = totalPrice;
        item.materialGroup = item.materialTree[0];
        item.materialType = item.materialTree[1];
        item.materialName = item.materialTree[2];
        item.unit = item.materialTree[3];
      });
      postData.orderOutboundMaterialInfos = formData.tableData;
      delete postData.tableData;
      if (props.id) {
        postData.orderId = props.id;
      }
      addInOrderData(postData).then((res: any) => {
        if (res.code === 0) {
          returnPage();
          ElMessage({
            message: status === "8" ? "保存成功！" : "提交成功！",
            type: "success"
          });
        }
      });
    } else {
      console.log("error submit!");
    }
  });
};

/** 返回 */
const returnPage = () => {
  store.commit("DEL_TAG", store.getters.tag);
  // closeTagAndOpenLastTag()
  router.push({
    path: "/InformationFilling/outIssue"
    // 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 getFileInfoFile = (res: any, file: any) => {
  formData.filePart = res.data.fileName;
  formData.fileName = file.name;
  formData.filePartList = [{ name: file.name, filePart: res.data.fileName }];
};

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>
