<!-- 应急物资分类表 -->
<template>
  <basic-container>
    <el-form class="whole_form">
      <el-form-item label="调出仓库">
        <el-select v-model="formData.deptId" style="width: 300px" :disabled="props.type == 'look'" clearable>
          <el-option v-for="item in dcckOptions" :key="item.deptId" :label="item.name" :value="item.deptId" />
        </el-select>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" border>
      <el-table-column prop="outboundType" label="出库类型" align="center" width="120">
        <template #default="scope">
          <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>
        </template>
      </el-table-column>
      <el-table-column prop="materialTree" label="物资名称" align="center" width="360">
        <template #default="scope">
          <el-cascader
            :disabled="props.type == 'look'"
            clearable
            size="small"
            v-model="scope.row.materialTree"
            placeholder="请选择粮食性质"
            :options="wzOptions"
            :props="{ value: 'id', label: 'name' }"
            style="width: 100%"
            @change="handleChange"
          ></el-cascader>
        </template>
      </el-table-column>
      <el-table-column prop="specs" label="规格" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.specs" size="small" :disabled="props.type == 'look'"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.quantity" size="small" :disabled="props.type == 'look'"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="province" label="调用省份" align="center" width="120">
        <template #default="scope">
          <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>
        </template>
      </el-table-column>

      <el-table-column prop="outboundTime" label="出库日期" align="center" width="140">
        <template #default="scope">
          <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>
        </template>
      </el-table-column>
      <el-table-column prop="unitPrice" label="单价(元)" align="center" width="114">
        <template #default="scope">
          <el-input v-model="scope.row.unitPrice" size="small" :disabled="props.type == 'look'"></el-input>
        </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">
            {{
              (scope.row.quantity * scope.row.unitPrice) / 10000
                ? (scope.row.quantity * scope.row.unitPrice) / 10000
                : 0
            }}
          </span>
          <span v-else>
            {{ scope.row.quantity * scope.row.unitPrice ? 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-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>
        </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"
            style="width: 100%"
            :action="fileUrl"
            :data="paramsData"
            :headers="myHeader"
            multiple
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="(response, file, index) => getFileInfo(response, file, scope.$index)"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <el-button v-if="props.type != 'look'" size="small" type="primary">选择文件</el-button>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" align="center" width="114">
        <template #default="scope">
          <el-input v-model="scope.row.remarks" size="small" :disabled="props.type == 'look'"></el-input>
        </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>
    <div class="operationbox">
      <el-button type="success" @click="saveSubmit" 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 router from "@/router";
import { addOutData, updateOutData, lookOutData, dictTree, 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";

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"];

const tableData = ref([{}]);
const wzOptions = ref([]);
const dcckOptions = ref([]);
const formData = ref({
  deptId: ""
});

// 根据码回显中文
const showCh = (value, option) => {
  const filterItem = option.filter((item) => item.deptId == value);
  return filterItem.length ? filterItem[0].name : "";
};

// 下拉数据
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) => {
  console.log(JSON.stringify(value));
};
// 新增一行
const addTableData = (rowIndex) => {
  const newRow = {};
  tableData.value.splice(rowIndex + 1, 0, newRow);
};
// 删除
const deleteTableData = (rowIndex) => {
  if (tableData.value.length > 1) {
    tableData.value.splice(rowIndex, 1);
  } else {
    ElMessage({
      message: "最后一条不可删除！",
      type: "warning"
    });
  }
};
// 详情获取数据
const lookData = () => {
  lookOutData(props.id).then((res: any) => {
    if (res.code === 0) {
      let getData = res.data.outboundMaterial;
      tableData.value = getData.map((item) => ({
        ...item,
        filePartList: [{ name: item.fileName, filePart: item.filePart }]
      }));
      formData.value.deptId = res.data.deptId;
      console.log(tableData.value);
    }
  });
};
/** 保存、提交 */
const saveSubmit = (status) => {
  const tabData0 = tableData.value[0];
  let postData = {
    outboundId: props.id,
    status: 7,
    outboundType: tabData0.outboundType,
    materialGroup: tabData0.materialTree[0],
    materialType: tabData0.materialTree[1],
    materialName: tabData0.materialTree[2],
    quantity: tabData0.quantity,
    calledProvince: tabData0.province,
    outboundTime: tabData0.outboundTime,
    isAvailable: tabData0.isAvailable,
    outboundMaterialInfos: tableData.value,
    deptId: formData.value.deptId,
    warehouse: showCh(formData.value.deptId, dcckOptions.value)
  };
  postData.outboundMaterialInfos = tableData.value.map(function ({ filePartList, ...item }) {
    let totalPrice = item.quantity * item.unitPrice ? item.quantity * item.unitPrice : 0;
    if (wanJson.indexOf(item.materialTree[3]) == -1) {
      totalPrice = (item.quantity * item.unitPrice) / 10000 ? (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) {
    updateOutData(postData).then((res: any) => {
      if (res.code === 0) {
        returnPage();
        ElMessage({
          message: "修改成功！",
          type: "success"
        });
      }
    });
  } else {
    addOutData(postData).then((res: any) => {
      if (res.code === 0) {
        returnPage();
        ElMessage({
          message: "新增成功！",
          type: "success"
        });
      }
    });
  }
};

/** 返回 */
const returnPage = (row: any) => {
  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 " + sessionStorage.getItem("access_token") };
// 附件相关
const getFileInfo = (res: any, file: any, index: number) => {
  tableData.value[index].filePart = res.data.fileName;
  tableData.value[index].fileName = file.name;
};
const handleRemove = (file: any, uploadFiles: any) => {
  console.log(file, uploadFiles);
};
const handlePreview = (uploadFile: any) => {
  console.log(uploadFile);
  sysFile(uploadFile.filePart).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) => {
  return ElMessageBox.confirm(`确定移除 ${uploadFile.name} ?`).then(
    () => true,
    () => false
  );
};
/** -----------------附件结束--------------- */

/** 初始化 **/
onMounted(() => {
  getSelect();
  if (props.type) {
    lookData();
  } else {
    tableData.value = [{}];
  }
});
</script>

<style lang="scss" scoped>
.operationbox {
  text-align: center;
  margin-top: 30px;
}
</style>
