<template>
  <div>
    <Modal v-model="showModal" :mask-closable="false" :width="1000" class="zIndex-1100">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Alert style="text-align: center">
          仪器基本信息
        </Alert>
        <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 v-model="name" placeholder="请输入仪器名称" @on-enter="_formSearch" />
              </Form-item>
              <Form-item class="search-btn">
                <Button type="primary" @click="_formSearch">
                  搜索
                </Button>
              </Form-item>
            </Form>
            </Col>
            <!-- 表格 -->
            <Col span="24" style="margin-bottom: 10px">
            <element-table
              ref="pageTable"
              :table-height="300"
              :get-page="getPage"
              @on-result-change="_tableResultChange"
              show-check-box
            >
              <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.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>

        <Form
          id="repair-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="repairStartTimePlan" style="width: 31.5%;">
            <Date-picker
              v-model="formObj.repairStartTimePlan"
              name="repairStartTimePlan"
              type="datetime"
              placeholder="计划维修开始时间"
              :editable="false"
              style="width: 100%;"
              format="yyyy-MM-dd HH:mm"
            />
          </Form-item>
          <Form-item label="计划维修结束时间" prop="repairEndTimePlan" style="width: 31.5%;">
            <Date-picker
              v-model="formObj.repairEndTimePlan"
              name="repairEndTimePlan"
              type="datetime"
              placeholder="计划维修结束时间"
              :editable="false"
              style="width: 100%;"
              format="yyyy-MM-dd HH:mm"
            />
          </Form-item>
          <Form-item label="故障原因" prop="breakdown" style="width: 31.5%;">
            <autoCompletes
              v-model="formObj.breakdown"
              name="breakdown"
              show-key="breakdown"
              :down-data="breakdownList"
              placeholder="请选择故障原因内容"
              @on-result-change="_breakdownChange"
            />
          </Form-item>

          <Form-item label="故障时间" prop="failureTime" style="width: 31.5%;">
            <Date-picker
              v-model="formObj.failureTime"
              name="failureTime"
              type="datetime"
              placeholder="故障时间"
              :editable="false"
              style="width: 100%;"
              format="yyyy-MM-dd HH:mm"
            />
          </Form-item>
          <Form-item label="计划维修人" prop="repairerNames" style="width: 31.5%;">
            <autoCompletes
              v-model="formObj.repairerNames"
              name="repairerNames"
              show-key="repairerNames"
              :down-data="repairerNamesList"
              placeholder="计划维修人"
              @on-result-change="_repairerChange"
            />
          </Form-item>
          <Form-item label="备注" prop="remark" style="width: 31.5%;">
            <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.repairId" name="repairId" type="hidden">
          <input v-model="formObj.repairerIds" name="repairerIds" type="hidden">
        </Form>
      </div>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="_cancel">
          取消
        </Button>
        <Button type="primary" @click="_ok">
          确定
        </Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { equipInfo, equipRepairDetail } from '../../../../api'
import autoCompletes from '../../../../components/base/autoCompletes'

