<template>
  <div class="app-container">

    <h4 class="form-header h4">销售订单信息</h4>
    <el-form ref="saleOrderForm" :model="saleOrderForm" label-width="100px">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="销售订单编号" prop="saleorderCode">
            <el-input v-model="saleOrderForm.saleorderCode" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="销售物料规格" prop="materialModel">
            <el-input v-model="saleOrderForm.materialModel" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="销售物料编号" prop="materialCode">
            <el-input v-model="saleOrderForm.materialCode" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="销售物料名称" prop="materialName">
            <el-input v-model="saleOrderForm.materialName" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row>
      <!--      <el-col :span="12">-->
      <!--        <h4 class="form-header h4">已选采购订单</h4>-->
      <!--        <el-form :model="allocatePurchaseOrderQueryParams" ref="allocateMaterialQueryForm" size="small" :inline="true"-->
      <!--                 v-show="showSearch"-->
      <!--                 label-width="68px">-->
      <!--          <el-form-item label="订单编号" prop="poNo">-->
      <!--            <el-input-->
      <!--              v-model="allocatePurchaseOrderQueryParams.poNo"-->
      <!--              placeholder="请输入物料编码"-->
      <!--              style="width:140px;"-->
      <!--              clearable-->
      <!--              @keyup.enter.native="handleAllocateMaterialQuery"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--          <el-form-item label="物料编码" prop="materialCode">-->
      <!--            <el-input-->
      <!--              v-model="allocatePurchaseOrderQueryParams.materialCode"-->
      <!--              placeholder="请输入物料编码"-->
      <!--              style="width:140px;"-->
      <!--              clearable-->
      <!--              @keyup.enter.native="handleAllocateMaterialQuery"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--          <el-form-item label="物料名称" prop="materialName">-->
      <!--            <el-input-->
      <!--              v-model="allocatePurchaseOrderQueryParams.materialName"-->
      <!--              placeholder="请输入物料名称"-->
      <!--              style="width:140px;"-->
      <!--              clearable-->
      <!--              @keyup.enter.native="handleAllocateMaterialQuery"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--          <el-form-item>-->
      <!--            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleAllocateMaterialQuery">搜索-->
      <!--            </el-button>-->
      <!--            <el-button icon="el-icon-refresh" size="mini" @click="resetAllocateMaterialQuery">重置</el-button>-->
      <!--            <el-button-->
      <!--              type="danger"-->
      <!--              plain-->
      <!--              icon="el-icon-delete"-->
      <!--              size="mini"-->
      <!--              @click="handleUnallocateBarCodes"-->
      <!--              v-hasPermi="['mes:saleOrder:bind']"-->
      <!--            >删除-->
      <!--            </el-button>-->
      <!--          </el-form-item>-->
      <!--        </el-form>-->
      <!--        <el-table v-loading="allocateLoading" :data="allocatePurchaseOrderList"-->
      <!--                  @selection-change="handleAllocateMaterialSelectionChange">-->
      <!--          <el-table-column type="selection" width="55" align="center"/>-->
      <!--          <el-table-column label="订单编号" align="center" prop="poNo"/>-->
      <!--          <el-table-column label="物料编码" align="center" prop="materialCode"/>-->
      <!--          <el-table-column label="物料名称" align="center" prop="materialName"/>-->
      <!--          <el-table-column label="物料规格" align="center" prop="materialSpec"/>-->
      <!--          <el-table-column label="规格参数" align="center" prop="specificationParameter" :show-overflow-tooltip="true"/>-->
      <!--          <el-table-column label="数量" align="center" prop="orderAmount"/>-->
      <!--        </el-table>-->

      <!--        <pagination-->
      <!--          v-show="allocatePurchaseOrderTotal>0"-->
      <!--          :total="allocatePurchaseOrderTotal"-->
      <!--          :page.sync="allocatePurchaseOrderQueryParams.pageNum"-->
      <!--          :limit.sync="allocatePurchaseOrderQueryParams.pageSize"-->
      <!--          @pagination="getAllocatePurchaseOrderList"-->
      <!--        />-->
      <!--      </el-col>-->


      <!--      <el-col :span="12" >-->
      <h4 class="form-header h4">可选采购订单</h4>
      <el-form :model="purchaseOrderQueryParams" ref="materialQueryForm" size="small" :inline="true" v-show="showSearch"
               label-width="68px">
        <el-form-item label="订单编号" prop="poNo">
          <el-input
            v-model="allocatePurchaseOrderQueryParams.poNo"
            placeholder="请输入物料编码"
            style="width:140px;"
            clearable
            @keyup.enter.native="handleAllocateMaterialQuery"
          />
        </el-form-item>
        <el-form-item label="物料编码" prop="materialCode">
          <el-input
            v-model="purchaseOrderQueryParams.materialCode"
            placeholder="请输入物料编码"
            style="width:140px;"
            clearable
            @keyup.enter.native="handlePurchaseOrderQuery"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input
            v-model="purchaseOrderQueryParams.materialName"
            placeholder="请输入物料名称"
            style="width:140px;"
            clearable
            @keyup.enter.native="handlePurchaseOrderQuery"
          />
        </el-form-item>
        <el-form-item label="物料规格" prop="materialSpec">
          <el-input
            v-model="purchaseOrderQueryParams.materialSpec"
            placeholder="请输入物料规格"
            style="width:140px;"
            clearable
            @keyup.enter.native="handlePurchaseOrderQuery"
          />
        </el-form-item>
        <el-form-item label="规格参数" prop="specificationParameter">
          <el-input
            v-model="purchaseOrderQueryParams.specificationParameter"
            placeholder="请输入规格参数"
            style="width:140px;"
            clearable
            @keyup.enter.native="handlePurchaseOrderQuery"
          />
        </el-form-item>
        <el-form-item label="常备物料" prop="alwaysFlag">
          <el-select v-model="purchaseOrderQueryParams.alwaysFlag" placeholder="请选择常备物料标识" clearable>
            <el-option
              v-for="dict in dict.type.mes_material_bind_flag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handlePurchaseOrderQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMaterialQuery">重置</el-button>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="multiple"
            @click="submitForm"
            v-loading="submitLoading"
            v-hasPermi="['mes:saleOrder:bind']"
          >保存
          </el-button>
          <!--el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleUnallocateBarCodes"
            v-hasPermi="['mes:saleOrder:bind']"
          >删除
          </el-button-->
        </el-form-item>
      </el-form>


      <el-table v-loading="selectableLoading"
                :data="purchaseOrderList"
                @selection-change="handleMaterialSelectionChange"
                :row-class-name="rowSerialNumberProcess"
                :row-style="getRowStyle">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" prop="serialNumber"/>
        <el-table-column label="订单ID" align="center" prop="purchaseOrderId"/>
        <el-table-column label="订单编号" align="center" prop="poNo"/>
        <el-table-column label="物料编码" align="center" prop="materialCode"/>
        <el-table-column label="物料名称" align="center" prop="materialName"/>
        <el-table-column label="物料规格" align="center" prop="materialSpec" :show-overflow-tooltip="true"/>
        <el-table-column label="规格参数" align="center" prop="specificationParameter" :show-overflow-tooltip="true"/>
        <el-table-column label="常备物料" align="center" prop="alwaysFlag">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_material_bind_flag" :value="scope.row.alwaysFlag"/>
          </template>
        </el-table-column>
        <el-table-column label="订单数" align="center" prop="orderAmount"/>
        <el-table-column label="已绑定数" align="center" prop="boundAmount"/>
        <el-table-column label="安全库存数" align="center" prop="safeAmount"/>
        <el-table-column label="销售订单绑定数" align="center" prop="orderBindAmount"/>
        <el-table-column label="销售订单条码数" align="center" prop="orderBarcodeAmount"/>
        <el-table-column label="更新绑定数" align="center" prop="updateAmount" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.updateAmount" size="mini"/>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="purchaseOrderTotal>0"
        :total="purchaseOrderTotal"
        :page.sync="purchaseOrderQueryParams.pageNum"
        :limit.sync="purchaseOrderQueryParams.pageSize"
        @pagination="getUnbindPurchaseOrderList"
      />
      <!--      </el-col>-->
    </el-row>

  </div>
