<template>
  <!-- 对话框(退料原因) -->
  <el-dialog
    v-dialogDrag
    title="退料"
    :visible.sync="open"
    width="1200px"
    append-to-body
    :before-close="beforeClose"
    @open="dialogOpen"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      size="mini"
      label-width="68px"
      :disabled="fetching"
      @submit.native.prevent
    >
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="物料条码" prop="number">
            <el-input
              ref="formNumber"
              v-model="form.number"
              placeholder="请扫入/输入物料条码"
              clearable
              @keyup.enter.native="queryRow"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="退料数量" prop="returnQty">
            <el-input-number
              v-model="form.returnQty"
              :min="0"
              :max="form.maxAmount"
              style="width: 100%"
              label="请输入退料数量"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="16" class="text-right">
          <el-button
            type="primary"
            plain
            size="mini"
            icon="el-icon-plus"
            @click="handleAddItem"
          >添加退料</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- <el-descriptions
      v-if="Object.keys(currentData).length > 0"
      :column="4"
      size="mini"
      border
      class="mb10"
      :label-style="{
        width: '80px'
      }"
    >
      <el-descriptions-item label="物料编码">
        {{ currentData.materialNo }}
      </el-descriptions-item>
      <el-descriptions-item label="物料名称">
        {{ currentData.materialName }}
      </el-descriptions-item>
      <el-descriptions-item label="物料批次">
        {{ currentData.materialLots }}
      </el-descriptions-item>
      <el-descriptions-item label="领料单号">
        {{ currentData.receiveOrderNo }}
      </el-descriptions-item>
      <el-descriptions-item label="发料单号">
        {{ currentData.sendOrderNo }}
      </el-descriptions-item>
      <el-descriptions-item label="可退数">
        {{ currentData.canReturnQty }}
      </el-descriptions-item>
      <el-descriptions-item label="原发料数">
        {{ currentData.sendQty }}
      </el-descriptions-item>
      <el-descriptions-item label="已退数">
        {{ currentData.returnAllQty }}
      </el-descriptions-item>
      <el-descriptions-item label="物料条码">
        {{ currentData.qrCode }}
      </el-descriptions-item>
    </el-descriptions> -->

    <el-table :data="list" border size="small">
      <el-table-column label="领料单号" align="center" prop="receiveOrderNo" />
      <el-table-column label="发料单号" align="center" prop="sendOrderNo" />
      <el-table-column
        label="物料编号"
        align="center"
        width="160"
        prop="materialNo"
      />
      <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column
        label="物料批次"
        align="center"
        width="120"
        prop="materialLots"
      />
      <el-table-column
        label="物料条码"
        align="center"
        width="120"
        prop="qrCode"
      />
      <el-table-column
        label="生产订单"
        align="center"
        width="120"
        prop="workOrderNo"
      />
      <el-table-column
        label="原始发料数量"
        align="center"
        width="120"
        prop="sendQty"
      />
      <el-table-column
        label="已退数"
        align="center"
        prop="returnAllQty"
      />
      <el-table-column
        label="长度m"
        align="center"
        width="120"
        prop="canReturnLength"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.canReturnLength" placeholder="请输入长度" @input="handleCalculateReturnQty($event, scope, 'length')" />
        </template>
      </el-table-column>
      <el-table-column
        label="宽度mm"
        align="center"
        width="120"
        prop="width"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.width" placeholder="请输入宽度" @input="handleCalculateReturnQty($event, scope, 'width')" />
        </template>
      </el-table-column>
      <el-table-column
        label="本次退料数"
        align="center"
        width="120"
        prop="canReturnQty"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.canReturnQty" placeholder="请输入本次退料数量" @change="returunQtyChange(scope.row.canReturnQty,scope.row)" />
        </template>
      </el-table-column>
      <el-table-column
        label="供应商"
        align="center"
        width="120"
        prop="supplierName"
      />

      <el-table-column
        label="操作"
        align="center"
        width="100"
        fixed="right"
      >
        <template slot-scope="{row}">
          <el-button
            v-hasPermi="['infra:test-demo:delete']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            class="text-danger"
            @click="handleRemoveRow(row)"
          >删除退料</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button v-loading="loading" type="primary" @click="submitForm">完成退料</el-button>
    </div>
    <!-- 选择退料单 -->
    <el-dialog
      v-dialogDrag
      title="选择退料单"
      :visible.sync="selectOpen"
      width="400px"
      append-to-body
      :before-close="beforeClose"
      @close="returunClose"
    >
      <el-form
        ref="selectForm"
        :model="selectForm"
        size="mini"
        label-width="68px"
        :disabled="fetching"
        @submit.native.prevent
      >
        <el-form-item label="领料单" prop="reportId">
          <el-select v-model="selectForm.returnOrder" @change="returnChange">
            <el-option
              v-for="report in currentData"
              :key="report.sendOrderNo"
              :label="report.receiveOrderNo"
              :value="report.receiveOrderNo"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectOpen = ! selectOpen">取消</el-button>
        <el-button v-loading="loading" type="primary" @click="handleEnsureSelected">完成退料</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { getMaterialToReturn } from '@/api/wms/output/materialReturn'

