<!-- 供应商---供应商库存管理 -->
<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" v-if="userInfo.identity !== 2">
                    <el-form-item label="供应商">
                      <el-select clearable filterable placeholder="请选择" v-model="search.supplierId">
                        <el-option :key="item.code" :label="item.name" :value="item.id" class="f-12"
                          v-for="item in supplierlist"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item class="Iisshow" label="产品">
                      <el-input class="f-12" placeholder="请输入物料名称/编码/SKU" style="width:200px"
                        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="显示库存数量为0的物料">
                      <el-select placeholder="请选择" v-model="search.isShow">
                        <el-option :value="true" label="是"></el-option>
                        <el-option :value="false" label="否"></el-option>
                      </el-select>
                    </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 size="small" @click="resetSearch">重置</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="materialNumber" width="200" />
            <el-table-column align="left" label="规格型号(SKU)" prop="specification" />
            <el-table-column align="left" label="物料名称" prop="materialName" />
            <el-table-column align="right" label="数量" prop="qty" width="120" />
            <el-table-column align="center" label="单位" prop="unitName" width="100" />
            <el-table-column align="left" label="供应商" prop="supplierName"></el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 底部 -->
      <div class="sale-page-footer">
        <div class="footer-left">
          <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" :width="actionType !== 'addMaterial' ? '75%' : '25%'" v-model="dialogVisible">
      <div class="sale-page-table-body" v-if="actionType == 'adjustInventory'">
        <el-table :data="tableInfo.slice((modelPageNo - 1) * 10, modelPageNo * 10)"
          :header-cell-class-name="headerRigthMethod" border @cell-click="getRowCol"
          :cell-class-name="tableCellClassName" class="table-box" max-height="600">
          <el-table-column label="物料编码" prop="materialNumber" width="200"></el-table-column>
          <el-table-column label="物料名称" prop="materialName"></el-table-column>
          <el-table-column label="规格型号" prop="specification"></el-table-column>
          <el-table-column label="即时库存" prop="realStock" width="150"></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-column label="操作" width="100">
            <template #default="scope">
              <span @click="colDelet(scope.row, scope.$index)" class="text-red">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加物料-->
      <div class="sale-page-table-body base-info-form-box f-12" v-if="actionType == 'addMaterial'">
        <el-form :model="form" label-width="150px" ref="form">
          <el-form-item class="f-12 zp" label="采购组织" label-width="150px">
            <el-select style="width: 202px;" @change="orgChange" filterable placeholder="请选择组织"
              v-model="form.purchaseOrgId">
              <el-option :key="item.name" :label="item.name" :value="item.id" class="f-12" v-for="item in orgIdArr">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="f-12" label="物料编码" label-width="150px">
            <el-select :loading="loading" :remote-method="matterCodeChange" @change="metterChange" class="input-wid"
              filterable id="tableInfo-table" placeholder="请输入关键词" remote reserve-keyword v-model="form.materialId">
              <el-option :key="item.id + item.number" :label="item.number" :value="item.id"
                v-for="item in matterCodelist"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="f-12" label="物料名称" label-width="150px">
            <el-input class="input-wid" disabled v-model.trim="form.materialName"></el-input>
          </el-form-item>
          <el-form-item class="f-12" label="规格型号(SKU)" label-width="150px">
            <el-input class="input-wid" disabled v-model.trim="form.specifications"></el-input>
          </el-form-item>
          <el-form-item class="f-12" label="即时库存" label-width="150px">
            <el-input class="input-wid" disabled v-model.trim="form.realStock"></el-input>
          </el-form-item>
          <el-form-item class="f-12" label="入库数量" label-width="150px">
            <el-input class="input-wid" @blur="numberChage1(form.qty, 0, null, 'qty')" v-model="form.qty"
              :disabled="!form.materialName"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div style="display:flex;justify-content: space-between;" v-if="actionType !== 'addMaterial'">
          <span class="dialog-footer">
            <!-- <el-button @click="handelhtmlToExcel('tableInfo-table',modelTitle);dialogVisible = false" size="small">导出</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>
            <el-button @click="modeMakeSure" size="small" type="primary" v-if="tableInfo.length > 0">确认</el-button>
          </span>
        </div>
        <div v-else>
          <el-button @click="modeMakeSure('addMaterial')" size="small" type="primary">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { countMethodsUnitNumber } from '@/utils/count.js'
