<template>
  <div>
    <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>{{ getOrder.num }}</td>
                <th>申请人</th>
                <td>{{ getOrder.applyer }}</td>
              </tr>
              <tr>
                <th>申请原因</th>
                <td>{{ getOrder.reason }}</td>
                <th>申请时间</th>
                <td>{{ this.$dateformat(getOrder.ctime, "yyyy-mm-dd HH:MM") }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <Form inline :label-width="80">
          <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(5,'确定驳回？')">
              驳回
            </Button>
            <Button type="error" style="margin-left: 15px;" @click="_approve(3,'确定终止？')">
              终止
            </Button>
          </div>
        </Form>
      </Alert>
    </div>
    <!--内容-->
    <div>
      <element-table
        ref="pageTable"
        :table-height="300"
        :get-page="getPage"
        :icon-msg="iconMsg"
        :opt-col-width="80"
        @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"
          :fixed="item.fixed?item.fixed:undefined"
        >
          <template slot-scope="scope">
            <div v-if="item.key==='applyName'">
              <Select
                v-model="scope.row.applyName"
                filterable
                transfer
                @on-change="_reasonChange('applyName',scope)"
              >
                <Option v-for="item in salesmanList" :key="item.id" :value="item.realname">
                  {{ item.realname }}
                </Option>
              </Select>
            </div>
            <div v-else-if="item.key === 'useStartTime'">
              <Date-picker
                v-model="scope.row.useStartTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                transfer
                style="width:100%;"
                placeholder="请选择日期"
                @on-change="_dateChange('useStartTime',scope)"
              />
            </div>
            <div v-else-if="item.key === 'useEndTime'">
              <Date-picker
                v-model="scope.row.useEndTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                transfer
                style="width:100%;"
                placeholder="请选择日期"
                @on-change="_dateChange('useEndTime',scope)"
              />
            </div>
            <div v-else-if="item.key === 'performanceStart'">
              <el-input
                v-model="scope.row.performanceStart"
                @focus="_handleRow(scope)"
                @blur="_performanceChange('performanceStart',scope)"
              />
            </div>
            <div v-else-if="item.key === 'performanceEnd'">
              <el-input
                v-model="scope.row.performanceEnd"
                @focus="_handleRow(scope)"
                @blur="_performanceChange('performanceEnd',scope)"
              />
            </div>
            <div v-else-if="item.key === 'uses'">
              <autoCompletes
                v-model="scope.row.uses"
                :down-data="rangeList"
                blur
                show-key="purpose"
                :handle-obj="scope"
                @on-result-change="_purposeChange"
              />
            </div>
            <div v-else-if="item.key === 'remark'">
              <el-input
                v-model="scope.row.remark"
                @focus="_handleRow(scope)"
                @blur="_save('remark')"
              />
            </div>
            <div v-else>
              {{ scope.row[item.key] }}
            </div>
          </template>
        </el-table-column>
      </element-table>
    </div>
  </div>
</template>
<script>
import global from '../../../../api/config'

import {
  userGroup,
  equipInfo,
  equipRelDelivery,
  equipDeliveryOrder
} from '../../../../api'
import autoCompletes from '../../../../components/base/autoCompletes'

export default {
  components: {
    autoCompletes
  },
  data() {
    return {
      selectIds: [],
      id: {},
      pageColumns: [
        { title: '仪器编号', key: 'equipNum', width: 120 },
        { title: '仪器名称', key: 'equipName', width: 160 },
        { title: '使用人', key: 'applyName', width: 160 },
        { title: '使用开始时间', key: 'useStartTime', width: 180 },
        { title: '使用结束时间', key: 'useEndTime', width: 180 },
        { title: '开始性能', key: 'performanceStart', width: 120 },
        { title: '结束性能', key: 'performanceEnd', width: 120 },
        { title: '用途', key: 'uses', width: 160 },
        { title: '备注', key: 'remark', width: 210 },
        { title: '制造厂商', key: 'manufacturer', width: 200 },
        { title: '规格', key: 'spec', width: 200 }
      ],
      iconMsg: [{ type: 'pt-trash', id: '', name: '删除' }],
      getPage: {},
      formObj: {},
      salesmanList: [],
      rangeList: [],
      getOrder: {}
    }
  },
  mounted() {
    this.id = this.$route.query.id
    this._page()
    this._purchase(this.id)
    // this._getPurposeList()
    this._getSalesmanList()
  },
  methods: {
    _dateChange(key, handleObj) {
      this._handleRow(handleObj)
      if (key === 'useStartTime' && this.currentRow.useStartTime !== '') {
        if (
          this.currentRow.useEndTime !== '' &&
          new Date(this.currentRow.useStartTime).getTime() >
            new Date(this.currentRow.useEndTime).getTime()
        ) {
          this.$Message.warning('使用开始时间不能大于使用结束时间!')
          this._page()
        } else {
          this._save(key)
        }
      }
      if (key === 'useEndTime' && this.currentRow.useEndTime !== '') {
        if (
          this.currentRow.useStartTime !== '' &&
          new Date(this.currentRow.useEndTime).getTime() <
            new Date(this.currentRow.useStartTime).getTime()
        ) {
          this.$Message.warning('使用结束时间不能小于使用开始时间!')
          this._page()
        } else {
          this._save('useEndTime')
        }
      }
    },
    _performanceChange(key, handleObj) {
      this._handleRow(handleObj)
      if (key === 'performanceStart' && this.currentRow.performanceStart) {
        this._save('performanceStart')
      } else {
        this.$Message.warning('开始性能不能为空！')
        this._page()
      }
      if (key === 'performanceEnd' && this.currentRow.performanceEnd) {
        this._save('performanceEnd')
      } else {
        this.$Message.warning('结束性能不能为空！')
        this._page()
      }
    },
    _reasonChange(key, handleObj) {
      this._handleRow(handleObj)
      this._save(key)
    },
    // 人员列表
    _getSalesmanList: async function() {
      const result = await userGroup.userPage()
      if (result) {
        this.salesmanList = result.records
      }
    },
    // 用途
    _getPurposeList: async function(purpose = '') {
      const data = {
        item: 'purpose',
        name: purpose
      }
      this.rangeList = await equipInfo.getParamListByName(data)
    },
    _purposeChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.$set(this.currentRow, 'uses', data.purpose)
          this._save('uses')
          break
        case 'query':
          this.$set(this.currentRow, 'uses', data.purpose)
          this._getPurposeList(data.purpose)
          break
        case 'blur':
          this._save('uses')
          break
      }
    },

    _save: async function(key) {
      const obj = {
        id: this.currentRow.id,
        obj: { [key]: this.currentRow[key] }
      }
      const result = await equipRelDelivery.editEquip(obj)

      if (result) {
        this.$Message.success('编辑成功！')
      }
    },
    _page: async function() {
      const obj = Object.assign(
        { orderId: this.id },
        this.$refs.pageTable._searchParams()
      )
      const result = await equipRelDelivery.page(obj)
      if (result) {
        for (let i = 0; i < result.records.length; i++) {
          result.records[i].useStartTime = result.records[i].useStartTime
            ? new Date(result.records[i].useStartTime)
            : ''
          result.records[i].useEndTime = result.records[i].useEndTime
            ? new Date(result.records[i].useEndTime)
            : ''
        }
        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
      }
    },
    // 操作的序号
    _handleRow(data) {
      this.currentRow = data.row
    },
    _purchase: async function(id) {
      this.getOrder = await equipDeliveryOrder.getById(id)
    },
    _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 equipDeliveryOrder.approveEquip(data)
      if (result) {
        this.$Message.success('审批成功！')
        setTimeout(() => {
          parent.location.replace(global.webURL + '/sys/workflow/flow_task')
        }, 200)
      }
    },
    _deleteById(ids) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除该记录？',
        onOk: () => {
          this._delOk(ids)
        }
      })
    },
    _delOk: async function(id) {
      const result = await equipRelDelivery.deletePurIds(id)
      if (result) {
        this._page()
        this.$Message.success('删除成功！')
      }
    },
    _iconClick(res, data) {
      switch (res) {
        case '删除':
          this._deleteById(data.id)
          break
      }
    }
  }
}
</script>
