<template>
  <div>
    <!--1.技术主管审批-->
    <div>
      <!-- 执行顺序 -->
      <Alert class="equip_alert">
        <div>
          <table class="tableClass table1Class">
            <tbody>
              <tr>
                <th colspan="4" style="text-align: center;font-size: 15px">
                  仪器维修申请单
                </th>
              </tr>
              <tr>
                <th>申请编号</th>
                <td>{{ getObj.num }}</td>
                <th>申请人</th>
                <td>{{ getObj.applyName }}</td>
              </tr>
              <tr>
                <th>申请时间</th>
                <td>{{ this.$dateformat(getObj.applyTime, 'yyyy-mm-dd HH:MM') }}</td>
                <th>申请原因</th>
                <td>{{ getObj.applyReason }}</td>
              </tr>
              <tr>
                <th>备注</th>
                <td colspan="3">
                  {{ getObj.remark }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <Form inline :label-width="90">
          <Form-item label="技术主管意见" prop="firstStepAdvice" style="width:70%;margin-top: 20px">
            <Input name="firstStepAdvice" value="同意" placeholder="请输入审批意见" />
          </Form-item>
          <div align="left" style="display: inline-block;margin-top: 23px;">
            <Button type="success" style="margin-left: 15px;" @click="_approve(2,'确定通过？')">
              同意
            </Button>
            <Button type="error" style="margin-left: 15px;" @click="_approve(3,'确定驳回？')">
              驳回
            </Button>
            <Button type="error" style="margin-left: 15px;" @click="_approve(5,'确定终止？')">
              终止
            </Button>
          </div>
        </Form>
      </Alert>
      <!--操作-->
      <div>
        <Button type="success" @click="_addRepair">
          添加
        </Button>
      </div>
    </div>

    <div style="margin-top: 10px">
      <element-table
        ref="pageTable"
        :page-columns="pageColumns"
        :get-page="getPage"
        :table-height="360"
        :icon-msg="iconMsg"
        :opt-col-width="80"
        hide-page
        @on-result-change="_tableResultChange"
      >
        <el-table-column
          v-for="item in pageColumns"
          :key="item.key"
          show-overflow-tooltip
          :prop="item.key"
          :label="item.title"
          :min-width="item.width"
          :fixed="item.fixed?item.fixed:undefined"
        >
          <template slot-scope="scope">
            <div v-if="item.key === 'breakdown'">
              <autoCompletes
                v-model="scope.row.breakdown"
                :down-data="breakdownList"
                blur
                show-key="breakdown"
                :handle-obj="scope"
                @on-result-change="_breakDownChange"
              />
            </div>
            <div v-else-if="item.key === 'repairerNames'">
              <autoCompletes
                v-model="scope.row.repairerNames"
                :down-data="repairerNamesList"
                blur
                show-key="repairerNames"
                :handle-obj="scope"
                @on-result-change="_repairerChange"
              />
            </div>
            <div v-else-if="item.key === 'failureTime'">
              <Date-picker
                v-model="scope.row.failureTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                transfer
                style="width:100%;"
                placeholder="请选择日期"
                @on-change="_dateChange('failureTime',scope)"
              />
            </div>
            <div v-else-if="item.key === 'repairStartTimePlan'">
              <Date-picker
                v-model="scope.row.repairStartTimePlan"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                transfer
                style="width:100%;"
                placeholder="请选择日期"
                @on-change="_dateChange('repairStartTimePlan',scope)"
              />
            </div>
            <div v-else-if="item.key === 'repairEndTimePlan'">
              <Date-picker
                v-model="scope.row.repairEndTimePlan"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                transfer
                style="width:100%;"
                placeholder="请选择日期"
                @on-change="_dateChange('repairEndTimePlan',scope)"
              />
            </div>
            <div v-else>
              {{ scope.row[item.key] }}
            </div>
          </template>
        </el-table-column>
      </element-table>
    </div>
    <Form id="file-form" :label-width="90" inline style="margin-top: 10px;">
      <Form-item label="附件上传">
        <div v-for="item in lmsEquipFiles" :key="item" class="file-upload-list">
          <div>
            <!--<img :src="item.url">-->
            <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"
          :before-upload="_handleBeforeUpload"
          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>
    <!--添加-->
    <equipRepairAdd ref="addModal" @on-result-change="_page" />
  </div>
</template>
<script>
import global from '../../../../api/config'
import { equipRepair, equipRepairDetail } from '../../../../api'
import autoCompletes from '../../../../components/base/autoCompletes'
import equipRepairAdd from './equipRepairAdd'

export default {
  components: {
    equipRepairAdd,
    autoCompletes
  },
  data() {
    return {
      pageColumns: [
        { title: '仪器编号', key: 'labNum', width: 160 },
        { title: '仪器名称', key: 'name', width: 160 },
        { title: '故障原因', key: 'breakdown', width: 160 },
        { title: '故障时间', key: 'failureTime', width: 180 },
        { title: '计划维修人员', key: 'repairerNames', width: 160 },
        { title: '计划维修开始时间', key: 'repairStartTimePlan', width: 180 },
        { title: '计划维修结束时间', key: 'repairEndTimePlan', width: 180 },
        { title: '备注', key: 'remark', width: 160 },
        { title: '规格型号', key: 'spec', width: 160 },
        { title: '制造厂商', width: 200, key: 'productPlace' }
      ],
      getPage: {
        records: []
      },
      currentRow: {},
      selectIds: [],
      iconMsg: [{ type: 'pt-trash', id: '', name: '删除' }],
      breakdownList: [],
      repairerNamesList: [],
      id: '',
      getObj: {},
      dataObj: {
        repairId: ''
      },
      fileObj: {
        id: '',
        type: 1
      },
      filePath: '',
      lmsEquipFiles: [],
      fileAction: global.baseURL + '/res/v1/equip_repair/uploadFile'
    }
  },
  mounted() {
    this.id = this.$route.query.id
    this._page()
    this._repair()
    this._getRepairerList()
    this._getBreakDownList()
  },
  methods: {
    _page: async function() {
      const obj = Object.assign(
        { repairId: this.id },
        this.$refs.pageTable._searchParams()
      )
      const result = await equipRepairDetail.page(obj)
      if (result) {
        for (let i = 0; i < result.records.length; i++) {
          result.records[i].failureTime = result.records[i].failureTime
            ? new Date(result.records[i].failureTime)
            : ''
          result.records[i].repairStartTimePlan = result.records[i]
            .repairStartTimePlan
            ? new Date(result.records[i].repairStartTimePlan)
            : ''
          result.records[i].repairEndTimePlan = result.records[i]
            .repairEndTimePlan
            ? new Date(result.records[i].repairEndTimePlan)
            : ''
        }
        this.getPage.records = result.records
        this.$refs.pageTable._initTable()
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this._page()
          break
        case 'selectIds':
          this.selectIds = data
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData)
          break
      }
    },
    _iconClick(res, data) {
      switch (res) {
        case '删除':
          this._delRepair(data)
          break
      }
    },
    // 操作的序号
    _handleRow(data) {
      this.currentRow = data.row
    },
    // 故障原因模糊
    _breakDownChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.currentRow.breakdown = data.breakdown
          this._save('breakdown')
          break
        case 'query':
          this.currentRow.breakdown = data.breakdown
          this._getBreakDownList(data.breakdown)
          break
        case 'blur':
          this._save('breakdown')
          break
      }
    },
    // 计划维修人 模糊搜索
    _repairerChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.currentRow.repairerNames = data.repairerNames
          this._save('repairerNames')
          break
        case 'query':
          this.currentRow.repairerNames = data.repairerNames
          this._getRepairerList(data.repairerNames)
          break
        case 'blur':
          this._save('repairerNames')
          break
      }
    },
    _dateChange(key, handleObj) {
      this._handleRow(handleObj)
      this._save(key)
    },
    _save: async function(key) {
      const obj = {
        id: this.currentRow.id,
        obj: { [key]: this.currentRow[key] }
      }
      const result = await equipRepairDetail.equipRepairBreakDownSave(obj)
      if (result) {
        // this._page()
      }
    },
    // 故障原因 List
    _getBreakDownList: async function(breakDown = '') {
      const data = {
        name: '故障原因',
        value: breakDown
      }
      this.breakdownList = await equipRepairDetail.equipRepairBreakDownEdit(
        data
      )
    },
    // 计划维修人 repairerNamesList
    _getRepairerList: async function(repairer = '') {
      const data = {
        name: '计划维修人',
        value: repairer
      }
      this.repairerNamesList = await equipRepairDetail.equipRepairBreakDownEdit(
        data
      )
    },
    _repair: async function() {
      this.getObj = await equipRepair.get(this.id)
      this.dataObj.repairId = this.getObj.id
      this.fileObj.id = this.getObj.id
      this.lmsEquipFiles = this.getObj.lmsEquipFiles
    },
    _approve(allow, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content,
        onOk: () => {
          const data = {}
          data.id = $('#flowFrame', parent.document).attr('data-tid')
          data.status = allow
          data.reason = $('input[name="firstStepAdvice"]').val()
          this._approveOk(data)
        }
      })
    },
    _approveOk: async function(data) {
      const result = await equipRepair.approve(data)
      if (result) {
        this.$Message.success('审批成功！')
        setTimeout(() => {
          parent.location.replace(global.webURL + '/sys/workflow/flow_task')
        }, 200)
      }
    },
    _addRepair() {
      this.$refs.addModal._open(this.id)
    },
    _delRepair(data) {
      // 删除
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除？',
        onOk: () => {
          this._delOk(data.id)
        }
      })
    },
    _delOk: async function(id) {
      const result = await equipRepairDetail.deleteByIds(id)
      if (result) {
        this._page()
        this.$Message.success('删除成功！')
      }
    },
    // 文件上传
    _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: async () => {
          const fileList = this.lmsEquipFiles
          const data = {
            id: file.id,
            repairId: this.dataObj.repairId,
            type: 1
          }
          const result = await equipRepair.deleteFile(data)
          if (result) {
            this.lmsEquipFiles.splice(fileList.indexOf(file), 1)
            this.$Message.success('删除成功！')
          }
        }
      })
    },
    _handleBeforeUpload() {},
    _handleSuccess(response, file, fileList) {
      if (response.success) {
        this.$Message.success('上传成功！')
        this.lmsEquipFiles.push(response.data)
      } else {
        this.$Message.error('上传失败！')
      }
    }
  }
}
</script>
