<template>
  <div>
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="派工单号">
        <el-input v-model="form.planCode" disabled style="width:360px"></el-input>
      </el-form-item>
      <el-form-item label="明细编号">
        <el-input v-model="form.planDetailCode" disabled></el-input>
      </el-form-item>
      <el-form-item label="仓库">
        <el-select v-model="form.warehouseId" placeholder="请选择仓库" style="width:360px" @change="warehouseChange">
          <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
                     :value="item.warehouseId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="领取原因">
        <el-input v-model="form.applyReason" type="textarea"></el-input>
      </el-form-item>
    </el-form>


    <el-divider content-position="center">物料信息</el-divider>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="130px">
      <el-form-item label="编码、名称或规格" prop="materialCodeNameSpec">
        <el-input
          v-model="queryParams.materialCodeNameSpec"
          placeholder="请输入编码、名称或规格"
          clearable
          @keyup.enter.native="searchMaterial"/>
      </el-form-item>

<!--      <el-form-item label="辅料标识" prop="accessoriesFlag">-->
<!--        <el-radio-group v-model="queryParams.accessoriesFlag">-->
<!--          <el-radio-->
<!--            v-for="dict in dict.type.mes_material_accessories_flag"-->
<!--            :key="dict.value"-->
<!--            :label="dict.value"-->
<!--          >{{ dict.label }}-->
<!--          </el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchMaterial('1')">BOM内物料搜索</el-button>
        <el-button type="warning" icon="el-icon-search" size="mini" @click="searchMaterial('0')">非BOM内物料搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :cell-style="{textAlign:'center'}"
      :data="wmsRawOutstockDetailList"
      :header-cell-style="{textAlign:'center'}"
      max-height="19.13vw"
      style="width: 100%;"
      v-loading="loading"
    >
      <el-table-column
        label="物料编号"
        prop="materialCode"
      >
      </el-table-column>
      <el-table-column
        label="物料名称"
        prop="materialName"
      >
      </el-table-column>
      <el-table-column
        label="物料规格"
        prop="materialSpec"
      >
      </el-table-column>
      <el-table-column
        label="安全库存"
        prop="safeFlag"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_safe_flag" :value="scope.row.safeFlag"/>
        </template>
      </el-table-column>

      <el-table-column
        label="可用库存"
        prop="availableAmount"
      >
      </el-table-column>
      <el-table-column
        label="占用库存"
        prop="unavailableAmount"
      >
      </el-table-column>
      <el-table-column
        label="已申请"
        prop="outstockAmount"
      >
      </el-table-column>
      <el-table-column
        label="领取数量"
        prop="planAmount"
        width="120"
      >
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.planAmount"
            controls-position="right"
            :max="maxPlanAmount"
            style="width: 100%"
          >
          </el-input-number>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
      >
        <template slot="header" slot-scope="scope">

          <br/>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="searchMaterial"
    />

    <div style="text-align: center;margin-top: 30px">
      <el-button type="primary" :loading="submitLoading" @click="submitForm">申请</el-button>
      <el-button type="info" @click="closeParentDialog">关闭</el-button>

    </div>

  </div>
</template>

<script>
import {getWarehouses, getMaterialInfoByMaterialId,getStockTotal, applyRawOutstock} from "@/api/board";

