<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="applyReason" class="width-32" label="维修申请原因:">
              <Input v-model="formObj.applyReason" name="applyReason" 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.detailId" name="detailId" 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 === 'repairStartTimeAct'" @click.stop="_handleIndex(scope)">
                  <Date-picker
                    v-model="scope.row.repairStartTimeAct"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    transfer
                    style="width:100%;"
                    placeholder="请选择日期"
                    @on-change="_repairStartTimeActChange"
                  />
                </div>
                <div v-else-if="item.key === 'repairEndTimeAct'" @click.stop="_handleIndex(scope)">
                  <Date-picker
                    v-model="scope.row.repairEndTimeAct"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    transfer
                    style="width:100%;"
                    placeholder="请选择日期"
                    @on-change="_repairEndTimeActChange"
                  />
                </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 === 'repairerNamesAct'" @click.stop="_handleIndex(scope)">
                  <AutoComplete
                    v-model="scope.row.repairerNamesAct"
                    :down-data="repairerNamesList"
                    blur
                    show-key="repairerNames"
                    @on-result-change="_repairerNameChange"
                  />
                </div>
                <div v-else-if="item.key === 'repairFee'" @click.stop="_handleIndex(scope)">
                  <InputNumber
                    v-model="scope.row.repairFee"
                    type="number"
                    precision="2"
                    @on-change="_breakDownChange(scope.row.id,scope.row.repairFee,'repairFee')"
                  />
                </div>
                <div v-else-if="item.key === 'repairMethod'" @click.stop="_handleIndex(scope)">
                  <Input
                    v-model="scope.row.repairMethod"
                    @on-blur="_breakDownChange(scope.row.id,scope.row.repairMethod,'repairMethod')"
                  /></Input>
                </div>
                <span v-else>{{ scope.row[item.key] }}</span>
              </template>
            </el-table-column>
          </element-table>

          </Col>
        </Row>
      </div>
      <!--      <Form id="file-form" :label-width="90" inline>-->
      <!--        <Form-item label="附件上传" style="width: 98.6%;">-->
      <!--          <div v-for="item in lmsEquipFiles" class="file-upload-list">-->
      <!--            <div>-->
      <!--              <div class="file-upload-list-cover">-->
      <!--                <Icon type="ios-eye-outline" @click.native="_handleView(item)" />-->
      <!--                <Icon type="ios-cloud-download-outline" @click.native="_downloadFile(item)" />-->
      <!--                <Icon type="ios-trash-outline" @click.native="_handleRemove(item)" />-->
      <!--              </div>-->
      <!--            </div>-->
      <!--            {{ item.orginName }}-->
      <!--          </div>-->
      <!--          <Upload-->
      <!--            :show-upload-list="false"-->
      <!--            :with-credentials="true"-->
      <!--            :on-success="_handleSuccess"-->
      <!--            type="drag"-->
      <!--            :action="fileAction"-->
      <!--            :data="fileObj"-->
      <!--            style="display: inline-block;width:100px;"-->
      <!--          >-->
      <!--            <div style="width: 100px;height:100px;line-height: 100px;">-->
      <!--              <Icon type="ios-cloud-upload" size="20" />-->
      <!--            </div>-->
      <!--          </Upload>-->
      <!--        </Form-item>-->
      <!--      </Form>-->
      <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 AutoComplete from '../../../components/base/AutoCompletes.vue'
import { equipRepairDo, equipRepair } from '../../../api'
import LmsEquipRepairManageStartTime from './do/LmsEquipRepairManageStartTime'
import LmsEquipRepairManageEndTime from './do/LmsEquipRepairManageEndTime'
import LmsEquipRepairManageFree from './do/LmsEquipRepairManageFree'
import LmsEquipRepairManageNamesAct from './do/LmsEquipRepairManageNamesAct'

/**
 * 添加编辑
 */
