<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.scrapId" name="scrapId" 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">
                <span v-if="item.key === 'scrapDate'" @click.stop="_handleIndex(scope)">
                  <Date-picker
                    v-model="scope.row.scrapDate"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    transfer
                    style="width:100%;"
                    placeholder="请选择日期"
                    @on-change="_breakDownChange(scope.row,$dateformat(scope.row.scrapDate,'yyyy-mm-dd HH:MM'),'scrapDate')"
                  />
                </span>
                <span v-else-if="item.key === 'scrapNameAct'" @click.stop="_handleIndex(scope)">
                  <Select
                    v-model="scope.row.scrapNameAct"
                    filterable
                    transfer
                    @on-change="_breakDownChange(scope.row,scope.row.scrapNameAct,'scrapNameAct')"
                  >
                    <Option v-for="item in scrapNameActList" :key="item.name" :value="item.name"> {{ item.name }}
                    </Option>
                  </Select>
                </span>
                <span v-else-if="item.key === 'scrapFee'" @click.stop="_handleIndex(scope)">
                  <InputNumber
                    v-model="scope.row.scrapFee"
                    type="number"
                    precision="2"
                    @on-change="_breakDownChange(scope.row,scope.row.scrapFee,'scrapFee')"
                  />
                </span>
                <span v-else-if="item.key === 'scrapMode'" @click.stop="_handleIndex(scope)">
                  <Input
                    v-model="scope.row.scrapMode"
                    @on-blur="_breakDownChange(scope.row,scope.row.scrapMode,'scrapMode')"
                  /></Input>
                </span>
                <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 { equipScrapDo, equipScrap } from '../../../api'
import LmsEquipRepairManageStartTime from './do/LmsEquipScrapManageStartTime'
import LmsEquipRepairManageEndTime from './do/LmsEquipScrapManageDealWay'
import LmsEquipRepairManageFree from './do/LmsEquipScrapManageFree'
import LmsEquipRepairManageNamesAct from './do/LmsEquipScrapManageNamesAct'

/**
 * 添加编辑
 */
let repairerJud = true
const defVal = {
  scrapId: '',
  scrapDate: '',
  applyTime: '',
  id: '',
  name: '',
  num: '',
  applyReason: '',
  status: '',
  remark: ''
}
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 },
        { title: '仪器名称', key: 'name', width: 160 },
        { title: '报废时间', key: 'scrapDate', width: 180 },
        { title: '报废负责人', key: 'scrapNameAct', width: 130 },
        { title: '报废费用', key: 'scrapFee', width: 130 },
        { title: '处理方式', key: 'scrapMode', width: 130 },
        { title: '报废原因', key: 'reason', width: 130 },
        { title: '报废预算金额', key: 'money', width: 130 },
        { title: '申请人', key: 'applyName', width: 160 },
        { title: '备注', key: 'remark', width: 160 },
        { title: '制造厂商', width: 200, key: 'productPlace' },
        { title: '规格型号', key: 'spec', width: 160 }
      ],
      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,
          scrapDate: this.$dateformat(
            pageData[i].scrapDate,
            'yyyy-mm-dd HH:MM'
          ),
          scrapNameAct: pageData[i].scrapNameAct,
          scrapFee: pageData[i].scrapFee
            ? reg.test(pageData[i].scrapFee)
              ? ('' + pageData[i].scrapFee).replace(/^\d+\./, '').length === 1
                ? pageData[i].scrapFee + '0'
                : pageData[i].scrapFee
              : parseInt(pageData[i].scrapFee).toFixed(2)
            : '',
          scrapMode: pageData[i].scrapMode
        })
      }
      this.$extend(mainTain, {
        lmsEquipScrap: { id: this.formObj.scrapId },
        manageList: detail
      })

      this._saveDo(mainTain)

      // this.$store
      //   .dispatch('LmsEquipRepairManage/checkMaintainEdit', mainTain)
      //   .then(() => {
      //     this._resultChange('提交成功!')
      //   })
    },
    _saveDo: async function(data) {
      const result = await equipScrapDo.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.formObj.scrapId = 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.formObj.scrapId)
    },
    _page: async function(id) {
      const result = await equipScrap.getById(id)
      this._dealPage(result.lmsEquipScrapDetailVOList)
      this.formObj = result
      this.formObj.scrapId = 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>