</template>

<script>
import {
  removeSalesBindPurchase,
  saleBindPurchaseOrderList,
  saveSalesBindPurchase,
  unbindPurchaseOrderList
} from "@/api/mes/purchaseOrder";

export default {
  name: "BindingPurchase",
  dicts: ['mes_material_bind_flag'],
  data() {
    return {
      // 已选采购订单遮罩层
      allocateLoading: true,
      // 可选采购订单遮罩层
      selectableLoading: true,
      submitLoading: false,
      // 已选采购订单选中数组
      orderBindIds: [],
      //可选采购订单信息选中数组
      barcodeInfos: [],
      //可选采购订单ID选中数组
      purchaseOrderIds: [],
      //可选采购订单对象选中数组
      purchaseOrderSelectableList: [],
      // 已选采购订单非单个禁用
      allocateMaterialSingle: true,
      // 已选采购订单非多个禁用
      allocateMaterialMultiple: true,
      // 可选采购订单非单个禁用
      materialSingle: true,
      // 可选采购订单非多个禁用
      materialMultiple: true,
      // 显示搜索条件
      showSearch: true,
      single: true,
      multiple: true,
      // 已选采购订单总条数
      allocatePurchaseOrderTotal: 0,
      //可选采购订单总条数
      purchaseOrderTotal: 0,
      // 已选采购订单信息表格数据
      allocatePurchaseOrderList: [],
      // 可选采购订单信息表格数据
      purchaseOrderList: [],
      // 已选采购订单编号List
      allocatePoNos: [],
      //库位信息
      saleOrderForm: {},
      allocateBarCodeBtnDisable: true,
      // 已选采购订单信息查询参数
      allocatePurchaseOrderQueryParams: {
        pageNum: 1,
        pageSize: 10,
        saleOrderId: null,
        materialCode: null,
        materialName: null,
        poNo: null,
      },
      // 可选采购订单信息查询参数
      purchaseOrderQueryParams: {
        pageNum: 1,
        pageSize: 10,
        saleOrderId: null,
        materialCode: null,
        materialName: null,
        specificationParameter: null,
        alwaysFlag: null,
        poNo: null
      },
    };
  },
  created() {
    this.getUnbindList();
  },
  methods: {
    getUnbindList() {
      const saleOrderId = this.$route.params && this.$route.params.saleOrderId;
      let saleorderCode = this.$route.query && this.$route.query.saleorderCode;
      this.purchaseOrderQueryParams.saleOrderId = saleOrderId;
      this.allocatePurchaseOrderQueryParams.saleOrderId = saleOrderId;

      this.saleOrderForm.saleorderCode = saleorderCode;
      this.saleOrderForm.saleOrderId = saleOrderId;
      this.saleOrderForm.materialId = this.$route.query && this.$route.query.materialId;
      this.saleOrderForm.materialCode = this.$route.query && this.$route.query.materialCode;
      this.saleOrderForm.materialName = this.$route.query && this.$route.query.materialName;
      this.saleOrderForm.materialModel = this.$route.query && this.$route.query.materialModel;
      // this.getAllocatePurchaseOrderList();
      this.getUnbindPurchaseOrderList();
    },

    /** 查询已选采购订单信息列表 */
    getAllocatePurchaseOrderList() {
      this.allocateLoading = true;
      saleBindPurchaseOrderList(this.allocatePurchaseOrderQueryParams).then(response => {
        this.allocatePurchaseOrderList = response.rows;
        this.allocatePurchaseOrderTotal = response.total;
        this.allocateLoading = false;
      });
    },

    /** 查询可选采购订单信息列表 */
    getUnbindPurchaseOrderList() {
      this.selectableLoading = true;
      unbindPurchaseOrderList(this.purchaseOrderQueryParams).then(response => {
        response.rows.forEach(e => {
          let orderBindBarcodeAmount = e.orderBindBarcodeAmount.split("-");
          e.orderBindAmount = parseInt(orderBindBarcodeAmount[0]);
          e.orderBarcodeAmount = parseInt(orderBindBarcodeAmount[1]);
        });

        this.purchaseOrderList = response.rows;
        this.purchaseOrderTotal = response.total;
        this.selectableLoading = false;
      });
    },

    /** 已选采购订单搜索按钮操作 */
    handleAllocateMaterialQuery() {
      this.allocatePurchaseOrderQueryParams.pageNum = 1;
      this.getAllocatePurchaseOrderList();
    },
    getRowStyle({row}) {
      return row.saleBindAmount > 0 ? {backgroundColor: '#8ee38e'} : {};
    },
    /** 已选采购订单重置按钮操作 */
    resetAllocateMaterialQuery() {
      this.resetForm("allocateMaterialQueryForm");
      this.handleAllocateMaterialQuery();
    },
    /** 已选采购订单多选框选中数据 */
    handleAllocateMaterialSelectionChange(selection) {
      this.orderBindIds = selection.map(item => item.orderBindId)
      // this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 可选采购订单搜索按钮操作 */
    handlePurchaseOrderQuery() {
      this.purchaseOrderQueryParams.pageNum = 1;
      this.getUnbindPurchaseOrderList();
    },
    /** 可选采购订单重置按钮操作 */
    resetMaterialQuery() {
      this.resetForm("materialQueryForm");
      this.handlePurchaseOrderQuery();
    },
    // 可选采购订单多选框选中数据
    handleMaterialSelectionChange(selection) {
      this.purchaseOrderIds = selection.map(item => item.purchaseOrderId)
      this.allocatePoNos = selection.map(item => item.poNo)
      this.purchaseOrderSelectableList = selection.map(item => item)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    rowSerialNumberProcess({row, rowIndex}) {
      row.serialNumber = rowIndex + 1;
    },
    handleUnallocateBarCodes() {
      const purchaseOrderIds = this.purchaseOrderIds.join(",");
      const allocatePoNos = this.allocatePoNos;
      const params = {
        saleOrderId: this.saleOrderForm.saleOrderId,
        purchaseOrderIds: purchaseOrderIds,
      }
      this.$modal.confirm('是否确认删除采购订单编号为"' + allocatePoNos + '"的数据项？').then(function () {
        return removeSalesBindPurchase(params);
      }).then(() => {
        // this.getAllocatePurchaseOrderList();
        this.getUnbindPurchaseOrderList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    isPositiveInteger(value) {
      // 使用正则表达式匹配正整数
      return /^[0-9]\d*$/.test(value);
    },

    /** 提交按钮 */
    submitForm() {
      this.submitLoading = true;
      // const purchaseOrderIds = this.purchaseOrderIds.join(",");
      for (let obj of this.purchaseOrderSelectableList) {
        obj.saleOrderId = this.saleOrderForm.saleOrderId;
        const orderAmount = obj.orderAmount ? parseInt(obj.orderAmount) : 0;//采购订单数量
        const boundAmount = obj.boundAmount ? parseInt(obj.boundAmount) : 0;//已绑定总数
        const safeAmount = obj.safeAmount ? parseInt(obj.safeAmount) : 0;//安全库存数
        const orderBindAmount = obj.orderBindAmount ? parseInt(obj.orderBindAmount) : 0;//销售订单已绑定数
        const orderBarcodeAmount = obj.orderBarcodeAmount ? parseInt(obj.orderBarcodeAmount) : 0;//销售订单已生成条码数量

        const updateAmount = obj.updateAmount ? parseInt(obj.updateAmount) : 0;//更新绑定数

        if (!this.isPositiveInteger(updateAmount) || updateAmount <= 0) {
          this.submitLoading = false;
          this.$modal.msgError("序号为" + (obj.serialNumber) + ",绑定数量须为大于0的正整数！");
          return;
        }

        if (updateAmount < orderBarcodeAmount) {
          this.submitLoading = false;
          this.$modal.msgError("序号" + (obj.serialNumber) + "的绑定数量需不能小于销售订单条码数！");
          return;
        }

        // （已绑定总数 + 安全库存数  + 更新绑定数量 - 销售订单已绑定数） 需要小于等于 采购订单数量
        let totalBindAmount = boundAmount + safeAmount + updateAmount - orderBindAmount;
        if (totalBindAmount - orderAmount > 0) {
          this.submitLoading = false;
          this.$modal.msgError("序号" + (obj.serialNumber) + "的总绑定数不能大于订单数!");
          return;
        }
      }

      this.saleOrderForm.mesPurchaseOrderList = this.purchaseOrderSelectableList;

      // console.log(this.saleOrderForm);
      saveSalesBindPurchase(this.saleOrderForm).then((response) => {
        this.$modal.msgSuccess("保存成功");
        this.getUnbindPurchaseOrderList();
        // this.getAllocatePurchaseOrderList();
      }).catch(() => {
        this.getUnbindList();
      }).finally(e => {
        this.submitLoading = false;
      });
    },

  }
};
</script>
