<template>
  <el-dialog
    v-dialogDrag
    title="盘点"
    :visible.sync="open"
    width="1200px"
    append-to-body
    @open="dialogOpen"
    @close="dialogClose"
  >
    <!-- 搜索栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="108px"
      :disabled="checkdisable"
      :rules="rules"
      @submit.native.prevent
    >
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="物料条码" prop="qrCode">
            <el-input
              ref="materialNos"
              v-model="queryParams.qrCode"
              placeholder="请输入/扫入物料条码"
              clearable
              @keyup.enter.native="getCurrentMaterial"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="盘点类型" prop="orderType">
            <DictSelect
              v-model="queryParams.orderType"
              placeholder="请选择单据类型"
              dict-type="WMS_REGULAR_CHECK_DOCUMENT_TYPE"
              @change="orderTypeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="盘点数量" prop="checkQty">
            <el-input-number
              v-model="queryParams.checkQty"
              :min="0"
              style="width: 100%"
              label="请输入盘点数量"
              @change="checkQtyChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="盘点作业" prop="wmsStockCountIdErp">
            <InventorySelect v-model="queryParams.wmsStockCountIdErp" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="账存数量" prop="stockQty">
            <el-input
              v-model="queryParams.stockQty"
              placeholder="请输入账存数量"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="盘盈(盘亏)数量" prop="differQty">
            <el-input
              v-model="queryParams.differQty"
              placeholder="请输入盘盈(盘亏)数量"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="queryParams.remark"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button
            type="primary"
            plain
            size="mini"
            icon="el-icon-plus"
            @click="handleAdd"
          >添加</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-descriptions
      v-if="Object.keys(currentData).length > 0"
      size="mini"
      :column="3"
      border
      class="mb10"
      :label-style="{
        width: '80px'
      }"
    >
      <el-descriptions-item label="物料条码">
        {{ currentData.qrCode }}
      </el-descriptions-item>
      <!-- <el-descriptions-item label="数量">
        {{ currentData.receiptQty }}
      </el-descriptions-item> -->
      <el-descriptions-item label="物料编码">
        {{ currentData.materialNo }}
      </el-descriptions-item>
      <el-descriptions-item label="物料名称">
        {{ currentData.materialName }}
      </el-descriptions-item>
      <!-- <el-descriptions-item label="出库说明">
        {{ currentData.remark }}
      </el-descriptions-item> -->
    </el-descriptions>

    <!-- 列表数据 -->
    <el-table :data="list" border size="mini">
      <el-table-column
        label="物料编码"
        align="center"
        prop="materialNo"
        show-overflow-tooltip
      />
      <el-table-column
        label="物料条码"
        align="center"
        prop="qrCode"
        show-overflow-tooltip
      />
      <el-table-column
        label="物料名称"
        align="center"
        prop="materialName"
        show-overflow-tooltip
      />
      <el-table-column label="帐存数量" align="center" prop="stockQty" />
      <el-table-column label="盘点数量" align="center" prop="checkQty" />
      <el-table-column label="盘盈盘亏数量" align="center" prop="differQty" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="仓库" align="center" prop="stockCode" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="160"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['wms:out-stock-detail:query']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            class="text-danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer">
      <el-button
        v-hasPermi="['wms:stock-check-master:create']"
        :loading="buttonLoading"
        type="primary"
        :disabled="signDisable"
        @click="handleSave"
      >保存</el-button>
    </div>

  </el-dialog>
</template>

<script>
import { getInfoByQrCode } from '@/api/wms/base/material'
import { createCheckMaster } from '@/api/wms/inLibrary/periodicInventory'
import InventorySelect from './InventorySelect.vue'