export default {
  data() {
    return {
      loading: false,
      list: [],
      open: false,
      // 选择退料
      selectOpen: false,
      selectForm: {
        returnOrder: null
      },
      form: {
        number: '', // 扫码结果
        returnQty: 0, // 退料数量
        remark: '', // 退料原因
        maxAmount: 0,
        canReturnQty: 0,
        canReturnLength: 0,
        width: 0
      },
      currentData: [],
      returnObj: {},
      rules: {},
      fetching: false
    }
  },
  methods: {
    // 计算退料数量
    handleCalculateReturnQty(e, { $index }, name) {
      if (name === 'width') {
        this.list[$index].canReturnQty = this.list[$index].canReturnLength * e * 0.001
      } else {
        this.list[$index].canReturnQty = e * this.list[$index].width * 0.001
      }
    },
    // 删除一条退料单物料
    handleRemoveRow(row) {
      const { id } = row
      const index = this.list.findIndex(item => item.id === id)
      if (index > -1) {
        this.list.splice(index, 1)
      }
    },
    // 查询当前物料
    queryRow() {
      if (!this.form.number) {
        this.$modal.msgWarning('请先扫入或输入物料批次！')
        return
      }
      this.fetching = true
      const { number: id, receiveOrderNo } = this.form
      const params = { id, receiveOrderNo }
      getMaterialToReturn(params).then(res => {
        const { data } = res
        if (!data) {
          this.$modal.msgWarning('未查到该物料或者该物料已使用！')
        } else {
          // // sendQty 原始数量  cumulatQty 上料数
          // const { sendQty, cumulatQty, returnAllQty = 0 } = data
          // // 查询可退料数量
          // const returnQty = sendQty - returnAllQty - cumulatQty
          // // 默认可退料数量为计算结果
          // this.form.returnQty = returnQty
          // // 最大可退料数量
          this.form.maxAmount = data.canReturnQty
          // this.currentData = { ...data, returnQty }
          this.form.returnQty = data.canReturnQty
          this.currentData = data
          this.handleAddItem()
        }
      }).finally(() => {
        this.fetching = false
      })
    },
    // 提交表单
    submitForm() {
      if (this.list.length === 0) {
        this.$modal.msgWarning('您还未添加任何物料，不能执行退料操作！')
        return
      }
      this.loading = true
      this.$emit('updateList', this.list)
      this.loading = false
      this.list = []
      this.open = false
    },
    // 添加row到list
    handleAddItem() {
      this.selectOpen = true
      // if (this.form.returnQty <= 0) {
      //   this.$modal.msgWarning('当前物料数量为0，不能添加到退料单！')
      //   return
      // }
      // // 检测是否重复
      // // this.currentData = {
      // //   ...this.currentData,
      // //   ...this.form
      // // }
      // // 重置form
      // this.form.number = ''
      // this.form.maxAmount = 0
      // this.form.returnQty = 0
      // // 插入到list
      // this.list.unshift(JSON.parse(JSON.stringify(...this.currentData)))
      // // 清空缓存数据
      // this.currentData = {}
      // this.autoFoucs()
    },
    // 取消操作
    cancel() {
      this.rest()
      this.open = false
    },
    // 重置
    rest() {
      this.list = []
      this.form = {
        number: '', // 扫码结果
        returnQty: 0, // 退料数量
        remark: '', // 退料原因
        maxAmount: 0
      }
      this.currentData = {}
      this.open = false
      this.resetForm('form')
    },
    beforeClose(done) {
      this.rest()
      done()
    },
    dialogOpen() {
      this.autoFoucs()
    },
    autoFoucs() {
      this.$nextTick(() => {
        this.$refs.formNumber.focus()
      })
    },
    handleEnsureSelected() {
      if (this.returnObj.canReturnQty <= 0) {
        this.$modal.msgWarning('当前物料数量为0，不能添加到退料单！')
        return
      }
      this.selectOpen = false
      // 插入到list
      this.list.unshift(JSON.parse(JSON.stringify(this.returnObj)))
      this.form = {}
    },
    returnChange(v) {
      const obj = this.currentData.find(item => item.receiveOrderNo === v)
      this.returnObj = obj
    },
    // 退料选择关闭
    returunClose() {
      this.selectForm.returnOrder = undefined
    },
    // 退料数量不能超过发料数
    returunQtyChange(v, row) {
      // if (row.sendQty !== undefined || row.sendQty !== null || row.sendQty !== '') {
      //   if (parseFloat(v) > row.sendQty) {
      //     this.$modal.msgWarning('本次退料数不能超过发料数，请重新输入退料数!')
      //     return
      //   }
      // }
      if (row.sendQty != null && parseFloat(v) > row.sendQty) {
        this.$modal.msgWarning('本次退料数不能超过发料数，请重新输入退料数!')
        return
      }
    }
  }
}
</script>

<style>

</style>
