<script>
import {getWareHouseList} from "../../../api/partspare/wareHouseEntity";
import {getAllBuList} from "../../../api/factory/site";
import {getInventoryStockList} from "../../../api/partspare/inventorystock";
import {saveBatchPurchaseOrder} from "../../../api/partspare/purchaseOrder";
import {Decimal} from "decimal.js";

export default {
  name: "inventoryStockPurchasing",
  data(){
    return{
      span:3,
      queryParams: {
        site: this.$store.state.user.site,
        limit: 50,
        page: 1,
        partNo: '',
        partDescription: '',
        spec: '',
        batchNo: '',
        warehouseId: '',
        locationId: '',
        startFirstInDate: '',
        endFirstInDate: '',
        startQtyOnHand: '',
        endQtyOnHand: '',
        groupType: '0',
        active: 'Y',
        safetyStock: '不安全',
        buNo: '',
        securityMethod:'库存和在途',
      },
      buList:[],
      wareHouseList:[],
      dataList: [],
      queryLoading: false,
      total:0,
      columns:[
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1BuDesc',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'buDesc',
          headerAlign: 'center',
          align: 'center',
          columnLabel: 'BU',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1PartNo',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'partNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '备品备件编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1PartDescription',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'partDescription',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '备品备件名称',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 160
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1BatchNo',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'batchNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '序列号',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1WarehouseId',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'warehouseId',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '仓库编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1LocationId',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'locationId',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '货位编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1UmId',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'umid',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '单位',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1QtyOnHand',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'qtyOnHand',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '在库数量',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1MinStock',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'minStock',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '最低库存数量',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1QtyOfPo',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'qtyOfPo',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '在途订单数量',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1PartnerId',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'partnerId',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '操作员',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1FirstInDate',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'firstInDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '录入日期',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 150
        },
      ],
      columns2:[
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1BuDesc',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'buDesc',
          headerAlign: 'center',
          align: 'center',
          columnLabel: 'BU',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1PartNo',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'partNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '备品备件编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1PartDescription',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'partDescription',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '备品备件名称',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 160
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1QtyOnHand',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'qtyOnHand',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '在库数量',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1MinStock',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'minStock',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '最低库存数量',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101106,
          serialNumber: '200101106Table1QtyOfPo',
          tableId: '200101106Table1',
          tableName: '备品备件采购表',
          columnProp: 'qtyOfPo',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '在途订单数量',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100
        },
      ],
      selectionDataList:[],
      purchaseVisible:false,
      purchaseLoading:false,
    }
  },
  methods:{
    handleQuery(){
      this.queryLoading = true
      getInventoryStockList(this.queryParams).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.total = data.page.totalCount
        } else {
          this.dataList = []
          this.total = 0
        }
        this.queryLoading = false
      }).catch((error)=>{
        this.$message.error(error)
        this.queryLoading = false
      })
    },
    getWareHouseList(){
      let wareHouse = {
        site: this.$store.state.user.site,
        active: 'Y',
        warehousetype: "备品备件仓",
      }
      getWareHouseList(wareHouse).then(({data}) =>{
        if (data && data.code === 0){
          this.wareHouseList = data.data
        }
      })
    },
    getBuList() {
      let tempData = {
        username: this.$store.state.user.name,
      }
      getAllBuList(tempData).then(({data}) => {
        if (data && data.code === 0) {
          this.buList = data.rows
        }
      })
    },
    handleQueryBySize(val){
      this.queryParams.limit = val
      this.handleQuery()
    },
    handleQueryByPage(val){
      this.queryParams.page = val
      this.handleQuery()
    },
    rowStyle({row}){
      // 当前行在库数量
      let qtyOnHand = row.qtyOnHand
      // 当前行最低库存数量
      let minStock = row.minStock
      // 在途数量
      let qtyOfPo = row.qtyOfPo
      // 累计数量
      if (this.queryParams.securityMethod === '库存和在途'){
        qtyOnHand += qtyOfPo
      }

      // 区分不同的样式对应不同的颜色
      if (qtyOnHand <= minStock) {
        return { 'background-color': '#D8ECF1', cursor: 'pointer' }
      }
    },
    handleSelectionChange(val) {
      let qty = 0;
      this.selectionDataList = val.map(item => {
        if (new Decimal(item.minStock).toNumber() > new Decimal(item.qtyOnHand).toNumber()){
          qty = new Decimal(item.minStock).sub(new Decimal(item.qtyOnHand)).toNumber()
        }
        return {
          ...item,
          purchaseQty: qty,
        }
      });
    },
    handlePurchase(){
      if (this.selectionDataList.length === 0) {
        this.$message.warning('请选择需要采购的备件')
        return
      }
      this.purchaseVisible = true
    },
    handlePurchaseSave(){
      let params = this.selectionDataList.map((item)=>{
        return {
          ...item,
          buNo:item.citemCode,
          inventoryStockId: item.id,
          id:null,
          qty: item.purchaseQty,
        }
      })
      this.purchaseLoading = true
      saveBatchPurchaseOrder(params).then(({data})=>{
        if (data && data.code === 0) {
          this.handleQuery();
          this.$refs.table.clearSelection();
          this.purchaseVisible = false;
          this.$message.success(data.msg)
        }else {
          this.$message.error(data.msg)
        }
        this.purchaseLoading = false
      }).catch((error)=>{
        this.$message.error(error)
        this.purchaseLoading = false
      })
    }

  },
  watch:{
    queryLoading(newVal, oldVal){
      if (newVal === true){
        setTimeout(()=>{
          this.queryLoading = false
        },3000)
      }
    },
    purchaseLoading(newVal, oldVal){
      if (newVal === true){
        setTimeout(()=>{
          this.purchaseLoading = false
        },3000)
      }
    }
  },
  created() {
    this.getBuList()
    this.getWareHouseList()
    this.handleQuery()
  },
}
</script>

