<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showEditModal"
      :close-on-click-modal="false"
      :title="modalTitle"
      width="1200px"
    >
      <div>
        <Form
          id="edit-form"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="80"
          inline
        >
          <Form-item label="仪器类别" prop="className" class="search-item">
            <el-input
              v-model="formObj.className"
              readonly
              placeholder="请选择仪器类别"
              @click.native="_selectZtree"
            />
            <input v-model.number="formObj.classId" name="classId" hidden>
          </Form-item>
          <Form-item label="仪器名称" prop="name" class="search-item">
            <el-input v-model="formObj.name" name="name" placeholder="请输入名称" clearable />
          </Form-item>
          <Form-item label="仪器编号" prop="labNum" class="search-item">
            <Input v-model="formObj.labNum" name="labNum" placeholder="请输入仪器编号" />
          </Form-item>

          <Form-item label="仪器品牌" prop="brand" class="search-item">
            <autoComplete
              name="brand"
              :down-data="brandList"
              :value="formObj.brand"
              placeholder="请选择仪器品牌"
              @on-result-change="_brandChange"
            />
          </Form-item>


          <Form-item label="供应商名称" prop="supplier" class="search-item">
            <Select
              v-model="formObj.supplierId"
              name="supplierId"
              filterable
              clearable
              placeholder="请选择供应商"
              style="width:100%"
            >
              <Option v-for="item in supplierList" :key="item.id" :value="item.id">
                {{ item.name }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="仪器价格" prop="price" class="search-item">
            <InputNumber v-model="formObj.price" name="price" style="width:100%" />
          </Form-item>
          <Form-item label="规格型号" prop="spec" class="search-item">
            <autoComplete
              name="spec"
              :down-data="specList"
              :value="formObj.spec"
              placeholder="请选择规格型号"
              @on-result-change="_specChange"
            />
          </Form-item>
          <Form-item label="制造厂商" prop="productPlace" class="search-item">
            <autoComplete
              name="productPlace"
              :down-data="productPlaceList"
              :value="formObj.productPlace"
              placeholder="请选择制造厂商"
              @on-result-change="_productPlaceChange"
            />
          </Form-item>


          <Form-item label="计量类别" prop="meterType" class="search-item">
            <autoComplete
              name="meterType"
              :down-data="meterTypeList"
              :value="formObj.meterType"
              placeholder="请选择或输入计量类别"
              @on-result-change="_meterTypeChange"
            />
          </Form-item>
          <Form-item label="精确度等级" prop="uncertainty" class="search-item">
            <autoComplete
              name="uncertainty"
              :down-data="uncertaintyList"
              :value="formObj.uncertainty"
              placeholder="请选择或输入精确度等级"
              @on-result-change="_uncertaintyChange"
            />
          </Form-item>
          <Form-item label="分辨力" prop="accuracy" class="search-item">
            <autoComplete
              name="accuracy"
              :down-data="accuracyList"
              :value="formObj.accuracy"
              placeholder="请选择或输入分辨力"
              @on-result-change="_accuracyChange"
            />
          </Form-item>



          <Form-item label="使用范围" prop="range" class="search-item">
            <autoComplete
              name="range"
              :down-data="rangeList"
              :value="formObj.range"
              placeholder="请选择或输入使用范围"
              @on-result-change="_rangeChange"
            />
          </Form-item>
          <Form-item label="设备管理人" prop="equipAdminId" class="search-item">
            <Select
              v-model="formObj.equipAdminId"
              filterable
              clearable
              label-in-value
              @on-change="_equipAdminChange"
            >
              <Option v-for="item in userList" :key="item.id" :value="item.id">
                {{ item.realname }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="仪器状态" prop="status" class="search-item" style="margin-left: 4px;">
            <Select v-model="formObj.status" clearable>
              <Option v-for="item in statusList" :key="item.value" :value="item.value">
                {{ item.name }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="出厂编号" prop="equipNum" class="search-item">
            <Input v-model="formObj.equipNum" name="equipNum" placeholder="请选输入出厂编号" />
          </Form-item>


          <Form-item label="证书编号" prop="ceNum" class="search-item">
            <Input v-model="formObj.ceNum" name="ceNum" placeholder="请输入证书编号" />
          </Form-item>

          <Form-item label="使用科别" prop="departmentName" class="search-item">
            <Input
              v-model="departmentName"
              name="departmentName"
              placeholder="请选择科别..."
              @click.native="_selectOrgZtree"
            />
          </Form-item>
          <Form-item label="仪器位置" prop="locationName" class="search-item">
            <Input
              v-model="locationName"
              name="locationName"
              placeholder="请选择位置..."
              @click.native="_selectLocationZtree"
            />
          </Form-item>
          <Form-item label="检定周期（月）" prop="period" class="search-item">
            <InputNumber v-model="formObj.period" name="period" :min="1" style="width:100%" />
          </Form-item>



          <Form-item label="购买日期" prop="buyDate" class="search-item">
            <Date-picker
              v-model="formObj.buyDate"
              name="buyDate"
              type="date"
              placeholder="购买日期"
              format="yyyy-MM-dd"
              style="width: 100%;"
            />
          </Form-item>


          <Form-item label="接收日期" prop="receiveDate" class="search-item">
            <Date-picker
              v-model="formObj.receiveDate"
              name="receiveDate"
              type="date"
              placeholder="接收日期"
              format="yyyy-MM-dd"
              style="width: 100%;"
            />
          </Form-item>
          <Form-item label="启用日期" prop="startUseDate" class="search-item">
            <Date-picker
              v-model="formObj.startUseDate"
              name="startUseDate"
              type="date"
              placeholder="启用日期"
              format="yyyy-MM-dd"
              style="width: 100%;"
            />
          </Form-item>
          <Form-item label="有效日期" prop="effectDate" class="search-item">
            <Date-picker
              v-model="formObj.effectDate"
              name="effectDate"
              type="date"
              placeholder="有效日期"
              format="yyyy-MM-dd"
              style="width: 100%;"
            />
          </Form-item>
          <Form-item label="期间核查周期（月）" prop="periodCheckCycle" class="search-item">
            <InputNumber
              v-model="formObj.periodCheckCycle"
              name="periodCheckCycle"
              :min="1"
              style="width:100%"
            />
          </Form-item>
          <Form-item label="仪器来源" prop="source" class="search-item" style="margin-left: 4px;">
            <Select v-model="formObj.source" clearable>
              <Option v-for="item in sourceList" :key="item.value" :value="item.value">
                {{ item.value }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="用途" prop="purpose" style="width: 98.6%;">
            <Input v-model="formObj.purpose" name="purpose" placeholder="请输入用途" type="textarea" :rows="1" />
          </Form-item>


          <Form-item label="数据采集类型" prop="acquisitionType" class="search-item">
            <Input v-model="formObj.acquisitionType" name="acquisitionType" placeholder="数据采集类型" />
          </Form-item>

          <Form-item label="数据采集地址" prop="acquisitionAddress">
            <Input
              v-model="formObj.acquisitionAddress"
              name="acquisitionAddress"
              type="textarea"
              :rows="3"
              placeholder="请输入数据采集地址"
            />
          </Form-item>

          <Form-item label="IP地址" prop="ipAddress">
            <Input v-model="formObj.ipAddress" name="ipAddress" type="textarea" :rows="3" placeholder="请输入IP地址" />
          </Form-item>
          <Form-item label="数据采集命令" prop="acquisitionCommand">
            <Input v-model="formObj.acquisitionCommand" name="acquisitionCommand" type="textarea" :rows="3" placeholder="请输入数据采集命令" />
          </Form-item>



          <Form-item label="备注" prop="remark" class="search-item">
            <el-input v-model="formObj.remark" name="remark" placeholder="请输入备注" />
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </el-dialog>
    <!--选择上级菜单tree-->
    <selectResourceTree ref="treeModal" @on-result-change="_treeData" />
    <!--选择图标-->
    <icons ref="iconsModal" @on-result-change="_iconsData" />
  </div>
</template>
<script>
/**
 * 添加编辑菜单表
 */
import { equipInfo, supplier } from '../../../api'
import icons from '../../../components/base/icons'
import selectResourceTree from './tree/selectEquipLocationTree'

export default {
  components: { selectResourceTree, icons },
  data() {
    return {
      id: '',
      modalTitle: '添加',
      formObj: {
        source: '购买',
        id: '',
        supplierId: '',
        classId: '',
        name: '',
        status: 0,
        spec: '',
        brand: '',
        price: '',
        productPlace: '',
        meterType: '',
        uncertainty: '',
        accuracy: '',
        range: '',
        techParams: '',
        techParamsText: '',
        equipNum: '',
        ceNum: '',
        labNum: '',
        departmentId: '',
        locationId: '',
        locationName: '',
        period: 12,
        periodCheckCycle: 6,
        buyDate: new Date(),
        receiveDate: new Date(),
        startUseDate: new Date(),
        effectDate: '',
        equipAdminId: '',
        equipAdminName: '',
        remark: '',
        purpose: '',
        departmentName: '',
        type: '1',
        classIds: '',
        lmsEquipFiles: [],
        acquisitionType: '',
        acquisitionAddress: '',
        ipAddress: '',
        acquisitionTypeList: [
          { value: '导出文件', name: '导出文件' },
          { value: '数据转接口', name: '数据转接口' },
          { value: 'mdb数据库', name: 'mdb数据库' },
          { value: '网口命令', name: '网口命令' }
        ],
        className: '',
        acquisitionCommand: '',
        acquisitionParser: ''
      },
      ruleValidate: {
        code: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
        icon: [{ required: true, message: '图标不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        sort: [
          {
            required: true,
            message: '排序不能为空',
            trigger: 'blur',
            type: 'number'
          }
        ],
        uri: [{ required: true, message: '路径不能为空', trigger: 'blur' }]
      },
      showEditModal: false,
      supplierList: [],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ],
      typeList: [{ value: 0, name: 'PC 菜单' }, { value: 2, name: 'APP 菜单' }],
      statusList: [{ value: 1, name: '正常' }, { value: 0, name: '禁用' }]
    }
  },
  methods: {
    // modal
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '保存':
          this._ok()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _resultChange(result, msg) {
      if (result) {
        this.showEditModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          data.status = this.formObj.status
          data.type = this.formObj.type
          data.classId = this.formObj.classId
          if (this.formObj.systemId) {
            data.systemId = this.formObj.systemId
          }
          this._save(data)
        } else {
          this.$message.error('表单验证失败')
          this._hideLoading()
        }
      })
    },
    // 添加、编辑保存
    _save: async function(data) {
      // 添加、编辑
      if (this.$string(this.id).isEmpty()) {
        const result = await equipInfo.add(data)
        this._resultChange(result, '添加成功')
      } else if (
        this.$judgeClassify({ id: this.id, classifyId: this.formObj.pid })
      ) {
        const result = await equipInfo.edit({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功')
      } else {
        this.$message.warning('上级菜单与菜单名不能重复，请重新选择~')
        this._hideLoading()
      }
    },
    _cancel() {
      this.showEditModal = false
    },
    _dateFormat: function(time) {
      const date = new Date(time)
      const year = date.getFullYear()
      /* 在日期格式中，月份是从0开始的，因此要加0
           * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
           * */
      const month =
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      const hours =
        date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      const minutes =
        date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      const seconds =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      // 拼接
      return (
        year +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hours +
        ':' +
        minutes +
        ':' +
        seconds
      )
    },
    _open(treeObj, formObj) {
      this._getSupplierList()
      this.showEditModal = true
      this.$nextTick(() => {
        this.$refs.formObj.resetFields()
        this._hideLoading()
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.modalTitle = '添加类别'
          if (JSON.stringify(treeObj) !== '{}') {
            $('input[name=classId]').val(treeObj.id)
            this.formObj.classId = treeObj.id
            this.formObj.className = treeObj.name
          } else {
            this.formObj.classId = '0'
            this.formObj.className = ''
          }
        } else {
          this.id = formObj.id
          if (undefined !== formObj.buyDate) {
            formObj.buyDate = this._dateFormat(formObj.buyDate)
          }
          if (undefined !== formObj.receiveDate) {
            formObj.receiveDate = this._dateFormat(formObj.receiveDate)
          }

          if (undefined !== formObj.startUseDate) {
            formObj.startUseDate = this._dateFormat(formObj.startUseDate)
          }
          if (undefined !== formObj.effectDate) {
            formObj.effectDate = this._dateFormat(formObj.effectDate)
          }
          if (undefined !== formObj.receiveDate) {
            formObj.receiveDate = this._dateFormat(formObj.receiveDate)
          }
          if (undefined !== formObj.receiveDate) {
            formObj.receiveDate = this._dateFormat(formObj.receiveDate)
          }

          this.formObj = formObj
          this.className = formObj.className
          this.modalTitle = '编辑菜单'
        }
      })
    },

    _getSupplierList: async function() {
      const result = await supplier.getList({})
      this.supplierList = result
    },
    // 选择系统返回
    _systemResult(data) {
      this.formObj.systemId = data
    },
    // 选择tree
    _selectZtree() {
      this.$refs.treeModal._open()
    },
    _treeData(result) {
      if (result === undefined) {
        // 未选中数据的时候
        this.formObj.classId = '0'
        this.formObj.className = ''
      } else {
        // 选中数据以后
        this.formObj.classId = result.id
        this.formObj.className = result.name
      }
    },
    // 选择图标
    _selectIcon() {
      this.$refs.iconsModal._open()
    },
    _iconsData(data) {
      this.formObj.icon = data
    }
  }
}
</script>