export default {
  name: "Materialinfo",
  props: {
    defineData: {
      type: Object,
      default: {}
    }
  },
  dicts: ['mes_safe_flag','mes_material_accessories_flag'],
  inject: ['closeDialog'],
  data() {
    return {
      // 遮罩层
      loading: true,
      //保存遮罩层
      submitLoading : false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料信息表格数据
      warehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      maxPlanAmount: 1,
      returnFlag: '',
      taskType: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        erpId: null,
        materialCode: null,
        oldMaterialCode: null,
        materialName: null,
        materialCategories: null,
        materialSubclass: null,
        materialTypeId: null,
        batchFlag: null,
        materialUnitId: null,
        materialUnit: null,
        materialMatkl: null,
        materialSpec: null,
        netWeight: null,
        grossWeight: null,
        factoryId: null,
        createOrgId: null,
        useOrgId: null,
        prodlineId: null,
        activeFlag: null,
        deletedFlag: null,
        approveDate: null,
        erpModifyDate: null,
        accessoriesFlag:'1' //bom内物料标识
      },
      // 表单参数
      form: {},
      RETURN_FLAG: {//返库标识
        YES: '1',//是
      },
      wmsRawOutstockDetailList:[],
    };
  },
  created() {
    this.getData();
    this.getMaterialInfoByMaterialId();
  },
  methods: {
    getData() {
      if (this.defineData.planCode) {
        this.form = {
          warehouseId: '',
          planId: this.defineData?.planId,
          planCode: this.defineData?.planCode,
          dispatchCode: this.defineData?.dispatchCode,
          planDetailCode: this.defineData?.planDetailCode,
          saleOrderId: this.defineData?.saleOrderId,
          productId: this.defineData?.productId,
          materialBomId: this.defineData?.materialBomId,
          applyReason: '',
          taskType: this.defineData?.taskType,
          stationId: this.defineData?.stationId,
          endStationCode: this.defineData?.stationCode,
          returnFlag: this.defineData?.returnFlag,
          mesAreaType: this.defineData?.mesAreaType,
          warehouseFloor: this.defineData?.warehouseFloor,
          wmsRawOutstockDetailList: []
        }

      }
      if (this.defineData.maxPlanAmount) {
        this.maxPlanAmount = this.defineData.maxPlanAmount
      }
      if (this.defineData.returnFlag) {
        this.returnFlag = this.defineData.returnFlag;
      }
    },

    getMaterialInfoByMaterialId(){
      getMaterialInfoByMaterialId(this.defineData.productId).then(e =>{
        this.queryParams.materialClassfication = e.data.materialClassfication;
        this.getWarehouses();
      });
    },


    getWarehouses() {
      // 获取仓库信息
      getWarehouses({
        warehouseFloor: this.defineData.warehouseFloor,
        returnFlag: this.defineData.returnFlag,
        mesAreaType: this.defineData.mesAreaType,
      }).then(e => {
        this.warehouseList = e.data
        this.form.warehouseId = e.data[0]?.warehouseId
        this.searchMaterial();
      })
    },

    warehouseChange(warehouseId) {
      this.form.wmsRawOutstockDetailList = [];
      this.form.warehouseId = warehouseId;
      this.searchMaterial();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.searchMaterial();
    },

    // 物料搜索
    searchMaterial(bomFlag) {
      this.loading = true;
      if (this.form.warehouseId === null || this.form.warehouseId === undefined
        || this.form.warehouseId === "") {
        return;
      }
      this.queryParams.warehouseId = this.form.warehouseId;
      this.queryParams.saleOrderId = this.form.saleOrderId;
      this.queryParams.planCode = this.form.planCode;
      this.queryParams.planDetailCode = this.form.planDetailCode;
      this.queryParams.productId = this.form.productId;
      this.queryParams.materialBomId = this.form.materialBomId;
      this.queryParams.accessoriesFlag = bomFlag;
      getStockTotal(this.queryParams).then(e => {
        this.total = e.total;
        // e.rows.forEach(ee =>{
        //    alert(parseFloat(ee.totalAmount-ee.occupyAmount).toFixed(2))
        // });

        this.wmsRawOutstockDetailList = e.rows.map(r => {
          return {
            stockTotalId: r.stockTotalId,
            materialId: r.materialId,
            materialCode: r.materialCode,
            materialName: r.materialName,
            materialSpec: r.materialSpec,
            safeFlag: r.safeFlag,
            availableAmount: parseFloat(r.totalAmount - r.occupyAmount - r.frozenAmount).toFixed(2),
            unavailableAmount: parseFloat(r.occupyAmount + r.frozenAmount).toFixed(2),
            outstockAmount: parseFloat(r.outstockAmount ? r.outstockAmount : 0).toFixed(2),
            planAmount: this.planAmount
          }
        })
        this.loading = false;
      })
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: null,
        erpId: null,
        materialCode: null,
        oldMaterialCode: null,
        materialName: null,
        materialCategories: null,
        materialSubclass: null,
        materialTypeId: null,
        batchFlag: null,
        materialUnitId: null,
        materialUnit: null,
        materialMatkl: null,
        materialSpec: null,
        netWeight: null,
        grossWeight: null,
        factoryId: null,
        createOrgId: null,
        useOrgId: null,
        prodlineId: null,
        activeFlag: null,
        deletedFlag: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        approveDate: null,
        erpModifyDate: null
      };
      this.resetForm("form");
    },

    /** 提交按钮 */
    submitForm() {
      let realOutstockDetailList = this.wmsRawOutstockDetailList.filter(detail => detail.planAmount > 0);
      if (realOutstockDetailList.length <= 0) {
        this.$modal.msgWarning("请输入领取数量");
        return;
      }
      this.submitloading = true;
      this.form.wmsRawOutstockDetailList = realOutstockDetailList;
      applyRawOutstock(this.form).then(e => {
        if (this.returnFlag === this.RETURN_FLAG.YES) {
          this.closeParentDialog()
        } else {
          this.searchMaterial();
        }
        this.$modal.msgSuccess("申请成功");
      }).finally(e => {
        this.submitloading = false;
      })
    },

    closeParentDialog() {
      this.closeDialog()
    }

  }
};
</script>
<style lang="less" scoped>


.el-table {
  background-color: #fff0;
  overflow-y: auto;
}


.roundBorder {
  position: absolute;
  transform: translate(-50%, -50%);
}


</style>