<template>
  <div class="box-container">
    <el-form label-position="top" :model="queryParams" style="max-width: 1200px">
      <el-row :gutter="10">
        <el-col :span="span">
          <el-form-item label="备品备件编码">
            <el-input v-model="queryParams.partNo" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="备品备件名称">
            <el-input v-model="queryParams.partDescription" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="规格型号">
            <el-input v-model="queryParams.spec" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="序列号">
            <el-input v-model="queryParams.batchNo" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="仓库">
            <el-select v-model="queryParams.warehouseId" style="width: 100%">
              <el-option value="" label="全部"></el-option>
              <el-option v-for="(item,index) in wareHouseList "
                         :key="item.warehouseId" :value="item.warehouseId" :label="item.warehouseName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="汇总方式">
            <el-select v-model="queryParams.groupType" style="width: 100%">
              <el-option value="0" label="料号+序号"></el-option>
              <el-option value="1" label="料号"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="span*2">
          <el-form-item label=" ">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button type="primary" @click="handlePurchase">采购</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="span*2">
          <el-form-item label="录入日期">
            <el-date-picker
              style="width: 47.5%"
              v-model="queryParams.startFirstInDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
            <span style="text-align: center">-</span>
            <el-date-picker
              style="width: 47.5%"
              v-model="queryParams.endFirstInDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd 23:59:59"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="span*2">
          <el-form-item label="在库数量范围">
            <el-input  style="width: 47.5%" v-model="queryParams.startQtyOnHand" clearable></el-input>
            <span style="text-align: center">-</span>
            <el-input  style="width: 47.5%" v-model="queryParams.endQtyOnHand" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="货位编码">
            <el-input  v-model="queryParams.startQtyOnHand" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="BU">
            <el-select v-model="queryParams.buNo" placeholder="请选择"  style="width: 100%">
              <el-option label="全部" value=""> </el-option>
              <el-option
                v-for = "i in buList"
                :key = "i.buNo"
                :label = "i.buDesc"
                :value = "i.buNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="安全库存汇总方式">
            <el-select v-model="queryParams.securityMethod" style="width: 100%">
              <el-option label="库存数量" value="库存"></el-option>
              <el-option label="(库存+在途)数量" value="库存和在途"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label=" ">
            <el-checkbox v-model="queryParams.safetyStock" true-label="不安全" false-label="" @change="handleQuery">仅显示低于安全库存的备件</el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="height: calc(100% - 120px)">
      <el-table :data="dataList" border
                height="100%" ref="table"
                v-loading="queryLoading"
                :row-style="rowStyle"
                @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50">
        </el-table-column>
        <el-table-column
          v-for="(item,index) in columns" :key="index"
          :sortable="item.columnSortable"
          :prop="item.columnProp"
          :header-align="item.headerAlign"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :align="item.align"
          :fixed="item.fixed===''?false:item.fixed"
          :min-width="item.columnWidth"
          :label="item.columnLabel">
          <template slot-scope="scope">
            <span v-if="!item.columnHidden">{{ scope.row[item.columnProp] }}</span>
            <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      style="margin-top: 5px"
      @size-change="handleQueryBySize"
      @current-change="handleQueryByPage"
      :current-page="queryParams.page"
      :page-sizes="[50, 100, 500, 1000]"
      :page-size="queryParams.limit"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>



    <el-dialog :visible.sync="purchaseVisible" title="待创建采购订单备件清单" :close-on-click-modal="false" width="1000px" v-drag>
      <div class="rq">
        <el-table :data="selectionDataList" border height="400px">
          <el-table-column
            v-for="(item,index) in columns2" :key="index"
            :sortable="item.columnSortable"
            :prop="item.columnProp"
            :header-align="item.headerAlign"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :align="item.align"
            :fixed="item.fixed===''?false:item.fixed"
            :min-width="item.columnWidth"
            :label="item.columnLabel">
            <template slot-scope="scope">
              <span v-if="!item.columnHidden">{{ scope.row[item.columnProp] }}</span>
              <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
            </template>
          </el-table-column>
          <el-table-column label="采购数量" align="center" min-width="100">
            <template slot-scope="{row,$index}">
              <el-input-number style="width: 100%;" :min="0" :controls="false" :step="0" v-model="selectionDataList[$index].purchaseQty"></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer style="text-align: center;line-height: 1;height: 30px;margin-top: 10px">
        <el-button type="primary" :loading="purchaseLoading" @click="handlePurchaseSave">保存</el-button>
        <el-button type="primary" @click="purchaseVisible = false">关闭</el-button>
      </el-footer>
    </el-dialog>
  </div>
</template>

<style scoped>
</style>