export default {
  components: {
    InventorySelect
  },
  data() {
    return {
      printData: [],
      printStyle: `
        <style>
          table {
            width:100%;
            margin: 0 auto;
            border: 1px solid #000000;
            border-collapse: collapse;
            page-break-after:always;
            font-size: 12px;
            table-layout: fixed;
          }

          th, td {
            border: 1px solid #000000;
          }
        </style>
      `,
      // 遮罩层
      loading: false,
      buttonLoading: false,
      // 总条数
      total: 0,
      // WMS 生产发料 主列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 签收按钮禁用
      signDisable: true,
      // 显示搜索条件
      showSearch: true,
      checkdisable: false,
      currentData: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        qrCode: '',
        remark: '',
        checkQty: null,
        stockQty: null,
        differQty: null,
        wmsStockCountIdErp: null
      },
      // form表单
      form: {},
      rules: {
        orderType: [{ required: true, message: '盘点类型不能为空', trigger: 'change' }],
        // qrCode: [{ required: true, message: '物料条码不能为空', trigger: 'blur' }],
        wmsStockCountIdErp: [{ required: true, message: '盘点作业不能为空', trigger: 'change' }]
      }
    }
  },
  methods: {
    // 查询当前物料
    getCurrentMaterial() {
      if (!this.queryParams.qrCode) {
        this.$modal.msgWarning('请先扫入或输入标签码！')
        return
      }
      this.checkdisable = true
      const { qrCode } = this.queryParams
      const params = {
        qrCode
      }
      getInfoByQrCode(params).then(res => {
        const { data } = res
        if (data.length <= 0) {
          this.$modal.msgWarning('该标签码不存在')
        } else {
          this.queryParams.checkQty = data[0].receiptQty
          this.queryParams.stockQty = data[0].receiptQty
          this.currentData = {
            ...res.data[0],
            ...this.queryParams
          }
        }
      }).finally(() => {
        this.checkdisable = false
      })
    },
    // 删除
    handleDelete(row) {
      const { qrCode } = row
      const index = this.list.findIndex(item => item.qrCode === qrCode)
      console.log(this.list)
      if (index > -1) {
        this.list.splice(index, 1)
      }
    },
    // 添加
    handleAdd() {
      this.$refs['queryForm'].validate(valid => {
        if (!valid) {
          return
        }
        if (!this.queryParams.qrCode) {
          this.$modal.msgWarning('请先扫入或输入标签码！')
          return
        }
        const { qrCode } = this.currentData
        const { differQty } = this.queryParams
        if (differQty <= 0) {
          this.$modal.msgWarning('盘盈(盘亏)数量不能小于0!')
          return
        }
        // 检测是否重复
        const some = this.list.some(i => i.qrCode === qrCode)
        if (some) {
          this.$modal.msgWarning('已存在相同批次的物料，请勿重新添加！')
          return
        }
        this.currentData = {
          ...this.currentData,
          ...this.queryParams
        }
        // 对象解构并重命名属性
        const { funitId: unit, erpStockId: stockCode, ...rest } = this.currentData
        this.currentData = { unit, stockCode, ...rest }
        //   重置
        this.queryParams.materialLots = ''
        //   添加到list
        this.currentData.wmsStockCountIdErp = null
        this.list.push(JSON.parse(JSON.stringify(this.currentData)))
        if (this.queryParams.recipient !== undefined || this.queryParams.recipient !== null) {
          this.signDisable = false
        } else {
          this.signDisable = true
        }
        this.queryParams.qrCode = undefined
        this.currentData = {}
        this.autoFocus()
      })
    },
    dialogOpen() {
      this.autoFocus()
    },
    autoFocus() {
      this.$nextTick(() => {
        this.$refs.materialNos.focus()
      })
    },
    // 重置
    reset() {
      // this.list = []
      this.queryParams = {
        qrCode: '',
        receiptQty: '',
        type: 1
      }
      this.currentData = {}
      this.open = false
      this.resetForm('form')
    },
    // 取消操作
    cancel() {
      this.reset()
      this.open = false
    },
    // 小数点问题处理
    getHandleNumber(val) {
      return Math.round((parseFloat(val) * 100000000)) / 100000000
    },
    // 类型改变计算盘盈盘亏数量 1:盘盈(盘盈(盘亏)数量=盘点数量-帐存数量) 2:盘亏(盘盈(盘亏)数量=帐存数量-盘点数量)
    orderTypeChange(v) {
      if (v === '1') {
        this.queryParams.differQty = this.getHandleNumber(this.queryParams.checkQty - this.queryParams.stockQty)
      } else if (v === '2') {
        this.queryParams.differQty = this.getHandleNumber(this.queryParams.stockQty - this.queryParams.checkQty)
      }
    },
    // 盘点数量变化计算盘盈（盘亏）数量
    checkQtyChange(v) {
      if (this.queryParams.orderType === '1') {
        this.queryParams.differQty = this.getHandleNumber(v - this.queryParams.stockQty)
      } else if (this.queryParams.orderType === '2') {
        this.queryParams.differQty = this.getHandleNumber(this.queryParams.stockQty - v)
      }
    },
    // 盘点保存
    handleSave() {
      const { id } = this.queryParams
      this.list.forEach(i => {
        i.id = id
      })
      if (this.list.length <= 0) {
        this.$modal.notifyWarning('盘点物料不能为空，请先扫码！')
        return
      }
      const detail = this.list.map(item => {
        const { qrCode: wmsLabelMasterId, ...rest } = item
        return {
          ...rest,
          wmsLabelMasterId
        }
      })
      const saveParams = {
        detail,
        wmsStockCountIdErp: this.queryParams.wmsStockCountIdErp,
        orderType: this.queryParams.orderType,
        remark: this.queryParams.remark
      }
      this.buttonLoading = true
      createCheckMaster(saveParams).then(res => {
        this.$modal.msgSuccess('盘点完成!')
        this.$emit('complete')
        this.reset()
      }).finally(() => {
        this.buttonLoading = false
      })
    },
    dialogClose() {
      this.list = []
      this.queryParams.type = 1
      this.queryParams.qrCode = null
      this.queryParams.receiptQty = ''
      this.currentData = []
      this.queryParams.qty = 0
      this.queryParams.maxAmount = 0
    },
    // 扫码弹出层关闭
    issueCodeClose() {
      this.form.encodedEmployeeId = undefined
    }
  }
}
</script>

      <style>

      </style>

