<template>
  <div>
    <Modal v-model="showModal" v-drag :mask-closable="false" width="1200" :styles="{marginTop:'10px'}">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Form
          id="edit-form"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="85"
          inline
        >
          <Form-item label="耗材类别" prop="category" class="width-32">
            <el-input
              v-model="formObj.category"
              readonly
              placeholder="请选择仪器类别"
              @click.native="_selectZtree"
            />
            <input v-model.number="formObj.categoryId" name="categoryId" hidden>
          </Form-item>
          <Form-item label="耗材名称" prop="name" class="width-32">
            <el-input v-model="formObj.name" name="name" placeholder="请输入耗材名称" clearable />
          </Form-item>
          <Form-item label="耗材编号" prop="num" class="width-32">
            <Input v-model="formObj.num" name="num" placeholder="请输入耗材编号" />
          </Form-item>

          <Form-item label="保存条件" prop="saveCondition" class="width-32">
            <Select v-model="formObj.saveCondition" name="saveCondition" placeholder="请选择保存条件">
              <Option v-for="item in saveConditionList" :key="item.name" :value="item.name">
                {{ item.name }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="保管人" prop="saver" class="width-32">
            <Input
              v-model="formObj.saver"
              name="saver"
              clearable
              readonly
              @click.native="_userChange"
            ></Input>
          </Form-item>
          <Form-item label="计量单位" prop="unit" class="width-32">
            <Input v-model="formObj.unit" name="unit" placeholder="请输入计量单位" />
          </Form-item>
          <Form-item label="转换率" prop="exchange" class="width-32">
            <InputNumber
              v-model.number="formObj.exchange"
              :min="1"
              name="exchange"
              style="width:100%"
              placeholder="请输入转换率"
            />
          </Form-item>
          <Form-item label="转换计量单位" prop="exunit" class="width-32">
            <Input v-model="formObj.exunit" name="exunit" placeholder="请输入转换计量单位" />
          </Form-item>
          <Form-item label="规格" prop="spec" class="width-32">
            <autoComplete
              name="spec"
              placeholder="请输入规格"
              :down-data="specList"
              :value="formObj.spec"
              @on-result-change="_specChange"
            />
          </Form-item>
          <Form-item label="密度" prop="thickness" class="width-32">
            <Input v-model="formObj.thickness" name="thickness" placeholder="请输入密度" />
          </Form-item>
          <Form-item label="制造厂商" prop="manufacturer" class="width-32">
<!--            <autoComplete-->
<!--              name="manufacturer"-->
<!--              placeholder="请输入制造厂商"-->
<!--              :down-data="manufacturerList"-->
<!--              :value="formObj.manufacturer"-->
<!--              @on-result-change="_manufacturerChange"-->
<!--            />-->
            <Input v-model="formObj.manufacturer" name="manufacturer" placeholder="请输入制造厂商" />
          </Form-item>
          <Form-item label="等级（纯度）" prop="quality" class="width-32">
<!--            <autoComplete-->
<!--              name="quality"-->
<!--              placeholder="请输入等级（纯度）"-->
<!--              :down-data="qualityList"-->
<!--              :value="formObj.quality"-->
<!--              @on-result-change="_qualityChange"-->
<!--            />-->
            <Input v-model="formObj.quality" name="quality" placeholder="请输入等级（纯度）" />
          </Form-item>
          <Form-item label="标准值" prop="standard" class="width-32">
<!--            <autoComplete-->
<!--              name="standard"-->
<!--              placeholder="请输入标准值"-->
<!--              :down-data="standardList"-->
<!--              :value="formObj.standard"-->
<!--              @on-result-change="_standardChange"-->
<!--            />-->
            <Input v-model="formObj.standard" name="standard" placeholder="请输入标准值" />
          </Form-item>
          <Form-item label="精确度等级" prop="unsure" class="width-32">
<!--            <autoComplete-->
<!--              name="unsure"-->
<!--              placeholder="请输入精确度等级"-->
<!--              :down-data="unsureList"-->
<!--              :value="formObj.unsure"-->
<!--              @on-result-change="_unsureChange"-->
<!--            />-->
            <Input v-model="formObj.unsure" name="unsure" placeholder="请输入精确度等级" />
          </Form-item>
          <Form-item label="仓库位置" prop="storehouse" class="width-32">

            <Input v-model="formObj.storehouse" name="storehouse" placeholder="请输入仓库位置" />
<!--            <Input-->
<!--              id="storehouse"-->
<!--              v-model.number="storeName"-->
<!--              name="storehouse"-->
<!--              icon="plus-circled"-->
<!--              readonly-->
<!--              placeholder="请选中仓库位置"-->
<!--              @on-click="_storeZtree"-->
<!--            /></Input>-->
          </Form-item>
          <Form-item label="最低库存量" prop="lowerStock" class="width-32">
            <InputNumber
              v-model.number="formObj.lowerStock"
              :min="0"
              name="lowerStock"
              style="width:100%"
              placeholder="请输入最低库存量"
              :formatter="value => value===''?value:(`${formObj.exunit}` === 'undefined' ?`${value}`:`${value}${formObj.exunit}`)"
              :parser="value => value.replace(`${formObj.exunit}`?`${formObj.exunit}`:'', '')"
            />
          </Form-item>
          <Form-item label="备注" prop="remark" class="width-32">
<!--            <autoComplete-->
<!--              name="remark"-->
<!--              placeholder="请输入备注"-->
<!--              :down-data="remarkList"-->
<!--              :value="formObj.remark"-->
<!--              @on-result-change="_remarkChange"-->
<!--            />-->

            <Input v-model="formObj.remark" name="remark" placeholder="请输入备注" />
          </Form-item>
          <Form-item class="width-23-2" label="使用部门:">
            <Input v-model="formObj.useDepartment" name="useDepartment" placeholder="请输入使用部门" ></Input>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </Modal>
    <!--选择上级菜单tree-->
    <selectResourceTree ref="treeModal" @on-result-change="_treeData" />
    <!--选择图标-->
    <icons ref="iconsModal" @on-result-change="_iconsData" />

    <!--选择人员-->
    <UserInfo ref="userModal" is-change @on-result-change="_userData" />
  </div>
</template>
<script>
/**
 * 添加编辑菜单表
 */
import { consumeLedger, dict } from '../../../api'
import icons from '../../../components/base/icons'
import UserInfo from '../../../components/user-info-single/assignPerson'
import selectResourceTree from './tree/selectCategoryTree'
export default {
  components: { selectResourceTree, icons, UserInfo },
  data() {
    return {
      id: '',
      modalTitle: '添加',
      formObj: {
        batchNo: '',
        price: '',
        id: '',
        typeId: '',
        name: '',
        num: '',
        spec: '',
        unsure: '',
        manufacturer: '',
        quality: '',
        standard: '',
        unit: '',
        exchange: '',
        exunit: '',
        remark: '',
        category: '',
        lowerStock: '',
        thickness: '',
        storehouse: '',
        useDepartment: '', // 使用部门
        saveCondition: '',
        saver: '',
        saverId: ''
      },
      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' }]
      },
      showModal: false,
      supplierList: [],
      saveConditionList: [],
      unitList: [],
      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.showModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this._hideLoading()
    },
    _userChange() {
      this.$refs.userModal._open('saver')
    },
    _userData(data, msg) {
      // 选择人员返回数据
      if (msg === 'saver') {
        // 选择取样人取样人
        this.formObj.saver = data.realname
        this.formObj.saverId = data.userId
      }
    },
    _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.categoryId = this.formObj.categoryId
          if (data.lowerStock) {
            data.lowerStock = parseFloat(this.formObj.lowerStock)
          }
          this._save(data)
        } else {
          this.$message.error('表单验证失败')
          this._hideLoading()
        }
      })
    },
    // 添加、编辑保存
    _save: async function(data) {
      // 添加、编辑
      if (this.$string(this.id).isEmpty()) {
        const result = await consumeLedger.add(data)
        this._resultChange(result, '添加成功')
      } else if (
        this.$judgeClassify({ id: this.id, classifyId: this.formObj.pid })
      ) {
        const result = await consumeLedger.edit({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功')
      } else {
        this.$message.warning('上级菜单与菜单名不能重复，请重新选择~')
        this._hideLoading()
      }
    },
    _cancel() {
      this.showModal = 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._getUnitList()
      this._getSaveCondition()
      this.showModal = true
      this.$nextTick(() => {
        this.$refs.formObj.resetFields()
        this._hideLoading()
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.modalTitle = '添加类别'
          if (JSON.stringify(treeObj) !== '{}') {
            $('input[name=categoryId]').val(treeObj.id)
            this.formObj.categoryId = treeObj.id
            this.formObj.category = treeObj.name
          } else {
            this.formObj.categoryId = '0'
            this.formObj.category = ''
          }
        } 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 = '编辑菜单'
        }
      })
    },

    _getUnitList: async function() {
      const result = await dict.getItem('耗材计量单位')
      this.unitList = result
    },
    _getSaveCondition: async function() {
      const result = await dict.getItem('耗材保存条件')
      this.saveConditionList = result
    },
    // 选择系统返回
    _systemResult(data) {
      this.formObj.systemId = data
    },
    // 选择tree
    _selectZtree() {
      this.$refs.treeModal._open()
    },
    _treeData(result) {
      if (result === undefined) {
        // 未选中数据的时候
        this.formObj.categoryId = '0'
        this.formObj.category = ''
      } else {
        // 选中数据以后
        this.formObj.categoryId = result.id
        this.formObj.category = result.name
      }
    },
    // 选择图标
    _selectIcon() {
      this.$refs.iconsModal._open()
    },
    _iconsData(data) {
      this.formObj.icon = data
    }
  }
}
</script>
