<template>
  <div>
    <Modal v-model="showEditModal" :mask-closable="false" :width="1200">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Row>
          <Col span="24" />
          <Form id="equipInfo-search-form" inline onsubmit="return false" :label-width="90">
            <Form-item class="width-23" label="仪器名称:" style="margin-bottom: 0">
              <Input name="name" placeholder="请输入仪器名称" @on-enter="_search" /></Input>
            </Form-item>
            <Form-item class="marleft-90">
              <Button type="primary" @click="_search">
                搜索
              </Button>
            </Form-item>
          </Form>
          </Col>
          <!-- 表格 -->
          <Col span="24" style="margin-bottom: 10px" />
          <element-table
            ref="pageTable"
            :page-columns="pageColumns"
            :table-height="400"
            :get-page="getPage"
            :opt-col-width="80"
            show-check-box
            @on-result-change="_tableResultChange"
          >
            <el-table-column
              v-for="item in pageColumns"
              :key="item.key"
              show-overflow-tooltip
              sortable
              :prop="item.key"
              :label="item.title"
              :min-width="item.width"
              :fixed="item.fixed?item.fixed:undefined"
            >
              <template slot-scope="scope">
                <div v-if="item.detail">
                  <a @click.stop="_detailModal(scope.row.id)">{{ scope.row[item.key] }}</a>
                </div>
                <!--                <div v-else-if="item.status">-->
                <!--                  <span v-for="items in status" v-if="items.val ===scope.row[item.key]">{{ items.title }}</span>-->
                <!--                </div>-->
                <div v-else-if="item.date">
                  {{ scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'):'' }}
                </div>
                <div v-else>
                  {{ scope.row[item.key] }}
                </div>
              </template>
            </el-table-column>
          </element-table>
          </Col>
        </Row>
      </div>
      <div>
        <Form
          id="maintain-detail-form-edit"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="120"
          inline
        >
          <Alert type="success" style="text-align: center;">
            仪器维保信息
          </Alert>

          <Form-item label="计划核查开始时间" prop="checkStartTimePlan" style="width: 25%;">
            <Date-picker
              v-model="formObj.checkStartTimePlan"
              name="checkStartTimePlan"
              type="datetime"
              placeholder="核查开始时间"
              :editable="false"
              style="width: 100%;"
              format="yyyy-MM-dd HH:mm"
            />
          </Form-item>
          <Form-item label="计划核查结束时间" prop="checkEndTimePlan" style="width: 25%;">
            <Date-picker
              v-model="formObj.checkEndTimePlan"
              name="checkEndTimePlan"
              type="datetime"
              placeholder="核查结束时间"
              :editable="false"
              style="width: 100%;"
              format="yyyy-MM-dd HH:mm"
            />
          </Form-item>
          <Form-item label="核查内容" prop="checkContent" style="width: 24%;">
            <Input v-model="formObj.checkContent" name="checkContent" placeholder="请输入核查内容" />
          </Form-item>
          <Form-item label="负责人" prop="checkName" style="width: 24%;">
            <Select
              v-model="formObj.checkName"
              filterable
              clearable
              placeholder="请选择负责人"
              @on-change="_maintainerChange"
            >
              <Option v-for="item in userList" :key="item.realname" :value="item.realname">
                {{ item.realname }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="核查频次" prop="checkRate" style="width: 33%;">
            <Input v-model="formObj.checkRate" name="checkRate" placeholder="请输入核查频次" />
          </Form-item>
          <Form-item label="核查方法" prop="checkWays" style="width: 33%;">
            <Input v-model="formObj.checkWays" name="checkWays" placeholder="请输入核查方法" />
          </Form-item>
          <Form-item label="核查结果判定方法" prop="decideMethod" style="width: 33%;">
            <Input v-model="formObj.decideMethod" name="decideMethod" placeholder="请输入核查结果判定方法" />
          </Form-item>
          <Form-item label="备注" prop="remark" style="width: 98.8%;">
            <Input v-model="formObj.remark" name="remark" placeholder="请输入备注信息" type="textarea" :rows="1" />
          </Form-item>
          <input v-model="formObj.equipId" name="equipId" type="hidden">
          <input v-model="formObj.checkId" name="checkId" type="hidden">
          <input v-model="formObj.maintainerIds" name="maintainerIds" type="hidden">
          <input v-model="formObj.checkName" name="checkName" type="hidden">
        </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 { equip, equipCheck, sysUser } from '../../../../api'
import global from '../../../../api/config'
const defVal = {
  // 展示
  name: '',
  equipNum: '',
  labNum: '',
  buyDate: '',
  effectDate: '',

  equipId: '',
  checkId: '',
  checkContent: '',
  remark: '',
  checkStartTimePlan: '',
  checkEndTimePlan: '',
  maintainerIds: '',
  checkName: '',
  checkRate: '',
  checkWays: '',
  decideMethod: ''
}
export default {
  components: {},
  data() {
    const validateStartDate = (rule, value, callback) => {
      if (this.formObj.checkStartTimePlan === '') {
        callback(new Error('计划核查开始时间不能为空'))
      } else {
        callback()
      }
    }
    const validateEndDate = (rule, value, callback) => {
      if (this.formObj.checkEndTimePlan === '') {
        callback(new Error('计划核查结束时间不能为空'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      modalTitle: '',
      formObj: defVal,
      ruleValidate: {
        checkContent: [
          { required: true, message: '核查内容不能为空', trigger: 'change' }
        ],
        checkStartTimePlan: [
          { required: true, validator: validateStartDate, trigger: 'change' }
        ],
        checkEndTimePlan: [
          { required: true, validator: validateEndDate, trigger: 'change' }
        ],
        checkName: [
          {
            required: true,
            message: '核查人不能为空',
            trigger: 'change',
            type: 'string'
          }
        ]
      },
      pageParams: {
        rows: 20
      },
      selectIds: [],
      showEditModal: false,
      userList: [],
      getPage: {},
      maintainerList: [],
      //  仪器名称List
      nameList: [],
      equipNumArr: [],
      //  保养内容
      maintainContentList: [],
      typeDetails: '', // 区分保养计划编辑添加和添加
      pageColumns: [
        { title: '仪器类别', key: 'className', width: 160, align: 'center' },
        { title: '仪器名称', key: 'name', width: 160, align: 'center' },
        { title: '仪器编号', key: 'labNum', width: 160, align: 'center' },
        { title: '规格型号', key: 'spec', width: 160, align: 'center' },
        { title: '制造厂商', width: 200, key: 'productPlace', align: 'center' },
        { title: '仪器品牌', key: 'brand', width: 160, align: 'center' },
        { title: '证书编号', key: 'ceNum', width: 160, align: 'center' },
        { title: '出厂编号', key: 'equipNum', width: 160, align: 'center' },
        {
          title: '使用科别',
          key: 'departmentName',
          width: 160,
          align: 'center'
        },
        { title: '使用地点', key: 'locationName', width: 160, align: 'center' },
        { title: '检定周期（月）', key: 'period', width: 160, align: 'center' },
        {
          title: '购买日期',
          key: 'buyDate',
          width: 160,
          date: true
        },
        {
          title: '有效日期',
          key: 'effectDate',
          width: 160,
          date: true
        },
        {
          title: '供应商名称',
          key: 'supplierName',
          width: 160,
          align: 'center'
        }
      ]
    }
  },
  mounted() {
    this._getUserList()
  },
  methods: {
    _getUserList: async function() {
      this.userList = await sysUser.list()
    },
    _resultChange(msg) {
      this.$Message.success(msg)
      this.showEditModal = false
      this.$emit('on-result-change', this.formObj.checkId)
    },
    _validateDate() {
      const date = new Date()
      if (this.formObj.repairStartTimePlan <= date) {
        this.$Message.warning('保养开始时间不能早于当前系统时间')
        return false
      } else if (
        this.formObj.repairStartTimePlan >= this.formObj.repairEndTimePlan
      ) {
        this.$Message.warning('保养结束时间不能早于保养开始时间')
        return false
      } else {
        return true
      }
    },
    _ok() {
      if (this.selectIds.length !== 0) {
        this.$refs.formObj.validate(valid => {
          valid = this._validateDate()
          if (valid) {
            const data = this.$serialize('maintain-detail-form-edit')
            // 添加
            if (this.$string(this.id).isEmpty()) {
              if (this.typeDetails === 1) {
                this._save({
                  equipIds: this.selectIds,
                  obj: data
                })
                // this.$store
                //   .dispatch('LmsEquipMaintain/addDetail', {
                //     equipIds: this.selectIds,
                //     obj: data
                //   })
                //   .then(() => {
                //     if (this.$store.state.LmsEquipMaintain.success) {
                //       this._resultChange('添加成功')
                //     }
                //   })
              } else {
                // this.$store
                //   .dispatch('LmsEquipMaintain/equipAddDetail', {
                //     equipIds: this.selectIds,
                //     obj: data
                //   })
                //   .then(() => {
                //     if (this.$store.state.LmsEquipMaintain.success) {
                //       this._resultChange('添加成功')
                //     }
                //   })
              }
            }
          } else {
            this.$Message.error('表单验证失败!')
          }
        })
      } else {
        this.$Message.warning('请选择仪器!')
      }
    },

    _save: async function(data) {
      const result = await equipCheck.addDetail(data)
      if (result) {
        this._resultChange('添加成功')
      }
    },

    _cancel() {
      this.showEditModal = false
    },
    _open(checkId, formObj, num) {
      this.showEditModal = true
      this.typeDetails = num
      this._pageClear()
      this._page()
      this._openSearchEquipMaintainContent()
      this._openSearchEquipMaintainer()
      this.selectIds = []
      this.formObj = defVal
      this.$refs.formObj.resetFields()
      this.maintainerList = []
      this.formObj.checkId = checkId
      if (this.$string(formObj).isEmpty()) {
        this.id = ''
        this.modalTitle = '添加仪器保养明细'
      }
    },
    _search() {
      this.$refs.pageTable._pageChange(1)
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      const result = await equip.page(this.$serializeForm(this.formObj))
      if (result) {
        this.getPage = result
        this.$refs.pageTable._initTable()
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          break
        case 'selectIds':
          this.selectIds = data
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData)
          break
        default:
          this._page()
      }
    },
    // 清楚搜索条件内容
    _pageClear() {
      $('#equipInfo-search-form')
        .find('input')
        .each(function() {
          $(this).val('')
        })
    },
    _equipData(result) {
      this.formObj.equipId = result.id
      this.formObj.equipNum = result.equipNum
      this.formObj.labNum = result.labNum
      this.formObj.buyDate = result.buyDate ? new Date(result.buyDate) : ''
      this.formObj.effectDate = result.effectDate
        ? new Date(result.effectDate)
        : ''
    },
    //  保养内容 maintainContent
    _openSearchEquipMaintainContent(maintainContent = '') {
      // const data = {
      //   name: '保养内容',
      //   value: maintainContent
      // }
      // this.$store
      //   .dispatch('LmsEquipMaintain/maintianEquipNumList', data)
      //   .then(() => {
      //     const maintainContentList = this.$store.state.LmsEquipMaintain
      //       .fileList
      //     const maintainContentArray = []
      //     for (let i = 0; i < maintainContentList.length; i++) {
      //       maintainContentArray.push(maintainContentList[i].maintainContent)
      //     }
      //     this.maintainContentList = maintainContentArray
      //   })
    },
    // 保养内容
    _maintainContentChange(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.reason = data
          break
        default:
          this.formObj.reason = data
          this._openSearchEquipMaintainContent(data)
          break
      }
    },
    // 负责人
    _openSearchEquipMaintainer: async function() {
      const result = await sysUser.list({})
      const registrantList = result
      const maintainerArray = []
      for (let i = 0; i < registrantList.length; i++) {
        maintainerArray.push({ name: registrantList[i].realname })
      }
      if (maintainerArray.indexOf(this.formObj.realname) === -1) {
        maintainerArray.push({ name: global.getUserInfo().realname })
      }
      this.maintainerList = maintainerArray
    },
    // 负责人
    _maintainerChange(data) {
      this.formObj.repairerNames = data
    }
  }
}
</script>