let repairerJud = true
const defVal = {
  detailId: '',
  status: '',
  num: '',
  applyReason: '',
  registerName: ''
}
export default {
  components: {
    LmsEquipRepairManageStartTime,
    LmsEquipRepairManageEndTime,
    LmsEquipRepairManageFree,
    LmsEquipRepairManageNamesAct,
    AutoComplete
  },
  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: 'name', width: 160, align: 'center' },
        {
          title: '实际维修开始时间',
          key: 'repairStartTimeAct',
          width: 180,
          align: 'center'
        },
        {
          title: '实际维修结束时间',
          key: 'repairEndTimeAct',
          width: 180,
          align: 'center'
        },
        {
          title: '实际维修人',
          key: 'repairerNamesAct',
          width: 130,
          align: 'center'
        },
        { title: '维修费用', key: 'repairFee', width: 130, align: 'center' },
        { title: '维修方式', key: 'repairMethod', width: 130, align: 'center' },
        {
          title: '计划维修开始时间',
          key: 'repairStartTimePlan',
          align: 'center',
          width: 180,
          datetime: true
        },
        {
          title: '计划维修结束时间',
          key: 'repairEndTimePlan',
          align: 'center',
          width: 180,
          datetime: true
        },
        {
          title: '计划维修人员',
          key: 'repairerNames',
          width: 160,
          align: 'center'
        },
        { title: '申请人', key: 'registerName', width: 160, align: 'center' },
        { title: '备注', key: 'remark', width: 160, align: 'center' },
        { title: '规格型号', key: 'spec', width: 160, align: 'center' },
        {
          title: '制造厂商',
          width: 200,
          key: 'productPlace',
          align: 'center',
          ellipsis: true
        }
      ],
      getPage: {},
      currentComponent: '',
      fileAction: global.baseURL + '/res/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('请至少选择一条数据!')
      }
    },

    _btnClick(msg, componetName) {
      const ids = this.selectIds
      this.currentComponent = componetName
      if (ids.length !== 0) {
        this.$nextTick(() => {
          switch (msg) {
          }
        })
      } 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
      }
    },
    // 操作的序号
    _handleIndex(data) {
      this.currentIndex = data.$index
    },
    _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({
          detailId: pageData[i].id,
          repairStartTimeAct: this.$dateformat(
            pageData[i].repairStartTimeAct,
            'yyyy-mm-dd HH:MM'
          ),
          repairEndTimeAct: this.$dateformat(
            pageData[i].repairEndTimeAct,
            'yyyy-mm-dd HH:MM'
          ),
          repairMethod: pageData[i].repairMethod,
          repairerNamesAct: pageData[i].repairerNamesAct,
          repairFee: pageData[i].repairFee
            ? reg.test(pageData[i].repairFee)
              ? ('' + pageData[i].repairFee).replace(/^\d+\./, '').length === 1
                ? pageData[i].repairFee + '0'
                : pageData[i].repairFee
              : parseInt(pageData[i].repairFee).toFixed(2)
            : ''
        })
      }
      this.$extend(mainTain, {
        lmsEquipRepair: { id: this.detailId },
        dtoList: detail
      })

      this._saveDo(mainTain)

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

    _hideLoading() {
      // this.$refs.footerModal._hideLoading()
    },
    // 实际维修人 repairerNamesList
    _openSearchEquiprepairer(repairer = '') {
      // const data = {
      //   name: '计划维修人',
      //   value: repairer
      // }
      // this.$store
      //   .dispatch('LmsEquipRepairDetail/equipRepairBreakDownEdit', data)
      //   .then(() => {
      //     const repairerNameList = this.$store.state.LmsEquipRepairDetail.list
      //     this.repairerNamesList = repairerNameList
      //   })
    },
    _cancel() {
      // this.$refs.footerModal._hideLoading()
      this.showEditModal = false
    },
    _open(ids) {
      this.showEditModal = true
      this.$refs.formObj.resetFields()
      this.id = ids
      this._openSearchEquiprepairer()
      // this._hideLoading()
      $('input[name="detailId"]').val(ids)
      this.fileObj.id = ids // 文件上传id
      this._page(ids)
      this.modalTitle = '维修实施'
    },
    _search() {
      this._openSearchEquiprepairer()
      this._page(this.detailId)
    },
    _page: async function(id) {
      const result = await equipRepair.getById(id)
      this._dealPage(result.lmsEquipRepairDetailVOList, result.applyName)
      this.formObj = result
      this.detailId = result.id // 主单id
      this.lmsEquipFiles = result.lmsEquipFiles // 文件集合
      this.$refs.pageTable._initTable()
    },
    // 维修实施 处理接口
    _dealPage(data, applyName) {
      let equipList = []
      equipList = data
      for (let i = 0; i < equipList.length; i++) {
        equipList[i].failureTime = new Date(equipList[i].failureTime)
        equipList[i].repairStartTimeAct = equipList[i].repairStartTimeAct
          ? new Date(equipList[i].repairStartTimeAct)
          : new Date(equipList[i].repairStartTimePlan)
        equipList[i].repairEndTimeAct = equipList[i].repairEndTimeAct
          ? new Date(equipList[i].repairEndTimeAct)
          : new Date(equipList[i].repairEndTimePlan)
        equipList[i].repairerNamesAct = equipList[i].repairerNamesAct
          ? equipList[i].repairerNamesAct
          : equipList[i].repairerNames
        equipList[i].registerName = applyName
      }
      this.getPage = {
        records: equipList
      }
      // this.$refs.pageTable._hideLoading()
    },
    // 附件
    _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>
