<template>
  <div>
    <Modal v-model="showEditModal" :mask-closable="false" width="1300">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Form
          id="edit-form"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="110"
          inline
        >
          <Alert>
            <h4 align="center">
              仪器基本信息
            </h4>
          </Alert>
          <Form-item label="仪器名称" prop="name" class="search-item">
            <Input
              v-model="formObj.name"
              name="name"
              placeholder="请选择仪器名称"
              icon="plus-circled"
              readonly
              @click.native="_selEquip"
            />
          </Form-item>
          <Form-item label="规格型号" prop="spec" class="search-item">
            <Input v-model="formObj.spec" name="spec" placeholder="请输入规格型号" readonly />
          </Form-item>
          <Form-item label="制造厂商" prop="productPlace" class="search-item">
            <Input v-model="formObj.productPlace" name="productPlace" placeholder="请输入产地" readonly />
          </Form-item>
          <Form-item label="仪器编号" prop="equipNum" class="search-item">
            <Input v-model="formObj.equipNum" name="equipNum" placeholder="请输入仪器编号" readonly />
          </Form-item>
          <Alert type="success">
            <h4 align="center">
              仪器使用信息
            </h4>
          </Alert>

          <Form-item label="使用开始时间" prop="useStartTime" class="search-item">
            <Date-picker
              v-model="formObj.useStartTime"
              name="useStartTime"
              type="datetime"
              placeholder="使用开始时间"
              :editable="false"
              format="yyyy-MM-dd HH:mm"
              style="width: 100%;"
            />
          </Form-item>
          <Form-item label="使用结束时间" prop="useEndTime" class="search-item">
            <Date-picker
              v-model="formObj.useEndTime"
              name="useEndTime"
              type="datetime"
              placeholder="使用结束时间"
              :editable="false"
              format="yyyy-MM-dd HH:mm"
              style="width: 100%;"
            />
          </Form-item>
          <Form-item label="开始性能" prop="performanceStart" class="search-item">
            <Input v-model="formObj.performanceStart" name="performanceStart" placeholder="请输入开始性能" />
          </Form-item>
          <Form-item label="结束性能" prop="performanceEnd" class="search-item">
            <Input v-model="formObj.performanceEnd" name="performanceEnd" placeholder="请输入结束性能" />
          </Form-item>
          <Form-item label="使用原因" prop="reason" style="width: 44%;">
            <Input v-model="formObj.reason" name="reason" placeholder="请输入使用原因" /></Input>
          </Form-item>
          <Form-item label="备注" prop="remark" style="width: 44%;">
            <Input v-model="formObj.remark" name="remark" placeholder="请输入产品备注" type="textarea" :rows="1" />
          </Form-item>
          <Form-item label="使用人" prop="userId" style="width: 44%">
            <Select
              ref="userSelect"
              v-model="formObj.userId"
              clearable
              label-in-value
              @on-change="_changeUser"
            >
              <Option v-for="item in userList" :key="item.id" :value="item.id">
                {{ item.realname }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="相关配件情况" prop="parts" style="width: 44%;">
            <Input v-model="formObj.parts" name="parts" placeholder="请输入相关配件情况" /></Input>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <Button type="ghost" style="margin-left: 8px" @click="_cancel">
          取消
        </Button>
        <Button type="warning" @click="_validateDate(0)">
          草稿
        </Button>
        <Button type="primary" @click="_validateDate(1)">
          提交
        </Button>
      </div>
    </Modal>
    <!--    &lt;!&ndash;选择仪器信息&ndash;&gt;-->
    <!--    <RelLmsEquipInfo ref="equipModal" @on-result-change="_equipData" />-->
  </div>
</template>
<script>
// import RelLmsEquipInfo from './RelLmsEquipInfo.vue'
import { equipUseRecord, sysUser } from '../../../../api'
import global from '../../../../api/config'

/**
 * 添加编辑仪器使用记录信息表
 */
export default {
  components: {
    // RelLmsEquipInfo
  },
  data() {
    const validateUseStartTime = (rule, value, callback) => {
      if (this.formObj.useStartTime === '') {
        callback(new Error('使用开始时间不能为空'))
      } else {
        callback()
      }
    }
    const validateUseEndTime = (rule, value, callback) => {
      if (this.formObj.useEndTime === '') {
        callback(new Error('使用结束时间不能为空'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      modalTitle: '',
      formObj: {
        name: '',
        spec: '',
        productPlace: '',
        equipNum: '',
        equipId: '',
        status: '',
        useStartTime: '',
        useEndTime: '',
        performanceStart: '',
        performanceEnd: '',
        userId: '',
        userName: '',
        reason: '',
        remark: '',
        parts: ''
      },
      ruleValidate: {
        name: [
          { required: true, message: '仪器名称不能为空', trigger: 'change' }
        ],
        useStartTime: [
          { required: true, validator: validateUseStartTime, trigger: 'change' }
        ],
        useEndTime: [
          { required: true, validator: validateUseEndTime, trigger: 'change' }
        ],
        userId: [
          { required: true, message: '使用人不能为空', trigger: 'change' }
        ]
      },
      showEditModal: false,
      userList: [],
      labList: []
    }
  },
  methods: {
    _getUserList: async function() {
      // // 用户列表
      // this.$store.dispatch('LmsEquipUseRecord/userList').then(() => {
      //   this.userList = []
      //   const user = global.getUserInfo()
      //   this.userList = this.$store.state.LmsEquipUseRecord.userList
      //   if (this.userList.indexOf(user.id) === -1) {
      //     this.userList.push({ id: user.id, realname: user.realname })
      //   }
      // })
      const result = await sysUser.list({})
      if (result) {
        this.userList = result
        const user = global.getUserInfo()
        if (this.userList.indexOf(user.id) === -1) {
          this.userList.push({ id: user.id, realname: user.realname })
        }
      }
    },
    _resultChange(msg) {
      this.formObj.userId = ''
      this.showEditModal = false
      this.$Message.success(msg)
      // this.$emit('on-result-change')
    },
    _changeUser(data) {
      this.formObj.userId = data.value
      this.formObj.userName = data.label
    },
    _validateDate(status) {
      if (this.formObj.useStartTime === '' && this.formObj.useEndTime !== '') {
        this.$Message.warning('请输入使用开始时间')
      } else if (
        this.formObj.useStartTime !== '' &&
        this.formObj.useEndTime === ''
      ) {
        this.$Message.warning('请输入使用结束时间')
      } else if (
        this.formObj.useStartTime !== '' &&
        this.formObj.useEndTime !== ''
      ) {
        if (this.formObj.useStartTime >= this.formObj.useEndTime) {
          this.$Message.warning('使用结束时间不能小于等于使用开始时间')
        } else {
          this._ok(status)
        }
      } else {
        this._ok(status)
      }
    },
    _ok(status) {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          this.$extend(data, {
            status: status,
            equipId: this.formObj.equipId,
            userName: this.formObj.userName,
            userId: this.formObj.userId
          })
          if (this.$string(this.id).isEmpty()) {
            // 添加
            // this.$store.dispatch('LmsEquipUseRecord/add', data).then(() => {
            //   this._resultChange('添加成功!')
            // })
            this._save(data)
          } else {
            // 编辑
            // this.$store
            //   .dispatch('LmsEquipUseRecord/edit', {
            //     id: this.formObj.id,
            //     obj: data
            //   })
            //   .then(() => {
            //     this._resultChange('编辑成功!')
            //   })
            this._edit({
              id: this.formObj.id,
              obj: data
            })
          }
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },

    _save: async function(data) {
      const result = await equipUseRecord.add(data)
      if (result) {
        this._resultChange('添加成功')
      }
    },
    _edit: async function(data) {
      const result = await equipUseRecord.edit(data)
      if (result) {
        this._resultChange('添编辑成功')
      }
    },

    _cancel() {
      this.showEditModal = false
    },
    _open(formObj) {
      this.showEditModal = true
      this.formObj.userId = ''
      this.$refs.formObj.resetFields()
      this._getUserList()
      if (this.$string(formObj).isEmpty()) {
        this.id = ''
        this.$refs.userSelect.clearSingleSelect()
        this.modalTitle = '添加仪器使用记录信息表'
      } else {
        console.log(formObj)
        this.id = formObj.id
        this.formObj = formObj
        this._showTime()
        this.modalTitle = '编辑仪器使用记录信息表'
      }
    },
    _selEquip() {
      this.$refs.equipModal._open()
    },
    _equipData(result) {
      console.log(result)
      this.formObj.equipId = result.id
      this.formObj.name = result.name
      this.formObj.spec = result.spec
      this.formObj.productPlace = result.productPlace
      this.formObj.equipNum = result.labNum
    },
    _showTime() {
      if (this.formObj.useStartTime === undefined) {
        this.formObj.useStartTime = ''
      } else {
        this.formObj.useStartTime = new Date(this.formObj.useStartTime)
      }

      if (this.formObj.useEndTime === undefined) {
        this.formObj.useEndTime = ''
      } else {
        this.formObj.useEndTime = new Date(this.formObj.useEndTime)
      }
    }
  }
}
</script>
