<template>
  <div>
    <Modal v-model="chemicalStockInModal" :mask-closable="false" class="zIndex-1100">
      <p slot="header">
        耗材直接入库
      </p>
      <div>
        <Form id="storage-form-storeIn" 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%" />
            </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="price">
            <label style="width: 40%">
              <InputNumber v-model.number="formObj.price" :min="1" name="price" style="width: 100%" />
            </label>
            <label style="width: 10%;text-align: center">元</label>
          </Form-item>
          <Form-item label="入库人" prop="realname">
            <Select
              v-model="formObj.realname"
              clearable
              style="width:100%"
              filterable
              name="realname"
              placeholder="请选择入库人员"
            >
              <Option v-for="item in salesmanList" :key="item" :value="item">
                {{ item }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="入库时间" prop="regdate">
            <Date-picker
              v-model="formObj.regdate"
              type="datetime"
              placeholder="入库时间"
              style="width: 100%;"
              @on-change="_timeChange"
            />
            <input name="regdate" type="hidden">
          </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 { consumeStock, sysUser } from '../../../../api'
import User from '../../../../components/user-info/assignPerson'
import Global from '../../../../api/config'

const defVal = {
  stock: 1,
  unit: '',
  remark: '',
  realname: '',
  regdate: new Date(),
  price: 1,
  purchaseOrderRelId: '',
  batchNum: ''
}

export default {
  components: { User },
  data() {
    const validateNumber = (rule, value, callback) => {
      const reg = /^\d+(\.\d{0,2})?$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('小数点后只能输入两位'))
      }
    }
    return {
      id: '',
      formObj: defVal,
      chemicalStockInModal: false,
      chemicalId: '',
      ruleValidate: {
        stock: [{ validator: validateNumber, trigger: 'blur', type: 'number' }],
        remark: [
          { required: true, trigger: 'blur', message: '入库原因不能为空' }
        ]
      },
      salesmanList: [],
      salesmanListTemp: [],
      purchaseOrderRelId: '',
      chemical: {}
    }
  },
  methods: {
    _resultChange(msg) {
      this.formObj = defVal
      this.chemicalStockInModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
    },
    // 人员列表
    _getSalesmanList: async function() {
      const result = await sysUser.list({})
      if (result) {
        const salesmanList = result
        const salesmanListTemp = []
        for (let i = 0; i < salesmanList.length; i++) {
          salesmanListTemp.push(salesmanList[i].realname)
        }
        if (salesmanListTemp.indexOf(this.formObj.realname) === -1) {
          salesmanListTemp.push(Global.getUserInfo().realname)
        }
        this.salesmanList = salesmanListTemp
        this.salesmanListTemp = this.salesmanList
      }
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('storage-form-storeIn')
          data.chemicalId = this.chemicalId
          data.purchaseOrderRelId = this.purchaseOrderRelId
          data.type = 0
          data.validDate = this.$dateformat(
            this.chemical.validDate,
            'yyyy-mm-dd'
          )
          this._save(data)
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },
    _save: async function(data) {
      const result = await consumeStock.editStock(data)
      if (result) {
        this._resultChange('入库成功')
      }
    },

    _cancel() {
      this.chemicalStockInModal = false
    },
    _open(data, id) {
      this.$refs.formObj.resetFields()
      this.chemical = data
      this.formObj.unit = data.unit
      this.chemicalId = data.id
      this.purchaseOrderRelId = id
      this.chemicalStockInModal = true
      this.formObj.realname = Global.getUserInfo().realname
      this.formObj.regdate = new Date()
      $('input[name=regdate]').val(
        this.$dateformat(new Date(), 'yyyy-mm-dd HH:MM:ss')
      )
      this._getSalesmanList()
    },
    // 入库时间
    _timeChange(data) {
      $('input[name="regdate"]').val(data)
    },
    // 选择人员
    _selectUser() {
      this.$refs.userModal._open('stockInMan')
    },
    _userData(data) {
      this.formObj.realname = data.realname
    }
  }
}
</script>
