<template>
  <div>
    <Row>
      <!--查询-->
      <Col span="24">
        <Form v-show="searchOpen" :label-width="80" inline onsubmit="return false">
          <label class="label-sign"></label>
          <Form-item class="search-item" label="项目名称:">
            <Input v-model="formObj.expName" placeholder="请输入项目名称" clearable @on-enter="_formSearch"></Input>
          </Form-item>
          <Form-item class="search-btn">
            <Button type="primary" @click="_formSearch">搜索</Button>
          </Form-item>
        </Form>
      </Col>
      <!--操作-->
      <Col span="24">
        <btn-list  :open="searchOpen" :msg="btn" :show-search-btn="true" class="contHide"
                 @on-result-change="_btnClick"></btn-list>
      </Col>
      <!-- 表格 -->
      <Col span="24">
        <PTVXETable ref="pageTable" :table-height="tableHeight"
                    :icon-msg="iconMsg" :get-page="getPage" @on-result-change="_tableResultChange">
          <vxe-table-column
            v-for="item in pageColumns"
            :key="item.key"
            :field="item.key"
            :title="item.title"
            :min-width="item.width?item.width:200"
            :fixed="item.fixed?item.fixed:undefined" sortable>
            <template slot-scope="scope">
              <div v-if="item.dateTime">
                {{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM'):''}}
              </div>
              <div v-else>{{scope.row[item.key]}}</div>
            </template>
          </vxe-table-column>
        </PTVXETable>
      </Col>
    </Row>
    <ItemOriginalRecordEdit ref="recordEditModal"></ItemOriginalRecordEdit>
    <ItemView ref="itemViewModal"></ItemView>
  </div>
</template>
<script>
/**
 * 原始记录查看
 */
import Global from '../../../api/config'
import { soilReport, soilTest } from '../../../api'
import ItemOriginalRecordEdit from './OriginalRecordEdit'
import ItemView from './ItemView'

export default {
  components: {
    ItemOriginalRecordEdit,
    ItemView
  },
  data() {
    return {
      currentComponent: '',
      getPage: {},
      btn: [
        {
          type: 'error',
          id: 'do-test-sample-viewitem-delete-batch',
          name: '批量删除'
        },
        {
          type: 'primary',
          id: '',
          name: '合并'
        }
      ],
      selectIds: [],
      iconMsg: [
        {
          type: 'md-create',
          id: 'do-test-sample-viewitem-edit',
          name: '编辑'
        },
        {
          type: 'ios-book',
          id: 'do-test-sample-viewitem-view-report',
          name: '查看项目报告'
        },
        {
          type: 'md-trash',
          id: 'do-test-sample-viewitem-delete',
          name: '删除'
        },
        {
          type: 'md-albums',
          id: 'do-test-sample-viewitem-view-appendix',
          name: '生成/查看附录'
        }
      ],
      pageColumns: [
        { title: '项目名称', key: 'expName' },
        { title: '钻孔编号', key: 'boreholeName' },
        { title: '备注', key: 'remark' },
        { title: '创建人', key: 'uname' },
        { title: '创建时间', key: 'ctime', dateTime: true }
      ],
      formObj: {
        entrustId: '',
        expName: undefined
      },
      searchOpen: false
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('', 340)
      } else {
        return this.$tableHeight('tabNoSearch')
      }
    }
  },
  mounted() {
    this._page()
  },
  methods: {
    _componentResult(data) {
      switch (this.currentComponent) {
        case 'EditDateModal':
          this._updateDate(data)
          break
        default:
          this._page()
      }
    },
    _btnClick(msg, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (msg) {
          case '批量删除':
            this._batchDelete()
            break
          case '合并':
            this._merge()
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    _merge() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this._mergeFile()
      }
    },
    _mergeFile: async function() {
      this.$refs.pageTable._showLoading()
      const result = await soilReport.itemReportMerge({
        ids: this.selectIds.join(',')
      })
      if (result) {
        this.$Message.success('合并成功')
        this._page()
      }
    },
    _batchDelete() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定删除？',
          onOk: () => {
            this._delete()
          }
        })
      }
    },
    _delete: async function() {
      const result = await soilTest.batchDeleteReport(this.selectIds.join(','))
      if (result) {
        this.$Message.success('删除成功')
        this._page()
      }
    },
    _iconClick(res, data, currentComponent) {
      this.currentComponent = currentComponent
      this.$nextTick(() => {
        switch (res) {
          case '编辑':
            // this.$refs.recordEditModal._openWithType(
            //   data.originalRecordId,
            //   'ENVTESTMAKEEDIT'
            // )
            this._reportMakeLook(data)
            break
          case '查看项目报告':
            this._reportView(data)
            // this._recordView(data.originalRecordId)
            break
          case '查看试验项目':
            this._itemView(data.id)
            break
          case '生成/查看附录':
            if (data.appendixKey) {
              this._viewAppendix(data)
            } else {
              this._generateAppendix(data.id)
            }
            break
          case '删除':
            this._deleteByIds([data.id])
            break
        }
      })
    },
    _generateAppendix: async function(id) {
      this.$Message.warning('正在生成，请稍后')
      this.$refs.pageTable._showLoading()
      const result = await soilReport.generateAppendix({ id: id })
      if (result) {
        this.$Message.success('生成成功')
        this.$refs.pageTable._hideLoading()
        this._page()
        this._viewAppendix(result)
      } else {
        this.$Message.warning('生成失败，请重试')
        this.$refs.pageTable._hideLoading()
      }
    },
    // 查看试验项目
    _itemView(id) {
      this.$refs.itemViewModal._open(id)
    },
    _reportView(data) {
      if (data.objectKey) {
        this._reportMakeLook(data)
      } else {
        this._recordView(data.originalRecordId)
      }
    },
    _reportMakeLook: async function(data) {
      const result = await soilReport.expReportGetById(data.id)
      if (result) {
        this._viewReport(result)
      }
    },
    _viewAppendix(data) {
      if (data) {
        this.$openWindowModeless({
          objectKey: data.appendixKey,
          idType: 13,
          id: data.id,
          isReport: 5
        })
      }
    },
    _viewReport(data) {
      if (data) {
        this.$openWindowModeless({
          objectKey: data.objectKey,
          idType: 13,
          id: data.id,
          isReport: 4
        })
      }
    },
    // 查看原始记录
    _recordView(originalRecordId) {
      let recordUrl = ''
      if (process.env.NODE_ENV === 'production') {
        recordUrl = 'http://record.patzn.com'
      } else {
        recordUrl = Global.recordURL
      }
      // eslint-disable-next-line no-undef
      layx.iframe(
        'labRecordWriteOriView',
        '原始记录预览',
        recordUrl + '/print/v1/form/' + originalRecordId + '?type=ENVTESTMAKE',
        {
          event: {
            onload: {
              after: function(layxWindow, winform) {
                // eslint-disable-next-line no-undef
                layx.max(winform.id)
              }
            }
          }
        }
      )
    },
    _open(entrustId) {
      this.formObj.entrustId = entrustId
      this._page()
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'selectIds':
          this.selectIds = data
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData, data.componentName)
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _page: async function() {
      this.selectIds = []
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      const result = await soilTest.expReportPage(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    // 删除原始记录
    _deleteByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录？',
        onOk: () => {
          this._deleteOk(ids)
        }
      })
    },
    _deleteOk: async function(ids) {
      const result = await soilTest.deleteReport(ids)
      if (result) {
        this.$Message.success('删除成功')
        this._page()
      }
    }
  }
}
</script>
