<template>
  <div>
    <Modal v-model="showGiveBackModal" :mask-closable="false">
      <p slot="header">
        耗材归还
      </p>
      <div>
        <Form id="storage-form-back" ref="formObj" :model="formObj" :rules="ruleValidate" :label-width="80">
          <Form-item label="归还量" prop="stock">
            <label style="width: 40%">
              <InputNumber
                v-model.number="formObj.stock"
                :min="1"
                name="stock"
                style="width: 100%"
                @on-change="_changeStock"
              />
            </label>
            <label style="width: 10%;text-align: center">{{ formObj.unit }}</label>
            <input v-model="formObj.unit" hidden name="unit">
          </Form-item>
          <Form-item label="剩余量" prop="exstock">
            <label style="width: 40%">
              <InputNumber v-model.number="formObj.exstock" :min="1" name="exstock" style="width: 100%" @on-change="_changeExstock" />
            </label>
            <label style="width: 10%;text-align: center">{{ formObj.exunit }}</label>
            <input v-show="exunitShow" v-model="formObj.exunit" name="exunit">
          </Form-item>
          <Form-item label="归还人" prop="salesman">
            <Input
              v-model="formObj.salesman"
              name="salesman"
              placeholder="请选择归还人"
              icon="plus-circled"
              readonly
              @click.native="_selectUser"
            /></Input>
          </Form-item>
          <Form-item label="归还时间" prop="time">
            <Date-picker
              v-model="formObj.time"
              type="datetime"
              placeholder="归还时间"
              style="width: 100%;"
              @on-change="_timeChange"
            />
            <input name="time" type="hidden">
          </Form-item>
          <Form-item label="归还原因" prop="reason">
            <Input v-model="formObj.reason" name="reason" placeholder="请输入归还原因" /></Input>
          </Form-item>
          <Form-item label="备注" prop="remark">
            <Input v-model="formObj.remark" name="remark" placeholder="请输入备注" /></Input>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <Button type="ghost" style="margin-left: 8px" @click="_cancel">
          取消
        </Button>
        <Button type="primary" @click="_ok">
          提交
        </Button>
      </div>
    </Modal>
    <!--选择人员（单选）-->
    <User ref="userModal" @on-result-change="_userData" />
  </div>
</template>
<script>
/**
 * 添加编辑试验耗材库存表
 */
import User from '../../../../components/user-info-single/assignPerson'
import Global from '../../../../api/config'
import { consumeStock } from '../../../../api'
const defVal = {
  stock: 1,
  exstock: 1,
  exunit: '',
  reason: '',
  remark: '',
  salesman: '',
  time: new Date()
}

export default {
  components: {
    User
  },
  data() {
    const validateNumber = (rule, value, callback) => {
      // 只能输入正整数，不能输入小数
      const reg = /^\+?[1-9]\d*$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('数量只能输入整数'))
      }
    }
    const validateStockNumber = (rule, value, callback) => {
      // 剩余量不能大于数量*转换率
      const reg = /^\+?[1-9]\d*$/
      if (!reg.test(value)) {
        callback(new Error('数量只能输入整数'))
        // } else if (value > this.exstockMax) {
        // callback(new Error('剩余量不能大于转换库存数量'));
      } else {
        callback()
      }
    }
    return {
      id: '',
      formObj: defVal,
      showGiveBackModal: false,
      chemicalId: '',
      exchange: '', // 转化率
      exstockMax: '', // 最大值
      ruleValidate: {
        stock: [{ validator: validateNumber, trigger: 'blur', type: 'number' }],
        exstock: [
          { validator: validateStockNumber, trigger: 'blur', type: 'number' }
        ]
      },
      unit: '',
      exunitShow: false
    }
  },
  methods: {
    _resultChange(msg) {
      this.formObj = defVal
      this.showGiveBackModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('storage-form-back')
          data.chemicalId = this.chemicalId
          data.type = 2
          // this.$store
          //   .dispatch('LmsChemicalStock/purchaseGiveBack', data)
          //   .then(() => {
          //     this._resultChange('归还成功!')
          //   })
          this._save(data)
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },

    _save: async function(data) {
      const result = await consumeStock.editStock(data)
      if (result) {
        this._resultChange('入库成功')
      }
    },
    _cancel() {
      this.showGiveBackModal = false
    },
    _open(data, exchange) {
      this.exchange = exchange // 转化率
      this.chemicalId = data.id
      this.formObj.exunit = data.exunit ? data.exunit : ''
      this.formObj.unit = data.unit ? data.unit : ''
      this.formObj.stock = data.stock ? data.stock : ''
      this.formObj.exstock = data.exstock ? data.exstock : ''
      if (data.exunit === undefined) {
        this.exunitShow = true
      } else {
        this.exunitShow = false
      }
      this.showGiveBackModal = true
      this.$refs.formObj.resetFields()
      this._getUser()
      this._getRemark()
    },
    _getRemark() {
      this.formObj.remark =
        '归还量为：' +
        this.formObj.stock +
        ' ' +
        this.formObj.unit +
        '，' +
        this.formObj.exstock +
        ' ' +
        this.formObj.exunit
    },
    _changeStock(data) {
      // 改变数量
      if (this.exchange === undefined) {
        this.formObj.exstock = 1
      } else {
        this.exstockMax = data * this.exchange
        this.formObj.exstock = data * this.exchange
      }
      this.formObj.remark =
        '归还量为：' +
        this.formObj.stock +
        ' ' +
        this.formObj.unit +
        '，' +
        this.formObj.exstock +
        ' ' +
        this.formObj.exunit
    },
    _changeExstock(data) {
      this.formObj.exstock = data
      this.formObj.remark =
        '归还量为：' +
        this.formObj.stock +
        ' ' +
        this.formObj.unit +
        '，' +
        this.formObj.exstock +
        ' ' +
        this.formObj.exunit
    },
    // 归还时间
    _timeChange(data) {
      $('input[name="time"]').val(data)
    },
    _getUser() {
      const user = Global.getUserInfo()
      this.formObj.salesman = user.realname
    },
    // 选择人员
    _selectUser() {
      this.$refs.userModal._open('stockInMan')
    },
    _userData(data) {
      this.formObj.salesman = data.realname
    }
  }
}
</script>
