<template>
  <div>
    <Modal v-model="chemicalStockOutModal" :mask-closable="false">
      <p slot="header">
        耗材直接出库
      </p>
      <div>
        <Form id="storage-form-storeOut" ref="formObj" :model="formObj" :rules="ruleValidate" :label-width="80">
          <Form-item label="数量" prop="stock">
            <label style="width: 40%">
              <InputNumber
                v-model="formObj.stock"
                :min="0"
                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="department">
            <Select @on-change="_departmentChange" filterable style="width:100%" name="department"  v-model="formObj.department">
              <Option v-for="item in departmentList" :value="item.id" :key="item.id">{{ item.name }}
              </Option>
            </Select>
           &lt;!&ndash; <Input name="department" v-model="formObj.department" placeholder="请选择科室"
                   @click.native="_selectUserGroup" icon="plus-circled" readonly></Input>&ndash;&gt;
          </Form-item>-->
          <Form-item label="使用人" prop="registrant">
            <Select v-model="formObj.registrant" filterable style="width:100%" @on-change="_selectChange">
              <Option v-for="item in salesmanList" :key="item" :value="item">
                {{ item }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="出库时间" prop="time">
            <Date-picker
              v-model="formObj.regdate"
              type="datetime"
              placeholder="出库时间"
              style="width: 100%;"
              @on-change="_timeChange"
            />
            <input name="regdate" 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>
    <!--选择科室（单选）-->
    <!--<UserGroup ref="userGroupModal" @on-result-change="_userGroupData"></UserGroup>-->
  </div>
</template>
<script>
/**
 * 添加编辑试验耗材库存表
 */
import global from '../../../../api/config'
import { sysUser, consumeStock } from '../../../../api'
const defVal = {
  stock: 1,
  unit: '',
  depId: '',
  department: '',
  registrant: '',
  remark: '',
  reason: '',
  regdate: new Date(),
  batchNum: ''
}

export default {
  components: {},
  data() {
    const validateNumber = (rule, value, callback) => {
      const reg = /^\d+(\.\d{0,5})?$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('小数点后只能输入五位'))
      }
    }
    return {
      id: '',
      formObj: defVal,
      chemicalStockOutModal: false,
      chemicalId: '',
      ruleValidate: {
        stock: [{ validator: validateNumber, trigger: 'blur' }],
        department: [
          { required: true, trigger: 'blur', message: '科室不能为空' }
        ],
        registrant: [
          { required: true, trigger: 'change', message: '使用人不能为空' }
        ]
      },
      selectList: [],
      departmentList: [],
      salesmanList: [],
      salesmanListTemp: [],
      chemical: {}
    }
  },
  methods: {
    _selectChange(data) {
      this.formObj.registrant = data
    },
    _resultChange(msg) {
      this.formObj = defVal
      this.chemicalStockOutModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('storage-form-storeOut')
          data.chemicalId = this.chemicalId
          data.registrant = this.formObj.registrant
          data.type = 1
          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.chemicalStockOutModal = false
    },
    _open(data) {
      this._selectdepartment()
      this.formObj.unit = data.unit ? data.unit : ''
      this.formObj.stock = 1
      this.formObj.remark = ''
      this.chemicalId = data.id
      this.chemical = data
      this.chemicalStockOutModal = true
      this.$refs.formObj.resetFields()
      $('input[name=regdate]').val(
        this.$dateformat(new Date(), 'yyyy-mm-dd HH:MM:SS')
      )
      this.formObj.department = ''
      this.formObj.depId = ''
      this.remark = ''
      this.salesmanList = []
      this._getUser()
      this._getSalesmanList()
    },
    _getUser() {
      const user = global.getUserInfo()
      this.formObj.registrant = user.realname
    },
    // 人员列表
    _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
      }
    },
    // 出库时间
    _timeChange(data) {
      $('input[name="regdate"]').val(data)
    },
    testChange() {
      // 该方法在input内容改变是就会触发进行检测
      this.numberChange(this.formObj.stock) // 调用函数
    },
    // 封装控制小数点位数的函数
    numberChange(VauleNumber) {
      // VauleNumber你想要控制位数的数字
      let newNumber = null
      if (VauleNumber >= 0) {
        const reg = /.*\..*/
        if (reg.test(VauleNumber)) {
          newNumber = parseFloat(VauleNumber.toFixed(5))
        } else {
          newNumber = VauleNumber
        }
      }
      console.log(newNumber)
      this.formObj.stock = newNumber
    },
    _selectdepartment() {
      // this.$store.dispatch('LmsMarshalManage/page').then(() => {
      //   this.departmentList = this.$store.state.LmsMarshalManage.page.records
      // })
    },
    _departmentChange(id) {
      // this.formObj.department = data.name;
      this.formObj.depId = id
      // this.$store
      //   .dispatch('LmsMarshalManage/userPage', { rows: 500, groupId: id })
      //   .then(() => {
      //     this.salesmanList = this.$store.state.LmsMarshalManage.userPage.records
      //   })
    }
  }
}
</script>
