<template>
  <div>
    <Modal v-model="chemicalStockInModal" :mask-closable="false" :width="800" class="zIndex-1100">
      <p slot="header">
        耗材直接首次入库
      </p>
      <div>
        <Form
          :id="formId"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="80"
          inline
        >
          <Form-item label="入库数量" prop="stock" class="width-48">
            <InputNumber v-model.number="formObj.stock" :min="1" name="stock" style="width: 100%" />
          </Form-item>
          <Form-item label="有效期" prop="validDate" class="width-48">
            <DatePicker
              v-model="formObj.validDate"
              type="date"
              placeholder="请选择有效期"
              style="width: 100%"
              :options="optionDate"
              @on-change="_validDateChange"
            />
            <input name="validDate" type="hidden">
          </Form-item>
          <Form-item label="生产批号" prop="batchNum" class="width-48">
            <Input v-model="formObj.batchNum" name="batchNum" placeholder="请输入生产批号" /></Input>
          </Form-item>
          <Form-item label="规格型号" prop="spec" class="width-48">
            <Input v-model="formObj.spec" name="spec" placeholder="请输入规格型号" /></Input>
          </Form-item>
          <Form-item label="商品编码" prop="productCode" class="width-48">
            <Input v-model="formObj.productCode" name="productCode" placeholder="请输入商品编码" /></Input>
          </Form-item>
          <Form-item label="CAS编号" prop="casNum" class="width-48">
            <Input v-model="formObj.casNum" name="casNum" placeholder="请输入CAS编号" /></Input>
          </Form-item>
          <Form-item label="等级（纯度）" prop="quality" class="width-48">
            <Input v-model="formObj.quality" name="quality" placeholder="请输入等级（纯度）" /></Input>
          </Form-item>
          <Form-item label="供应商" prop="supplier" class="width-48">
            <autoComplete
              name="supplier"
              placeholder="请输入供应商"
              :down-data="supplierList"
              :value="formObj.supplier"
              @on-result-change="_SupplierChange"
            />
          </Form-item>
          <Form-item label="价格" prop="unitPrice" class="width-48">
            <Input v-model="formObj.unitPrice" name="unitPrice" placeholder="请输入价格" /></Input>
          </Form-item>
          <Form-item label="制造厂商" prop="manufacturer" class="width-48">
            <autoComplete
              v-model="formObj.manufacturer"
              name="manufacturer"
              :down-data="manufacturerList"
              placeholder="请输入制造厂商"
              @on-result-change="_manufacturerChange"
            />
            <!-- <Input name="manufacturer" v-model="formObj.manufacturer" placeholder="请输入制造厂商"></Input>-->
          </Form-item>
          <Form-item label="入库人" prop="realname" class="width-48">
            <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" class="width-48">
            <DatePicker
              v-model="formObj.regdate"
              type="datetime"
              placeholder="请选择入库时间"
              style="width: 100%"
              :options="optionDate"
              @on-change="_stockTimeChange"
            />
            <input name="regdate" type="hidden">
          </Form-item>
          <Form-item label="入库原因" prop="reason" class="width-48">
            <Input v-model="formObj.reason" name="reason" placeholder="请输入入库原因" /></Input>
          </Form-item>
          <Form-item label="备注" prop="remark" class="width-48">
            <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>
  </div>
</template>
<script>
/**
 * 添加编辑试验耗材库存表
 */
import { consumeStock } from '../../../../api'
import global from '../../../../api/config'
import autoComplete from '../../../../components/base/autoComplete.vue'

export default {
  components: {
    autoComplete
  },
  props: {
    chemical: null // 耗材信息
  },
  data() {
    const validateNumber = (rule, value, callback) => {
      const reg = /^\d+(\.\d{0,2})?$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('小数点后只能输入两位'))
      }
    }
    return {
      id: '',
      formObj: {
        stock: 1,
        validDate: '',
        accuracyRange: '',
        casNum: '',
        productCode: '',
        batchNum: '',
        spec: '',
        quality: '',
        supplier: '',
        unitPrice: '',
        manufacturer: '',
        realname: '',
        regdate: new Date(),
        reason: '',
        remark: ''
      },
      chemicalStockInModal: false,
      ruleValidate: {
        stock: [
          {
            required: true,
            validator: validateNumber,
            trigger: 'blur',
            type: 'number'
          }
        ],
        // validDate: [{required: true, message: '有效期不能为空', trigger: 'change', type: 'date'}],
        batchNum: [
          { required: true, message: '生产批号不能为空', trigger: 'blur' }
        ]
        // productCode: [{required: true, message: '商品编码不能为空', trigger: 'blur'}],
        // manufacturer: [{required: true, message: '制造厂商不能为空', trigger: 'change'}],
      },
      chemicalId: '',
      optionDate: {
        // 今天之前的日期被禁用
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000
        }
      },
      regdate: '',
      salesmanList: [],
      salesmanListTemp: [],
      manufacturer: '',
      manufacturerListTemp: [],
      manufacturerList: [],
      //  供应商
      supplierList: [],
      formId: 'storage-form' + this.$randomCode()
    }
  },
  methods: {
    _resultChange(msg) {
      this.chemicalStockInModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
    },
    _openSearchManufacturer(manufacturer = '') {
      // eslint-disable-next-line no-unused-vars
      const data = {
        item: 'manufacturer',
        name: manufacturer
      }
    },
    // 制造厂商
    _manufacturerChange(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.manufacturer = data
          break
        default:
          this.formObj.manufacturer = data
          this._openSearchManufacturer(data)
          break
      }
    },
    // 人员列表
    _getSalesmanList() {
      // eslint-disable-next-line no-unused-vars
      const data = {}
    },
    // 供应商
    _getSupplier(supplier = '') {
      // eslint-disable-next-line no-unused-vars
      const data = {
        value: supplier
      }
    },
    _SupplierChange(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.supplier = data
          break
        default:
          this.formObj.supplier = data
          this._getSupplier(data)
      }
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize(this.formId)
          data.chemicalId = this.chemicalId
          data.realname = this.formObj.realname
          data.spec = this.formObj.spec
          // data.validDate = this.validDate;
          if (this.$string(this.chemicalId).isEmpty()) {
            this.$Message.error('请选择耗材!')
          } else {
            this._save(data)
          }
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },

    _save: async function(data) {
      const result = await consumeStock.add(data)
      if (result) {
        this.chemicalStockInModal = false
        this.$Message.success('添加成功')
        this.$emit('on-result-change')
      }
    },

    _cancel() {
      this.chemicalStockInModal = false
    },
    _open(id) {
      this.chemicalStockInModal = true
      this.$refs.formObj.resetFields()
      this.chemicalId = id
      this.formObj.validDate = ''
      $('input[name=validDate]').val('')
      this._getUser()
      this._getSalesmanList()
      this._openSearchManufacturer()
      this._getSupplier()
      this.formObj.regdate = new Date()
      $('input[name=regdate]').val(
        this.$dateformat(new Date(), 'yyyy-mm-dd HH:MM:ss')
      )
      if (this.chemical && this.chemical.spec) {
        this.$set(this.formObj, 'spec', this.chemical.spec)
      } else {
        this.$set(this.formObj, 'spec', '')
      }
    },

    _getUser() {
      const user = global.getUserInfo()
      this.formObj.realname = user.realname
    },
    _validDateChange(data) {
      $('input[name=validDate]').val(data)
    },
    // 入库时间
    _stockTimeChange(data) {
      $('input[name=regdate]').val(data)
    }
  }
}
</script>
