<template>
  <div>
    <Modal v-model="showModal" v-drag width="1100">
      <p slot="header">选择原始记录模板</p>
      <div>
        <TwoCard @on-result-change="_refresh" :gutter=16 left-name="原始记录模板类别" right-name="实验室原始记录模板名称" left-span="8">
          <template slot="left">
            <OriginalRecordClassTree ref="classTree" @on-result-change="_classData"></OriginalRecordClassTree>
          </template>
          <template slot="right">
            <Row>
              <!--查询-->
              <Col span="24">
                <Form :label-width="50" inline onsubmit="return false">
                  <label class="label-sign"></label>
                  <Form-item label="名称:">
                    <Input v-model="formObj.title" @on-enter="_search" placeholder="请输入名称" style="width: 200px"
                           clearable/>
                  </Form-item>
                  <Form-item class="search-btn">
                    <Button @click="_search" type="primary">搜索</Button>
                  </Form-item>
                </Form>
              </Col>
              <!-- 表格 -->
              <Col span="24">
                <PTVXETableHeight ref="pageTable" :tableHeight="tableHeight"
                            @on-result-change="_tableResultChange" :getPage="getPage" :isRadio="true" hide-checkbox>
                  <vxe-table-column
                    :field="item.key"
                    :title="item.title"
                    :min-width="item.width?item.width:200"
                    :fixed="item.fixed?item.fixed:undefined"
                    v-for="(item) in pageColumns"
                    :key="item.key" sortable>
                    <template slot-scope="scope">
                      <div v-if="item.key==='ctime'">
                        {{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM:ss'):''}}
                      </div>
                      <div v-else>{{scope.row[item.key]}}</div>
                    </template>
                  </vxe-table-column>
                </PTVXETableHeight>
              </Col>
            </Row>
          </template>
        </TwoCard>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" @on-result-change="_footerResult" :footer="footerList"></modal-footer>
      </div>
    </Modal>
    <!--自定义post请求iframe-->
    <RecordIframe ref="iframeModal"></RecordIframe>
  </div>
</template>
<script>
/**
 * 选择原始记录模板（实验室的）
 */
import Global from '../../../api/config'
import TwoCard from '../../../components/base/TwoCard'
import { soilTest } from '../../../api'
import OriginalRecordClassTree from './OriginalRecordClassTree'
import RecordIframe from './RecordIframe'
let count = 0
export default {
  components: {
    OriginalRecordClassTree,
    TwoCard,
    RecordIframe
  },
  data() {
    return {
      showModal: false,
      getPage: {},
      pageColumns: [{ title: '名称', key: 'title' }],
      formObj: {
        id: '',
        title: '',
        businessTypeList: 0
      },
      entrustId: '',
      clientList: [],
      selectData: [],
      itemIds: [],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '确定', type: 'primary' }
      ]
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('', 300)
    }
  },
  created() {
    // 监听原始记录消息
    // eslint-disable-next-line nuxt/no-globals-in-created
    window.addEventListener('message', this._saveOriginal)
  },
  // 销毁监听事件
  beforeDestroy() {
    count = 0
    window.removeEventListener('message', this._saveOriginal)
  },
  methods: {
    // 刷新左右数据
    _refresh() {
      this.formObj = this.$resetFields(this.formObj)
      this.formObj.businessTypeList = 0
      this.$refs.classTree._requestByBusinessTypeList()
      this._search()
    },
    // 左侧数据请求
    _classTree() {
      const height = this.$tableHeight('', 300)
      this.$refs.classTree._Ztree(height, 0)
    },
    // 左边树的点击
    _classData(result) {
      if (result !== undefined) {
        this.formObj.id = result.id
      } else {
        this.formObj.id = ''
      }
      this._search()
    },
    /** *modal-footer */
    _footerResult(name) {
      switch (name) {
        case '取消':
          this.showModal = false
          break
        case '确定':
          this._ok()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _open(ids, entrustId, clientInfo) {
      console.log(Global.recordURL)
      this.formObj = this.$resetFields(this.formObj)
      this.entrustId = entrustId
      this.clientList = clientInfo
      this._classTree()
      this.showModal = true
      this.itemIds = ids
      this.formObj.businessTypeList = 0
      this._page()
      this.selectData = []
      this._hideLoading()
      count = 0
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      this.formObj.entrustId = this.id
      const result = await soilTest.templatePage(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    _search() {
      this.$refs.pageTable._pageChange(1)
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'singleSelect':
          this.selectData = [data]
          break
        case 'dbSelect':
          this.selectData = [data]
          this._ok()
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _ok() {
      if (this.selectData.length === 0) {
        this.$Message.warning('请选择一个原始记录模板！')
        this._hideLoading()
      } else {
        console.log(this.selectData)
        // 校验多样品多项目原始记录模板
        this._createOriginalRecord()
      }
    },
    _check: async function(param) {
      const result = await soilTest.checkLimit(param)
      console.log(result)
    },
    _createOriginalRecord() {
      this.showModal = false
      console.log('环境', process.env.NODE_ENV)
      let recordUrl = ''
      if (process.env.NODE_ENV === 'production') {
        recordUrl = 'http://record.patzn.com'
      } else {
        recordUrl = Global.recordURL
      }
      let baseUrl = Global.baseURL
      baseUrl +=
        '/soil/v1/sample/original_record_data_bind?entrustId=' +
        this.entrustId +
        '&expIds=' +
        this.itemIds +
        '&modelId=' +
        this.selectData[0].id
      const url =
        recordUrl +
        '/print/v1/eln/template_meter_' +
        this.selectData[0].id +
        '?bindUri=' +
        encodeURIComponent(baseUrl)
      const params = {
        ids: this.itemIds.join(','),
        client: this.clientList[0],
        bindUri: encodeURIComponent(baseUrl)
      }
      this.$refs.iframeModal._createIframe(url, params)
      console.log('原始记录', url, params)
      localStorage.setItem('recordStatus', 'addLabRecord')
    },
    _recordChange() {
      this.$emit('on-result-change')
    },
    _save: async function(temp) {
      const result = await soilTest.saveItem(temp)
      console.log(result)
      if (result) {
        this.$Message.success('添加成功')
        this._recordChange()
        this.$refs.iframeModal._closeIframe()
      }
    },
    // 保存原始记录信息
    _saveOriginal(data) {
      if (localStorage.getItem('recordStatus') === 'addLabRecord') {
        if (count === 0) {
          if (data.data.msg !== true) {
            // 添加
            const tempData = {
              formId: data.data.msg,
              ids: this.itemIds.join(',')
            }
            console.log('saveData', data)
            const copyMapTemp = {}
            if (data.data.copySheet && data.data.copyedSheet) {
              tempData.copyMap = {}
              const copyedKey = String(data.data.copyedSheet)
              copyMapTemp[copyedKey] = ''
              copyMapTemp[copyedKey] = String(data.data.copySheet)
              // 存在复制sheet的情况
              tempData.copyMap = JSON.stringify(copyMapTemp)
            } else if (typeof data.data.testValueArry !== 'undefined') {
              const testValue = data.data.testValueArry
              tempData.copyMap = {}
              testValue.forEach(item => {
                const copyedKey = String(item.copyedSheet)
                copyMapTemp[copyedKey] = ''
                copyMapTemp[copyedKey] = String(item.copySheet)
                tempData.copyMap = JSON.stringify(copyMapTemp)
              })
            }
            console.log('保存的数据', tempData)
            if (tempData.formId !== undefined) {
              tempData.entrustId = this.entrustId
              this._save(tempData)
            }
          }
        }
        count = count + 1
      }
    }
  }
}
</script>