export default {
  components: { autoCompletes },
  data() {
    const validateStartDate = (rule, value, callback) => {
      if (this.formObj.repairStartTimePlan === '') {
        callback(new Error('计划维修开始时间不能为空'))
      } else {
        callback()
      }
    }
    const validateEndDate = (rule, value, callback) => {
      if (this.formObj.repairEndTimePlan === '') {
        callback(new Error('计划维修结束时间不能为空'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      modalTitle: '',
      formObj: {
        spec: '',
        brand: '',
        price: '',
        productPlace: '',
        meterType: '',
        uncertainty: '',
        accuracy: '',
        range: '',
        equipNum: '',
        ceNum: '',
        labNum: '',
        departmentName: '',
        locationNameName: '',
        period: '',
        buyDate: '',
        effectDate: '',

        equipId: '',
        repairId: '',
        breakdown: '',
        remark: '',
        repairStartTimePlan: '',
        repairEndTimePlan: '',
        repairerIds: '',
        repairerNames: '',
        failureTime: new Date()
      },
      ruleValidate: {
        breakdown: [
          { required: true, message: '故障原因不能为空', trigger: 'change' }
        ],
        repairerNames: [
          { required: true, message: '计划维修人不能为空', trigger: 'change' }
        ],
        repairStartTimePlan: [
          { required: true, validator: validateStartDate, trigger: 'change' }
        ],
        repairEndTimePlan: [
          { required: true, validator: validateEndDate, trigger: 'change' }
        ]
      },
      showModal: false,
      getPage: {},
      repairerNamesList: [],
      breakReason: [],
      breakdownList: [],
      repairerList: [],
      pageColumns: [
        { title: '仪器名称', key: 'name', width: 160 },
        { title: '仪器类别', key: 'className', width: 160 },
        { title: '仪器编号', key: 'labNum', width: 160 },
        { title: '规格型号', key: 'spec', width: 160 },
        { title: '制造厂商', width: 200, key: 'productPlace' },
        { title: '仪器品牌', key: 'brand', width: 160 },
        { title: '出厂编号', key: 'equipNum', width: 160 },
        { title: '证书编号', key: 'ceNum', width: 160 },
        { title: '使用科别', key: 'departmentName', width: 160 },
        { title: '使用地点', key: 'locationName', width: 160 },
        { title: '检定周期（月）', key: 'period', width: 160 },
        { title: '购买日期', key: 'buyDate', width: 160, date: true },
        { title: '有效日期', key: 'effectDate', width: 160, date: true },
        { title: '供应商名称', key: 'supplierName', width: 160 }
      ],
      selectIds: [],
      name: ''
    }
  },
  methods: {
    _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() {
      this.$refs.formObj.validate(valid => {
        const validDate = this._validateDate()
        if (valid && validDate) {
          const data = this.$serialize('repair-detail-form-edit')
          if (this.$string(this.id).isEmpty()) {
            this._save(data)
          }
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },
    _save: async function(data) {
      const result = await equipRepairDetail.equipRepairDetailAdd({
        equipIds: this.selectIds,
        obj: data
      })
      if (result) {
        this.showModal = false
        this.$Message.success('添加成功')
        this.$emit('on-result-change')
      }
    },
    _cancel() {
      this.showModal = false
    },
    _open(repairId) {
      this.showModal = true
      this.$refs.formObj.resetFields()
      this.name = ''
      this._page()
      this._getBreakDownList()
      this._getEquipRepairerList()
      this.repairerList = []
      this.formObj.repairId = repairId
      this.id = ''
      this.modalTitle = '新增仪器维修明细'
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _page: async function() {
      const result = await equipInfo.page(
        this.$serializeForm({ name: this.name })
      )
      if (result) {
        this.getPage = result
        this.$refs.pageTable._initTable()
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this._page()
          break
        case 'selectIds':
          this.selectIds = data
          break
      }
    },
    // 故障原因
    _breakdownChange(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.breakdown = data.breakdown
          break
        default:
          this.formObj.breakdown = data.breakdown
          this._getBreakDownList(data.breakdown)
          break
      }
    },
    // 故障原因 List
    _getBreakDownList: async function(breakDown = '') {
      const data = {
        name: '故障原因',
        value: breakDown
      }
      this.breakdownList = await equipRepairDetail.equipRepairBreakDownEdit(
        data
      )
    },
    _searchParams() {
      const data = this.$serialize('equipInfo-search-form')
      return this.$extend(data, this.pageParams)
    },
    // 计划维修人 repairerNamesList
    _getEquipRepairerList: async function(repairer = '') {
      const data = {
        name: '计划维修人',
        value: repairer
      }
      this.repairerNamesList = await equipRepairDetail.equipRepairBreakDownEdit(
        data
      )
    },
    // 维修人
    _repairerChange(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.repairerNames = data.repairerNames
          break
        default:
          this.formObj.repairerNames = data.repairerNames
          this._getEquipRepairerList(data.repairerNames)
          break
      }
    }
  }
}
</script>
