<template>
  <div>
    <Modal v-model="showEditModal" :mask-closable="false" width="1100">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Alert>
          <Form
            id="start-edit-form"
            ref="formObj"
            :model="formObj"
            :rules="ruleValidate"
            :label-width="120"
            class="coll-search"
            inline
          >
            <label class="label-sign" />
            <Form-item prop="num" class="width-32" label="计划编号:">
              <Input v-model="formObj.num" name="num" placeholder="计划编号" disabled />
            </Form-item>
            <Form-item prop="name" class="width-32" label="计划名称:">
              <Input v-model="formObj.name" name="name" placeholder="请输入计划名称" disabled />
            </Form-item>
            <Form-item prop="registerName" class="width-32" label="申请人:">
              <Input v-model="formObj.registerName" name="registerName" placeholder="请输入申请人" disabled />
            </Form-item>
            <input v-model="formObj.checkId" name="checkId" type="hidden">
          </Form>
        </Alert>
        <Row>
          <Col span="24" style="margin-top:5px" />
          <!--操作-->
          <!--          <BtnList :msg="btn" class="contHide" @on-result-change="_btnClick" />-->

          <el-button type="success" @click="_maintainStartTime">
            维护实际开始时间
          </el-button>
          <el-button type="success" @click="_maintainRepair">
            维护实际核查人
          </el-button>
          <el-button type="primary" @click="_maintainFee">
            维护核查费用
          </el-button>
          <el-button type="primary" @click="_maintainEndTime">
            维护实际结束时间
          </el-button>
          </Col>
          <!--表格-->
          <Col span="24" style="margin: 10px 0;" />
          <element-table
            ref="pageTable"
            :table-height="400"
            :get-page="getPage"
            show-check-box
            select-data
            @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"
              :align="item.align"
              :fixed="item.fixed?item.fixed:undefined"
            >
              <template slot-scope="scope">
                <div v-if="item.key === 'checkStartTimeAct'" @click.stop="_handleIndex(scope)">
                  <Date-picker
                    v-model="scope.row.checkStartTimeAct"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    transfer
                    style="width:100%;"
                    placeholder="请选择日期"
                    @on-change="_checkStartTimeActChange"
                  />
                </div>
                <div v-else-if="item.key === 'checkEndTimeAct'" @click.stop="_handleIndex(scope)">
                  <Date-picker
                    v-model="scope.row.checkEndTimeAct"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    transfer
                    style="width:100%;"
                    placeholder="请选择日期"
                    @on-change="_checkEndTimeActChange"
                  />
                </div>
                <span v-else-if="item.datetime">{{ scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM'):'' }}
                </span>
                <div v-else-if="item.key === 'checkActName'" @click.stop="_handleIndex(scope)">
                  <Select
                    v-model="scope.row.checkActName"
                    transfer
                    filterable
                    placeholder="请选择实际核查人"
                    @on-change="_checkTimeActChange(scope.row.id,scope.row.checkActName,'checkActName')"
                  >
                    <Option v-for="item in checkActerList" :key="item.name" :value="item.name">
                      {{ item.name }}
                    </Option>
                  </Select>
                </div>
                <div v-else-if="item.key === 'checkFee'" @click.stop="_handleIndex(scope)">
                  <InputNumber
                    v-model="scope.row.checkFee"
                    type="number"
                    precision="2"
                    @on-change="_checkTimeActChange(scope.row.id,scope.row.checkFee,'checkFee')"
                  />
                </div>
                <span v-else>{{ scope.row[item.key] }}</span>
              </template>
            </el-table-column>
          </element-table>
          </Col>
        </Row>
      </div>

      <div slot="footer">
        <el-button type="success" @click="_cancel">
          关闭
        </el-button>
        <el-button type="primary" @click="_ok">
          提交
        </el-button>

        <!--        <ModalFooter ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />-->
      </div>
    </Modal>
    <Modal v-model="visible" title="查看图片">
      <img v-if="visible" :src="'https://obs.myhwclouds.com/lims/'+filePath" style="width: 100%">
    </Modal>

    <LmsEquipRepairManageStartTime ref="startTimeModal" @on-result-change="_pageMoment" />
    <LmsEquipRepairManageEndTime ref="endTimeModal" @on-result-change="_pageMoment" />
    <LmsEquipRepairManageFree ref="manageFreeModal" @on-result-change="_pageMoment" />
    <LmsEquipRepairManageNamesAct ref="namesActModal" @on-result-change="_pageMoment" />
  </div>
</template>
<script>
import global from '../../../api/config'
import { equipCheck, sysUser } from '../../../api'
import LmsEquipRepairManageStartTime from './do/LmsEquipCheckManageStartTimeAct'
import LmsEquipRepairManageEndTime from './do/LmsEquipCheckManageEndTimeAct'
import LmsEquipRepairManageFree from './do/LmsEquipCheckManageFree'
import LmsEquipRepairManageNamesAct from './do/LmsEquipCheckManageNamesActual'

/**
 * 添加编辑
 */
let repairerJud = true
const defVal = {
  checkId: '',
  process: '',
  processFiles: '',
  remark: '',
  companyId: '',
  status: '',
  checkStartTimeAct: '',
  checkEndTimeAct: ''
}
export default {
  components: {
    LmsEquipRepairManageStartTime,
    LmsEquipRepairManageEndTime,
    LmsEquipRepairManageFree,
    LmsEquipRepairManageNamesAct
  },
  data() {
    return {
      id: '',
      modalTitle: '',
      formObj: defVal,
      ruleValidate: {},
      lmsEquipFiles: [], // 文件列表
      filePath: '', // 文件路径
      visible: false, // 是否显示查看图片Modal
      fileObj: {
        // 文件id
        id: '',
        type: '1'
      },
      footerList: [
        { name: '关闭', type: 'primary' },
        { name: '提交', type: 'primary' }
      ],
      currentIndex: '',
      selectIds: [],
      repairerNamesList: [],
      pageColumns: [
        { title: '仪器编号', key: 'labNum', width: 160, align: 'center' },
        { title: '仪器名称', key: 'equipName', width: 160, align: 'center' },
        {
          title: '实际开始时间',
          key: 'checkStartTimeAct',
          width: 180,
          align: 'center'
        },
        {
          title: '实际结束时间',
          key: 'checkEndTimeAct',
          width: 180,
          align: 'center'
        },
        {
          title: '实际核查人',
          key: 'checkActName',
          width: 160,
          align: 'center'
        },
        { title: '核查费用', key: 'checkFee', width: 130, align: 'center' },
        { title: '核查内容', key: 'checkContent', width: 160, align: 'center' },
        {
          title: '计划开始时间',
          key: 'checkStartTimePlan',
          width: 180,
          align: 'center',
          datetime: true
        },
        {
          title: '计划结束时间',
          key: 'checkEndTimePlan',
          width: 180,
          align: 'center',
          datetime: true
        },
        { title: '负责人', key: 'checkName', width: 160, align: 'center' },
        { title: '备注', key: 'remark', width: 160, align: 'center' },
        { title: '制造厂商', key: 'productPlace', width: 160, align: 'center' },
        { title: '规格型号', key: 'spec', width: 160, align: 'center' }
      ],
      getPage: {},
      currentComponent: '',
      checkActerList: [], // 实际核查人
      fileAction: global.baseURL + '/v1/equip_repair/uploadFile', // 文件路径
      showEditModal: false,
      btn: [
        {
          type: 'success',
          id: '',
          name: '维护实际开始时间',
          componentName: LmsEquipRepairManageStartTime
        },
        {
          type: 'error',
          id: '',
          name: '维护实际维修人',
          componentName: LmsEquipRepairManageNamesAct
        },
        {
          type: 'info',
          id: '',
          name: '维护维修费用',
          componentName: LmsEquipRepairManageFree
        },
        {
          type: 'info',
          id: '',
          name: '维护实际结束时间',
          componentName: LmsEquipRepairManageEndTime
        }
      ],
      selectIndex: [],
      detailId: ''
    }
  },
  methods: {
    _pageMoment(data, name) {
      const dataPage = this.getPage.records
      this.selectIndex.forEach((item, index) => {
        dataPage[item][name] = data
        this.getPage.records.splice(item, 1, dataPage[item])
      })
      this.selectIndex = []
      this.selectIds = []
    },

    _maintainStartTime() {
      const ids = this.selectIds
      if (ids.length !== 0) {
        this.$refs.startTimeModal._open(ids, this.detailId)
      } else {
        this.$Message.warning('请至少选择一条数据!')
      }
    },
    _maintainRepair() {
      const ids = this.selectIds
      if (ids.length !== 0) {
        this.$refs.namesActModal._open(ids, this.detailId)
      } else {
        this.$Message.warning('请至少选择一条数据!')
      }
    },
    _maintainFee() {
      const ids = this.selectIds
      if (ids.length !== 0) {
        this.$refs.manageFreeModal._open(ids, this.detailId)
      } else {
        this.$Message.warning('请至少选择一条数据!')
      }
    },
    _maintainEndTime() {
      const ids = this.selectIds
      if (ids.length !== 0) {
        this.$refs.endTimeModal._open(ids, this.detailId)
      } else {
        this.$Message.warning('请至少选择一条数据!')
      }
    },

    // 操作的序号
    _handleIndex(data) {
      this.currentIndex = data.$index
    },
    _checkStartTimeActChange() {
      const ids = this.getPage.records[this.currentIndex].id
      const startTimes = this.getPage.records[this.currentIndex]
        .checkStartTimeAct
      const endTimes = this.getPage.records[this.currentIndex].checkEndTimeAct

      if (new Date(startTimes) > endTimes && typeof endTimes !== 'undefined') {
        this.$Message.warning('实际开始时间不能晚于结束时间!')
      } else if (startTimes === '') {
        this.$Message.error('实际开始时间不能为空，请选择时间!')
      } else {
        this._checkTimeActChange(
          ids,
          this.$dateformat(startTimes, 'yyyy-mm-dd HH:MM'),
          'checkStartTimeAct'
        )
      }
    },

    // 行编辑修改
    _checkTimeActChange(data, value, name) {
      this.getPage.records[this.currentIndex][name] = value
    },
    _btnClick(msg, componetName) {
      const ids = this.selectIds
      this.currentComponent = componetName
      if (ids.length !== 0) {
        this.$nextTick(() => {})
      } else {
        this.$Message.warning('请至少选择一条数据!')
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'selectData':
          {
            const idList = []
            const idIndex = []
            for (let i = 0; i < data.length; i++) {
              idList.push(data[i].id)
              idIndex.push(
                this.getPage.records.findIndex(item => item.id === data[i].id)
              )
            }
            this.selectIds = idList
            this.selectIndex = idIndex
          }
          break
      }
    },

    _repairStartTimeActChange() {
      const ids = this.getPage.records[this.currentIndex].id
      const startTimes = this.getPage.records[this.currentIndex]
        .repairStartTimeAct
      const endTimes = this.getPage.records[this.currentIndex].repairEndTimeAct

      if (new Date(startTimes) > endTimes && typeof endTimes !== 'undefined') {
        this.$Message.warning('实际维修开始时间不能晚于结束时间!')
      } else if (startTimes === '') {
        this.$Message.error('实际维修开始时间不能为空，请选择时间!')
      } else {
        this._breakDownChange(
          ids,
          this.$dateformat(startTimes, 'yyyy-mm-dd HH:MM'),
          'repairStartTimeAct'
        )
      }
    },
    _repairerNameChange(msg, data) {
      const ids = this.getPage.records[this.currentIndex].id
      switch (msg) {
        case 'select':
          repairerJud = true
          this._breakDownChange(ids, data.repairerNames, 'repairerNamesAct')
          break
        case 'query':
          repairerJud = false
          this.getPage.records[this.currentIndex].repairerNamesAct =
            data.repairerNames
          this._openSearchEquiprepairer(data.repairerNames)
          break
        case 'blur':
          if (!repairerJud) {
            this._breakDownChange(
              ids,
              this.getPage.records[this.currentIndex].repairerNamesAct,
              'repairerNamesAct'
            )
            repairerJud = true
          }
          break
      }
    },
    _footerResult(name) {
      switch (name) {
        case '关闭':
          this._cancel()
          break
        case '提交':
          this._ok()
          break
      }
    },
    // scope.row.id,$dateformat(scope.row.repairEndTimeAct,'yyyy-mm-dd HH:MM'),'repairEndTimeAct'
    _repairEndTimeActChange() {
      const ids = this.getPage.records[this.currentIndex].id
      const startTimes = this.getPage.records[this.currentIndex]
        .repairStartTimeAct
      const endTimes = this.getPage.records[this.currentIndex].repairEndTimeAct

      if (
        new Date(endTimes) < startTimes &&
        typeof startTimes !== 'undefined'
      ) {
        this.$Message.warning('实际维修结束时间不能早于开始时间!')
      } else if (endTimes === '') {
        this.$Message.error('实际维修结束时间不能为空，请选择时间!')
      } else {
        this._breakDownChange(
          ids,
          this.$dateformat(endTimes, 'yyyy-mm-dd HH:MM'),
          'repairEndTimeAct'
        )
      }
    },
    _resultChange(msg) {
      this.formObj = defVal
      this.showEditModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
    },
    _breakDownChange(ids, value, name) {
      this.getPage.records[this.currentIndex][name] = value
    },
    _ok() {
      const detail = []
      const mainTain = {}
      const pageData = this.getPage.records
      const reg = /.*\..*/ // 判断是否含有小数点
      for (let i = 0; i < pageData.length; i++) {
        detail.push({
          checkId: pageData[i].id,
          checkStartTimeAct: this.$dateformat(
            pageData[i].checkStartTimeAct,
            'yyyy-mm-dd HH:MM'
          ),
          checkEndTimeAct: this.$dateformat(
            pageData[i].checkEndTimeAct,
            'yyyy-mm-dd HH:MM'
          ),
          checkActName: pageData[i].checkActName,
          checkFee: pageData[i].checkFee
            ? reg.test(pageData[i].checkFee)
              ? ('' + pageData[i].checkFee).replace(/^\d+\./, '').length === 1
                ? pageData[i].checkFee + '0'
                : pageData[i].checkFee
              : parseInt(pageData[i].checkFee).toFixed(2)
            : ''
        })
      }
      this.$extend(mainTain, {
        lmsEquipCheck: { id: this.formObj.checkId },
        manageList: detail
      })
      this._saveDo(mainTain)

      // this.$store
      //   .dispatch('LmsEquipRepairManage/checkMaintainEdit', mainTain)
      //   .then(() => {
      //     this._resultChange('提交成功!')
      //   })
    },
    _saveDo: async function(data) {
      const result = await equipCheck.addDo(data)
      if (result) {
        this._resultChange('提交成功')
      } else {
        this._resultChange('提交失败')
      }
    },

    _hideLoading() {
      // this.$refs.footerModal._hideLoading()
    },
    // 实际维修人 repairerNamesList
    _openSearchEquiprepairer: async function() {
      const result = await sysUser.list({})
      if (result) {
        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.checkActerList = maintainerArray
      }
    },
    _cancel() {
      // this.$refs.footerModal._hideLoading()
      this.showEditModal = false
    },
    _open(ids) {
      this.showEditModal = true
      this.$refs.formObj.resetFields()
      this.id = ids
      this.formObj.checkId = ids
      this._openSearchEquiprepairer()
      // this._hideLoading()
      this.fileObj.id = ids // 文件上传id
      this._page(ids)
      this.modalTitle = '维修实施'
    },
    _search() {
      this._openSearchEquiprepairer()
      this._page(this.formObj.checkId)
    },
    _page: async function(id) {
      const result = await equipCheck.getVOById(id)
      this._dealPage(result.lmsEquipCheckManageVO)
      this.formObj = result
      this.formObj.checkId = result.id // 主单id
      this.lmsEquipFiles = result.lmsEquipFiles // 文件集合
      this.$refs.pageTable._initTable()
    },
    _dealPage(data) {
      let equipList = []
      equipList = data
      for (let i = 0; i < equipList.length; i++) {
        equipList[i].scrapDate = equipList[i].scrapDate
          ? new Date(equipList[i].scrapDate)
          : ''
      }
      this.$refs.pageTable._hideLoading()
      this.getPage = {
        records: equipList
      }
    },
    // 附件
    _handleView(data) {
      this.filePath = data.filePath
      const index1 = this.filePath.lastIndexOf('.')
      const index2 = this.filePath.length
      const suffix = this.filePath.substring(index1 + 1, index2) // 后缀名
      if (suffix === 'png' || suffix === 'jpg' || suffix === 'jpeg') {
        this.visible = true
      } else {
        this.$Message.warning({
          content: '非图片文件无法查看，请下载查看',
          duration: 3
        })
        this.visible = false
      }
    },
    _downloadFile(file) {
      // 下载文件
      this.$Modal.confirm({
        title: '提示',
        content: '确定要下载？',
        onOk: () => {
          const url =
            global.baseURL + '/res/v1/equip_repair/downLoadFile?id=' + file.id
          window.open(url)
        }
      })
    },
    // 附件删除
    _handleRemove(file) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除文件？',
        onOk: () => {
          const fileList = this.lmsEquipFiles
          const data = {
            id: file.id,
            repairId: this.detailId,
            type: 1
          }
          this.$store
            .dispatch('LmsEquipRepairManage/equipRepairDeleteUpload', data)
            .then(() => {
              if (this.$store.state.LmsEquipRepairManage.success) {
                this.lmsEquipFiles.splice(fileList.indexOf(file), 1)
                this.$Message.success('删除成功！')
              }
            })
        }
      })
    },
    _handleSuccess(response, file, fileList) {
      if (response.success) {
        this.$Message.success('上传成功！')
        this.lmsEquipFiles.push(response.data)
        console.log(this.lmsEquipFiles)
      } else {
        this.$Message.error('上传失败！')
      }
    }
  }
}
</script>