import { transformTimestamp, exporthandel, htmlToExcel } from '@/utils/pubulic.js'
import { orderCopy } from '@/utils/takeMethods'
export default {
  name: 'SupplierCoordinationInventoryManage',
  data () {
    return {
      salePrecisionNumber: [],
      isPrecision: [],
      isCount: [],
      form: { purchaseOrgId: '', materialId: '', unitId: '', qty: '', realStock: null, specifications: '', materialName: '' },
      matterCodelist: [], //物料编码下拉数据
      loading: false,
      supplierlist: [], // 供应商下拉数据
      modelTitle: '', // 弹框标题
      modelPageNo: 1, // 确认弹框的分页
      multipleSelection: [], // 列表选中
      actionType: '', //判断点击的顶部那个按钮
      tableInfo: [], //操作结果
      isLoading: false, //表格加载数据
      btnType: [
        's-p-t-g1',
        's-p-t-g2',
        's-p-t-g3',
        's-p-t-g8',
        's-p-t-g4',
        's-p-t-g11',
        's-p-t-g12',
        'dayin',
        'adjustInventory',
        'addMaterial'
      ], // 不需要显示的顶部按钮类型
      Time1: [],
      dialogVisible: false, // 操作弹框显示
      // 搜索条件
      search: {
        orgId: '', // 组织ID
        isShow: false, //显示库存数量为0的
        productKey: '', //产品 物料名称/编码/SKU
        pageNo: 1, // 页码
        pageSize: 50 // 页数
      },
      qtyTotal: 0, //数量
      orderTotal: 0,
      tableData: [],
      selectItem: 0,
      rowShow: false,
      heightNum: 0,
      windowHeight: 0,
      unitData: [],
      isDown: true
    }
  },
  computed: {
    ...mapState({
      userInfo: state => (state && state.user && state.user.userInfo ? state.user.userInfo : {}),
      orgIdArr: state => (state ? state.user.orgIdArr : null),
      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.getInventoryManage()
      }
    }
  },
  methods: {
    keyupFn (e) {
      if (e.keyCode === 13) {
        // enter见搜索
        this.searchData()
      }
    },
    // 初始
    Init () {
      this.getInventoryManage()
      this.getsupplierList()
      this.getUnit()
    },
    // 重置
    resetSearch () {
      this.search = {
        orgId: this.userInfo.identity === 2 ? 0 : this.orgId, // 组织ID
        isShow: false, //显示库存数量为0的
        productKey: '', //产品 物料名称/编码/SKU
        pageNo: 1, // 页码
        pageSize: 50 // 页数
      }
      this.getInventoryManage()
    },
    //注意这里是解构
    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()
            }
          })
        }
      })
    },
    orgChange (val) {
      this.form.purchaseOrgId = val
      this.form.materialId = ''
      this.form.qty = ''
      this.form.unitId = ''

      console.log(val)
    },
    // 获取计量单位
    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
      }
    },
    numberChage1 (val, index, item, key) {
      const _this = this
      this.numberPrecisionMethods(index, 'unitId', 'salePrecisionNumber', 'isPrecision', 'isCount', 'addtype')
      // 判断条件 单位
      if (val) {
        if (_this.isPrecision[index]) {
          if (val.toString().indexOf('.') !== -1 && _this.salePrecisionNumber[index] != 0) {
            _this.form.qty = Number(val).toFixed(0)
          }
          _this.form.qty = _this.form.qty.toString().replace(/\D/g, '')
        } else {
          if (val.toString().indexOf('.') !== -1) {
            let tempList = _this.unitData.filter(it => it.id === _this.form.unitId)
            if (tempList && tempList.length > 0) {
              tempList[0].roundoffType = 2
            }
            let result = countMethodsUnitNumber(
              tempList,
              val,
              _this.form.qty,
              _this.isCount[index],
              _this.salePrecisionNumber[index]
            )
            _this.form.qty = 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.form.qty = _this.form.qty
            .toString()
            .replace(/[^\d^\\.]+/g, '')
            .replace('.', '$#$')
            .replace(/\./g, '')
            .replace('$#$', '.')
            .replace(eval(reg), '$1$2.$3')
        }
      }
      let tempList = _this.unitData.filter(it => it.id === _this.form.unitId)
      let result = countMethodsUnitNumber(
        tempList,
        _this.form.qty,
        _this.form.qty,
        _this.isCount[index],
        _this.salePrecisionNumber[index],
        true
      )
      _this.form.qty = result.value
      _this.isCount[index] = result.isDefault
    },
    // 数量改变时
    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
    },
    // 订单号 复制按钮
    saleOrderCopy () {
      orderCopy()
    },
    // 操作弹框导出
    handelhtmlToExcel (domid, title) {
      htmlToExcel(domid, title)
    },
    // 物料/规格型号--下拉更新
    metterChange (val, index, type) {
      let metterInfo = {}
      //物料
      metterInfo = this.matterCodelist.filter(res => {
        return val === res.id
      })[0]
      this.form.materialName = metterInfo.name
      this.form.specifications = metterInfo.name = metterInfo.specifications

      this.form.unitId = metterInfo.name = metterInfo.baseUnitId
      // 还要加一个获取即时库存数量的接口
      this.$http.post('SupplierInventory/qty', { materialId: val, orgId: this.form.purchaseOrgId }).then(res => {
        if (res.status === 200) {
          this.form.realStock = res.data
          console.log('获取即时库存')
        }
      })
    },
    // 获取物料编码信息
    matterCodeChange (val) {
      if (val !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.$http
            .showLoading(false)
            .post('SysConfig/GetMaterial', { name: val, file: 'Number', orgId: this.orgId })
            .then(res => {
              if (res.status === 200) {
                this.matterCodelist = res.data
              }
            })
        }, 200)
      } else {
        this.matterCodelist = []
      }
    },
    // 调整库存删除
    colDelet (it, index) {
      this.tableInfo.splice(index, 1)
    },
    // 获取供应商-下拉列表
    getsupplierList () {
      this.$http.get('SysConfig/supplier/select').then(r => {
        if (r.status === 200) {
          this.supplierlist = r.data
        }
      })
    },
    // 确认弹框
    modeMakeSure (type) {
      let newform = {}
      newform = {
        purchaseOrgId: this.form.purchaseOrgId,
        materialId: this.form.materialId,
        unitId: this.form.unitId,
        qty: this.form.qty ? this.form.qty : 0
      }
      let arr = []
      this.tableInfo.forEach(it => {
        if (it.qty || it.qty == 0) {
          arr.push({
            id: it.id,
            inQty: it.qty ? it.qty : 0
          })
        }
      })
      // 确认库存
      if (arr.length > 0 && type !== 'addMaterial') {
        this.$http.post('SupplierInventory/adjust', { data: arr }).then(res => {
          if (res.status === 200) {
            this.search.pageNo = 1
            this.dialogVisible = false
            this.getInventoryManage()
            // this.$refs.splitmultipleTable.clearSelection()
            this.$message.success({ message: '确认成功', showClose: true })
          }
        })
      } else {
        if (arr.length === 0 && type !== 'addMaterial') {
          this.$message.error({ message: '没有数据可以确认，请确认是否信息完整，有填写入库数量', showClose: true })
        }
      }
      if (type === 'addMaterial') {
        // 确认添加物料
        this.$http.post('SupplierInventory/add', newform).then(res => {
          if (res.status === 200) {
            this.dialogVisible = false
            this.search.pageNo = 1
            this.getInventoryManage()
            this.$message.success({ message: '添加成功', showClose: true })
          }
        })
      }
    },
    // 搜索切换高度
    openRow () {
      this.isDown = !this.isDown
      this.rowShow = !this.rowShow
      if (this.rowShow) {
        this.heightNum = this.heightNum - 80
      } else {
        this.heightNum = this.heightNum + 80
      }
    },
    // 获取订单数据
    getInventoryManage () {
      this.isLoading = true
      this.$http.post('SupplierInventory/list', this.search).then(res => {
        if (res.status === 200) {
          this.isLoading = false
          this.tableData = res.data.list
          this.orderTotal = res.data.totalCount
          this.qtyTotal = res.data.qtyTotal
        }
      })
    },
    // 顶部公共按钮操作
    actionhandel (type) {
      this.actionType = type
      //添加物料
      if (type === 'addMaterial') {
        this.modelTitle = '添加物料'
        this.dialogVisible = true
        this.form = {}
      }
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        // 库存调整
        if (type === 'adjustInventory') {
          this.modelTitle = '库存调整'
          this.multipleSelection.forEach((it, index) => {
            this.$http.post('SupplierInventory/qty', { materialId: it.materialId, orgId: it.purchaseOrgId }).then(res => {
              if (res.status === 200) {
                this.multipleSelection[index].realStock = res.data
                this.tableInfo = JSON.parse(JSON.stringify(this.multipleSelection))
              }
            })
            this.dialogVisible = true
          })
        }
      } else {
        //按列表字段导出,点击全部导出
        if (type !== 'add' && type !== 'refresh' && type !== 'daochu' && type !== 'addMaterial') {
          this.$message.error({ message: '请先勾选', showClose: true })
        }
      }
      if (type === 'daochu') {
        exporthandel('SupplierInventory/Export', this.search)
      }
      // 点击刷新
      if (type === 'refresh') {
        this.getInventoryManage()
      }
    },
    // 搜索事件
    searchData () {
      this.search.pageNo = 1
      this.getInventoryManage()
    },

    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';

::v-deep(.input-wid) {
  width: 200px !important;
}
</style>