<!-- 供应商---生产入库 -->
<template>
  <div class="main-container order-mc-bg">
    <div class="sale-container">
      <!-- 顶部按钮组 -->
      <toolBtn :btnType="btnType" @actionhandel="actionhandel"></toolBtn>
      <!-- 列表 -->
      <div class="sale-page-body">
        <!-- 表头 -->
        <div class="sale-page-table-header" ref="getSaleTableHeader">
          <el-form :inline="true">
            <el-row class="form-row1">
              <el-col :span="20">
                <el-row :gutter="2">
                  <el-col :span="4">
                    <el-form-item class="Iisshow" label="采购订单号">
                      <el-input class="f-12" placeholder="请输入采购订单号" v-model.trim="search.billNo"></el-input>
                      <div :data-clipboard-text="search.billNo" @click="saleOrderCopy" class="copyBtn">
                        <i class="el-icon-document-copy" />
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item class="Iisshow" label="产品">
                      <el-input class="f-12" placeholder="请输入物料名称/编码/SKU" v-model.trim="search.productKey"></el-input>
                      <div :data-clipboard-text="search.productKey" @click="saleOrderCopy" class="copyBtn">
                        <i class="el-icon-document-copy" />
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="入库日期">
                      <el-date-picker @change="time1Chang" class="f-12" end-placeholder="结束时间" start-placeholder="开始时间"
                        type="daterange" v-model="Time1" value-format="YYYY-MM-DD"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="4" class="form-row-lastcol">
                <el-row :gutter="2">
                  <el-col :span="24">
                    <el-form-item class="form-group1">
                      <el-button @click="resetSearch" size="small" type="primary">重置</el-button>
                      <el-button @click="searchData" size="small" type="primary">搜索</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <!-- 列表 -->
        <div class="sale-page-table-body">
          <el-table :data="tableData" :header-cell-class-name="headerRigthMethod" :max-height="heightNum"
            @selection-change="handleSelectionChange" border class="table-box" element-loading-spinner="el-icon-loading"
            element-loading-text="加载中，请稍后..." ref="tableInfoRef" style="width: 100%;font-size:12px"
            v-loading="isLoading">
            <el-table-column align="center" type="selection" width="40" />
            <el-table-column align="left" label="采购组织" prop="purchaseOrgName" width="250"></el-table-column>
            <el-table-column align="left" label="备料/采购订单号" prop="purchaseBillNo" width="160"></el-table-column>
            <el-table-column align="left" label="物料编码" prop="materialNumber" width="200" />
            <el-table-column align="left" label="规格型号(SKU)" prop="specification" width="280" />
            <el-table-column align="left" label="物料名称" prop="materialName" width="280" />
            <el-table-column align="right" label="采购数量" prop="purchaseQty" width="120" />
            <el-table-column align="right" label="生产入库数量" prop="qty" width="100" />
            <el-table-column align="left" label="入库日期" prop="date" width="110"></el-table-column>
            <el-table-column align="left" label="供应商" prop="supplierName" />
          </el-table>
        </div>
      </div>
      <!-- 底部 -->
      <div class="sale-page-footer">
        <div class="footer-left">
          <div>
            <span>采购数量:</span>
            <span class="sale-number-color">{{ purchaseQtyTotal }}</span>
          </div>
          <div>
            <span>生产入库数量:</span>
            <span class="sale-number-color">{{ qtyTotal }}</span>
          </div>
        </div>
        <div class="footer-right">
          <el-pagination :currentPage="search.pageNo" :page-size="search.pageSize" :page-sizes="[50, 100, 150]"
            :total="orderTotal" @current-change="handleCurrentChange" @size-change="handleSizeChange"
            layout="slot,sizes, total,prev,pager, next,jumper" popper-class="每页显示">
            <span class="total-select-item">
              共选中
              <text style="text-align:center;color:#4178D5;padding:0 1px;">{{
                multipleSelection?
              multipleSelection.length : 0
              }}</text>行
            </span>
          </el-pagination>
        </div>
        <div class="footer-pagination-total-page">
          <span>共{{ Math.ceil(orderTotal / search.pageSize) }}页</span>
        </div>
      </div>
    </div>
    <!-- 操作结果 -->
    <el-dialog :title="modelTitle" v-model="dialogVisible" width="75%">
      <div class="sale-page-table-body">
        <el-table :data="tableInfo.slice((modelPageNo - 1) * 10, modelPageNo * 10)"
          :header-cell-class-name="headerRigthMethod" border class="table-box" id="tableInfo-table"
          @cell-click="getRowCol" :cell-class-name="tableCellClassName" max-height="600">
          <el-table-column label="采购组织" prop="purchaseOrgName" width="200"></el-table-column>
          <el-table-column label="采购订单号" prop="purchaseBillNo" width="200"></el-table-column>
          <el-table-column label="物料编码" prop="materialNumber" width="180"></el-table-column>
          <el-table-column label="物料名称" prop="materialName" width="250"></el-table-column>
          <el-table-column label="规格型号" prop="specification"></el-table-column>
          <el-table-column prop="qty" width="150">
            <template #header>
              <span class="iconfont icon-bianji1 iconfont-mg"></span>入库数量
            </template>
            <template #default="scope">
              <el-input :maxlength="11" v-if="scope.row.isqty" :id="'qty' + scope.$index"
                @blur="numberChage(scope.row.qty, scope.$index, scope.row, 'qty')" v-model="scope.row.qty"></el-input>
              <span v-else>{{ scope.row.qty }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div style="display:flex;justify-content: space-between;">
          <span class="dialog-footer">
            <!-- <el-button @click="handelhtmlToExcel('tableInfo-table',modelTitle);dialogVisible = false">导出</el-button> -->
            <el-button @click="dialogVisible = false" size="small" type="primary">关 闭</el-button>
            <!-- <el-button size="small" @click="dialogVisible = false">打印</el-button> -->
          </span>
          <span class="dialog-footer" style=" display: flex;align-items: center;">
            <el-pagination :currentPage="modelPageNo" :page-size="10" :total="tableInfo.length"
              @current-change="modelPageNoChange" layout="prev, pager, next, jumper,total" size="small"
              v-if="tableInfo.length > 10"></el-pagination>
            <span class="f-12 ext-black-light" style="margin-right: 25px;">共{{ tableInfo && tableInfo.length > 0 ?
              tableInfo.length : 0
            }}条</span>
            <el-button @click="modeMakeSure" size="small" type="primary">确认生产入库</el-button>
          </span>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { countMethodsUnitNumber } from '@/utils/count.js'
import { orderCopy } from '@/utils/takeMethods'
import { transformTimestamp, htmlToExcel, exporthandel } from '@/utils/pubulic.js'
export default {
  name: 'SupplierCoordinationWarehouse',
  data () {
    return {
      salePrecisionNumber: [],
      isPrecision: [],
      isCount: [],
      modelTitle: '生产入库调整', // 弹框标题
      modelPageNo: 1, // 确认弹框的分页
      OrdedetailIds: [], // 勾选的明细id集合
      OrderNoNames: [], // 选择的单据订单号集合
      multipleSelection: [], // 列表选中
      actionType: '', //判断点击的顶部那个按钮
      tableInfo: [], //操作结果
      isLoading: false, //表格加载数据
      btnType: ['s-p-t-g1', 's-p-t-g2', 'audit', 'de-approval', 'de-approval', 's-p-t-g4', 'out-export', 'daochu', 'setIntoNum'], // 不需要显示的顶部按钮类型
      Time1: [],
      dialogVisible: false, // 操作弹框显示
      // 搜索条件
      search: {
        orgId: '', // 组织ID
        billNo: '', // 采购订单号
        productKey: '', //产品 物料名称/编码/SKU
        beginDate: '', // 下单开始日期
        endDate: '', //下单结束日期
        pageNo: 1, // 页码
        pageSize: 50 // 页数
      },
      purchaseQtyTotal: 0, //采购数量
      qtyTotal: 0, //生产入库数量
      orderTotal: 0, // 未入库数量统计
      tableData: [],
      selectItem: 0,
      rowShow: false,
      heightNum: 0,
      windowHeight: 0,
      isDown: true
    }
  },
  computed: {
    ...mapState({
      userInfo: state => (state && state.user && state.user.userInfo ? state.user.userInfo : {}),
      orgId: state => (state && state.org && state.org.orgId ? state.org.orgId : null)
    }),
    transformTime: function () {
      return function (value) {
        return transformTimestamp(value)
      }
    }
  },
  created () {
    this.windowHeight = document.documentElement.clientHeight
    this.heightNum = this.windowHeight - (40 + 30 + 54 + 34 + 34 + 34 + 16 + 16)
    this.search.orgId = this.userInfo.identity === 2 ? 0 : this.orgId
    this.Init()
  },
  activated () {
    // 键盘监听事件
    document.addEventListener('keyup', this.keyupFn, false)
  },
  deactivated () {
    document.removeEventListener('keyup', this.keyupFn, false)
  },
  watch: {
    orgId (val) {
      if (val) {
        this.search.orgId = this.userInfo.identity === 2 ? 0 : val
        this.getWarehouselist()
      }
    }
  },
  mounted () { },
  methods: {
    keyupFn (e) {
      if (e.keyCode === 13) {
        // enter见搜索
        this.searchData()
      }
    },
    // 初始
    Init () {
      this.getWarehouselist()
      this.getUnit()
    },
    //注意这里是解构
    tableCellClassName ({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex
      column.index = columnIndex
    },
    getRowCol (row, column, cell, event) {
      // 处理表格下拉框输入框显示隐藏
      this.tableInfo.forEach((it, index) => {
        Object.assign(it, { isqty: false })
      })
      var showtagarry = ['isqty']
      var parentshowtagarry = ['qty']
      showtagarry.forEach((k, idx) => {
        if (column.property == parentshowtagarry[idx]) {
          this.tableInfo[row.index][k] = true
          this.$nextTick(_ => {
            if (document.getElementById(column.property + row.index)) {
              document.getElementById(column.property + row.index).focus()
            }
          })
        }
      })
    },
    // 获取计量单位
    getUnit () {
      this.$http.get('SysConfig/GetUnitAllProperty').then(r => {
        if (r.status === 200) {
          this.unitData = r.data
        }
      })
    },
    numberPrecisionMethods (index, unit, S, P, C, type) {
      if (type || this.tableInfo[index][unit]) {
        var thetempList = []
        if (type) {
          thetempList = this.unitData.filter(it => it.id === this.form.unitId)
        } else {
          thetempList = this.unitData.filter(it => it.id === this.tableInfo[index][unit])
        }
        thetempList[0].precision == 0 ? (this[P][index] = true) : (this[P][index] = false)
        thetempList[0].precision == 0 ? (this[S][index] = 0) : (this[S][index] = thetempList[0].precision)
      }
      this[P][index] = this[P][index] ? this[P][index] : false
      this[S][index] = this[S][index] || this[S][index] == 0 ? this[S][index] : 10
      if (!this[C][index]) {
        this[C][index] = 1
      }
    },
    // 数量改变时
    numberChage (val, index, item, key) {
      const _this = this
      // 判断条件 单位
      this.numberPrecisionMethods(index, 'unitId', 'salePrecisionNumber', 'isPrecision', 'isCount')
      if (val) {
        if (_this.isPrecision[index]) {
          if (val.toString().indexOf('.') !== -1 && _this.salePrecisionNumber[index] != 0) {
            _this.tableInfo[index][key] = Number(val).toFixed(0)
          }
          _this.tableInfo[index][key] = _this.tableInfo[index][key].toString().replace(/\D/g, '')
        } else {
          if (val.toString().indexOf('.') !== -1) {
            let tempList = _this.unitData.filter(it => it.id === _this.tableInfo[index].unitId)
            if (tempList && tempList.length > 0) {
              tempList[0].roundoffType = 2
            }
            let result = countMethodsUnitNumber(
              tempList,
              val,
              _this.tableInfo[index][key],
              _this.isCount[index],
              _this.salePrecisionNumber[index],
              true
            )
            _this.tableInfo[index][key] = result.value
            _this.isCount[index] = result.isDefault
          }

          let numD = ''
          let count = '\\d'
          for (let ind = 0; ind < _this.salePrecisionNumber[index]; ind++) {
            numD = numD + count
          }
          let reg = '/^(-)*(\\d+)\\.(' + numD + ').*$/'
          _this.tableInfo[index][key] = _this.tableInfo[index][key]
            .toString()
            .replace(/[^\d^\\.]+/g, '')
            .replace('.', '$#$')
            .replace(/\./g, '')
            .replace('$#$', '.')
            .replace(eval(reg), '$1$2.$3')
        }
      }
      let tempList = _this.unitData.filter(it => it.id === _this.tableInfo[index].unitId)
      let result = countMethodsUnitNumber(
        tempList,
        _this.tableInfo[index][key],
        _this.tableInfo[index][key],
        _this.isCount[index],
        _this.salePrecisionNumber[index],
        true
      )
      _this.tableInfo[index][key] = result.value
      _this.isCount[index] = result.isDefault
    },
    // 重置
    resetSearch () {
      this.search = {
        orgId: this.userInfo.identity === 2 ? 0 : this.orgId, // 组织ID
        billNo: '', // 采购订单号
        productKey: '', //产品 物料名称/编码/SKU
        beginDate: '', // 下单开始日期
        endDate: '', //下单结束日期
        pageNo: 1, // 页码
        pageSize: 50 // 页数
      }
      this.Time1 = []
      this.getWarehouselist()
    },
    // 操作弹框导出
    handelhtmlToExcel (domid, title) {
      htmlToExcel(domid, title)
    },
    // 订单号 复制按钮
    saleOrderCopy () {
      orderCopy()
    },
    // 确认弹框
    modeMakeSure () {
      let idsarry = []
      this.tableInfo.forEach(it => {
        if (it.qty || it.qty == 0) {
          idsarry.push({
            id: it.id,
            qty: it.qty
          })
        }
      })
      if (idsarry.length > 0) {
        this.$http.post('SupplierProduceInstock/instock', { data: idsarry }).then(res => {
          if (res.status === 200) {
            this.dialogVisible = false
            this.search.pageNo = 1
            this.getWarehouselist()
            this.$message.success({ message: '确认成功', showClose: true })
          }
        })
      } else {
        this.$message.error({ message: '请输入库数量在确认', showClose: true })
      }

      this.dialogVisible = false
    },
    // 搜索切换高度
    openRow () {
      this.isDown = !this.isDown
      this.rowShow = !this.rowShow
      if (this.rowShow) {
        this.heightNum = this.heightNum - 80
      } else {
        this.heightNum = this.heightNum + 80
      }
    },
    // 获取订单数据
    getWarehouselist () {
      this.isLoading = true
      this.$http.post('SupplierProduceInstock/list', this.search).then(res => {
        if (res.status === 200) {
          this.isLoading = false
          this.tableData = res.data.list
          this.orderTotal = res.data.totalCount
          this.purchaseQtyTotal = res.data.purchaseQtyTotal
          this.qtyTotal = res.data.qtyTotal
        }
      })
    },
    // 顶部公共按钮操作
    actionhandel (type) {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        // 删除
        if (type === 'delet') {
          let table = []
          this.multipleSelection.forEach(it => {
            table.push(it.id)
          })
          this.$http.post('SupplierProduceInstock/delete', { ids: table }).then(res => {
            if (res.status === 200) {
              this.search.pageNo = 1
              this.getWarehouselist()
              this.$message.success({ message: '删除成功', showClose: true })
            }
          })
        }
        // 调整入库数量
        if (type === 'setIntoNum') {
          this.dialogVisible = true
          this.tableInfo = JSON.parse(JSON.stringify(this.multipleSelection))
        }
        // 调整入库数量
        if (type === 'setIntoNum') {
          this.dialogVisible = true
          this.tableInfo = JSON.parse(JSON.stringify(this.multipleSelection))
        }
      } else {
        if (type !== 'add' && type !== 'refresh' && type !== 'out-export') {
          this.$message.error({ message: '请先勾选', showClose: true })
        }
      }
      // 导出
      if (type === 'out-export') {
        exporthandel('SupplierProduceInstock/Export', this.search)
      }
      // 点击刷新
      if (type === 'refresh') {
        this.getWarehouselist()
      }
    },
    // 下单日期改变
    time1Chang (value) {
      if (value && value.length > 0) {
        this.search.beginDate = value[0]
        this.search.endDate = value[1]
      } else {
        this.search.beginDate = ''
        this.search.endDate = ''
      }
    },
    // 搜索事件
    searchData () {
      this.search.pageNo = 1
      this.getWarehouselist()
    },
    headerRigthMethod ({ row, column, rowIndex, columnIndex }) {
      return 'headerRight'
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleSizeChange (val) {
      this.search.pageNo = 1
      this.search.pageSize = val
      this.Init()
    },
    handleCurrentChange (val) {
      this.search.pageNo = val
      this.Init()
    },
    modelPageNoChange (val) {
      this.modelPageNo = val
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/style/saleOrder/saleOrderCommon.scss';
@import '@/assets/style/saleOrder/orderList.scss';
@import '@/assets/style/saleOrder/common.scss';
</style>