<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="68px"
      :disabled="searching"
      @submit.native.prevent
    >
      <el-row :gutter="10">
        <el-col :span="7">
          <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="7">
          <el-form-item label="数量" prop="qty">
            <el-input-number
              v-model="queryParams.qty"
              :min="0"
              :max="queryParams.maxAmount"
              style="width: 100%"
              label="请输入退料数量"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="出库说明" prop="remark">
            <el-input
              v-model="queryParams.remark"
              placeholder="请输入出库说明"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col v-show="false" :span="3">
          <el-form-item label="部门名称" prop="departmentName">
            <el-input
              v-model="queryParams.departmentName"
              placeholder="请输入部门名称"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="7">
          <el-form-item label="领用部门" prop="departmentNo">
            <DepartmentSelect
              v-model="queryParams.departmentNo"
              placeholder="请选择领用部门"
              @change="departmentNoChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="领用人" prop="recipient">
            <el-input
              v-model="queryParams.recipient"
              style="width: 100%"
              placeholder="请扫描工卡二维码"
              @keyup.enter.native="handleFinish"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="出库类型" prop="outType">
            <el-select
              v-model="queryParams.outType"
              placeholder="请选择出库类型"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in getDictDatas(DICT_TYPE.WMS_OTHER_ISSUE_TYPE_ERP)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3" 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.materialNo }}
      </el-descriptions-item>
      <el-descriptions-item label="物料名称">
        {{ currentData.materialName }}
      </el-descriptions-item>
    </el-descriptions>

    <!-- 列表数据 -->
    <el-table
      :data="list"
      border
      size="mini"
      :summary-method="getSummaries"
      show-summary
    >
      <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="qty" />
      <el-table-column label="领用部门" align="center" prop="departmentNo" />
      <el-table-column label="领用人" align="center" prop="recipient" />
      <el-table-column label="出库类型" align="center" prop="outType">
        <template slot-scope="scope">
          <dict-tag
            :type="DICT_TYPE.WMS_OTHER_ISSUE_TYPE_ERP"
            :value="scope.row.outType"
          />
        </template>
      </el-table-column>
      <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:other-out-sock:create']"
        :loading="buttonLoading"
        type="primary"
        :disabled="signDisable"
        @click="handleSign"
      >签收</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createBatch, getEmployeeMaster } from '@/api/wms/output/otherIssue'
import { getInfoByQrCode } from '@/api/wms/base/material'
import DepartmentSelect from './DepartmentSelect.vue'
import { Base64 } from 'js-base64'

export default {
  components: {
    DepartmentSelect
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      buttonLoading: false,
      // 总条数
      total: 0,
      // WMS 生产发料 主列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 扫码签收
      scanCodeOpen: false,
      // 签收按钮禁用
      signDisable: true,
      // 显示搜索条件
      showSearch: true,
      searching: false,
      currentData: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        qrCode: '',
        remark: '',
        type: 1,
        qty: 0,
        maxAmount: 0,
        departmentNo: undefined,
        recipient: undefined,
        outType: undefined,
        encodedEmployeeId: undefined
      },
      // form表单
      form: {}
    }
  },
  methods: {
    // 查询当前物料
    getCurrentMaterial() {
      if (!this.queryParams.qrCode) {
        this.$modal.msgWarning('请先扫入或输入标签码！')
        return
      }
      this.searching = 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.qty = data[0].receiptQty
            this.queryParams.maxAmount = data[0].receiptQty
            //   this.list.push(...data)
            //   this.currentData = res.data
            this.currentData = {
              ...res.data[0],
              ...this.queryParams
            }
          }
        })
        .finally(() => {
          this.searching = false
        })
    },
    // 删除
    handleDelete(row) {
      const { qrCode } = row
      const index = this.list.findIndex((item) => item.qrCode === qrCode)
      if (index > -1) {
        this.list.splice(index, 1)
      }
    },
    // 添加
    handleAdd() {
      const { qrCode } = this.currentData
      const { remark, departmentNo, recipient, outType } = this.queryParams
      const isEmpty =
        remark !== '' &&
        recipient !== undefined &&
        departmentNo !== undefined &&
        outType !== undefined
      if (!isEmpty) {
        this.$modal.msgWarning(
          '出库说明/领用部门/领用人/出库类型不能为空，请填写出库说明'
        )
        return
      }
      // 检测是否重复
      const some = this.list.some((i) => i.qrCode === qrCode)
      if (some) {
        this.$modal.msgWarning('已存在相同批次的物料，请勿重新添加！')
        return
      }
      this.currentData = {
        ...this.currentData,
        ...this.queryParams
      }
      //   重置
      this.queryParams.materialLots = ''
      // this.queryParams.remark = ''
      // this.queryParams.departmentNo = undefined
      // this.queryParams.recipient = undefined
      // this.queryParams.outType = undefined
      //   添加到list
      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
    },
    handleScanEmployCode() {
      if (this.list.length === 0) {
        this.$modal.msgWarning('您还未添加任何物料，不能执行出库操作！')
        return
      }
      this.scanCodeOpen = true
    },
    // 扫码 领用人
    handleFinish() {
      this.queryParams.encodedEmployeeId = this.queryParams.recipient
      if (
        this.queryParams.recipient !== undefined &&
        this.queryParams.recipient !== null
      ) {
        this.queryParams.recipient = Base64.decode(this.queryParams.recipient)
        this.signDisable = false
      }
      const base64Id = this.queryParams.recipient
      getEmployeeMaster(base64Id).then((res) => {
        this.queryParams.recipient = res.data.employeeName || ''
      })
    },
    // 签收/打印标签
    async handleSign() {
      try {
        this.loading = true
        const { id } = this.queryParams
        this.list.forEach((i) => {
          i.id = id
        })
        if (this.list.length === 0) {
          this.$modal.notifyWarning('出库物料不能为空，请先扫码！')
          return
        }
        const finishParams = this.list.map((item) => {
          item.encodedEmployeeId = this.queryParams.encodedEmployeeId
          const {
            qty,
            materialNo,
            qrCode: materialLots,
            remark,
            type,
            wmsStoreId,
            departmentNo,
            recipient,
            outType,
            departmentName,
            encodedEmployeeId
          } = item
          return {
            qty,
            materialNo,
            materialLots,
            remark,
            type,
            wmsStoreId,
            departmentNo,
            recipient,
            outType,
            departmentName,
            encodedEmployeeId
          }
        })
        this.buttonLoading = true
        await createBatch(finishParams)
        this.$emit('complete')
        this.$modal.msgSuccess('出库签收完成!')
        this.scanCodeOpen = false
        this.reset()
        this.open = false
      } catch (error) {
        console.log(error)
      } finally {
        this.buttonLoading = false
        this.loading = 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
    },
    // 部门选择
    departmentNoChange(v) {
      const { name } = v
      this.queryParams.departmentName = name
    },
    // 扫码弹出层关闭
    issueCodeClose() {
      this.form.encodedEmployeeId = undefined
    },
    // 小数点问题处理
    getHandleNumber(val) {
      return Math.round(parseFloat(val) * 100000000) / 100000000
    },
    // 数量合计
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }

        const values = this.list.map((item) => Number(item[column.property]))
        if (column.property === 'qty') {
          sums[index] = values.reduce((acc, cur) => {
            const value = Number(cur)
            if (!isNaN(value)) {
              return this.getHandleNumber(acc + cur)
            } else {
              return acc
            }
          }, 0)
          sums[index]
        }
      })
      return sums
    }
  }
}
</script>

<style></style>
