<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="maintainStartTimePlan" style="width: 25%;">
            <Date-picker
              v-model="formObj.maintainStartTimePlan"
              name="maintainStartTimePlan"
              type="datetime"
              placeholder="保养开始时间"
              :editable="false"
              style="width: 100%;"
              format="yyyy-MM-dd HH:mm"
            />
          </Form-item>
          <Form-item label="计划保养结束时间" prop="maintainEndTimePlan" style="width: 25%;">
            <Date-picker
              v-model="formObj.maintainEndTimePlan"
              name="maintainEndTimePlan"
              type="datetime"
              placeholder="保养结束时间"
              :editable="false"
              style="width: 100%;"
              format="yyyy-MM-dd HH:mm"
            />
          </Form-item>
          <Form-item label="保养内容" prop="maintainContent" style="width: 24%;">
            <autoComplete
              v-model="formObj.maintainContent"
              name="maintainContent"
              :down-data="maintainContentList"
              placeholder="请选择保养内容"
              @on-result-change="_maintainContentChange"
            />
          </Form-item>
          <Form-item label="负责人" prop="maintainerNames" style="width: 24%;">
            <Select
              v-model="formObj.maintainerNames"
              filterable
              clearable
              placeholder="请选择负责人"
              @on-change="_maintainerChange"
            >
              <Option v-for="item in maintainerList" :key="item.name" :value="item.name">
                {{ item.name }}
              </Option>
            </Select>
          </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.maintainId" name="maintainId" type="hidden">
          <input v-model="formObj.maintainerIds" name="maintainerIds" type="hidden">
          <input v-model="formObj.maintainerNames" name="maintainerNames" 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 autoComplete from '../../../../components/base/autoComplete.vue'
import { equip, equipMaintain, sysUser } from '../../../../api'
import global from '../../../../api/config'
const defVal = {
  // 展示
  name: '',
  equipNum: '',
  labNum: '',
  buyDate: '',
  effectDate: '',

  equipId: '',
  maintainId: '',
  maintainContent: '',
  remark: '',
  maintainStartTimePlan: '',
  maintainEndTimePlan: '',
  maintainerIds: '',
  maintainerNames: ''
}
export default {
  components: { autoComplete },
  data() {
    const validateStartDate = (rule, value, callback) => {
      if (this.formObj.maintainStartTimePlan === '') {
        callback(new Error('计划保养开始时间不能为空'))
      } else {
        callback()
      }
    }
    const validateEndDate = (rule, value, callback) => {
      if (this.formObj.maintainEndTimePlan === '') {
        callback(new Error('计划保养结束时间不能为空'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      modalTitle: '',
      formObj: defVal,
      ruleValidate: {
        maintainContent: [
          { required: true, message: '保养内容不能为空', trigger: 'change' }
        ],
        maintainStartTimePlan: [
          { required: true, validator: validateStartDate, trigger: 'change' }
        ],
        maintainEndTimePlan: [
          { required: true, validator: validateEndDate, trigger: 'change' }
        ],
        maintainerNames: [
          {
            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')
    },
    _validateDate() {
      const date = new Date()
      if (this.formObj.maintainStartTimePlan <= date) {
        this.$Message.warning('保养开始时间不能早于当前系统时间')
        return false
      } else if (
        this.formObj.maintainStartTimePlan >= this.formObj.maintainEndTimePlan
      ) {
        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 equipMaintain.addDetail(data)
      if (result) {
        this._resultChange('添加成功')
      }
    },

    _cancel() {
      this.showEditModal = false
    },
    _open(maintainId, 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.maintainId = maintainId
      alert(this.formObj.maintainId)
      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.maintainContent = data
          break
        default:
          this.formObj.maintainContent = 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.maintainerNames = data
    }
  }
}
</script>
