<template>
  <div>
    <Modal v-model="showModal" v-drag width="1100">
      <p slot="header">选择原始记录模板</p>
      <div>
        <TwoCard :gutter=16 left-name="证书模板类别" right-name="证书模板名称" left-span="8" @on-result-change="_refresh">
          <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" placeholder="请输入名称" style="width: 200px" clearable
                           @on-enter="_search"/>
                  </Form-item>
                  <Form-item class="search-btn">
                    <Button type="primary" @click="_search">搜索</Button>
                  </Form-item>
                </Form>
              </Col>
              <!-- 表格 -->
              <Col span="24">
                <PTVXETable ref="pageTable" :height="300"
                            :get-page="getPage" :is-radio="true" hide-checkbox @on-result-change="_tableResultChange">
                  <vxe-table-column
                    v-for="(item,index) in pageColumns"
                    :key="index"
                    :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.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>
                </PTVXETable>
              </Col>
            </Row>
          </template>
        </TwoCard>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult"></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 { meterPrint } from '../../../api'
import RecordIframe from './RecordIframe'
import OriginalRecordClassTree from './OriginalRecordClassTree'
let count = 0

export default {
  components: {
    OriginalRecordClassTree,
    TwoCard,
    RecordIframe
  },
  data() {
    return {
      showModal: false,
      getPage: {},
      pageColumns: [
        { title: '名称', key: 'title' },
        { title: '项目代号', key: 'remark' }
      ],
      formObj: {
        // id: '',
        title: ''
        // businessTypeList: 0
      },
      selectData: [],
      sampleId: '',
      sampleData: '',
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '确定', type: 'primary' }
      ]
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('', 380)
    }
  },
  mounted() {
    // 监听原始记录消息
    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('', 345)
      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(sampleId, data) {
      this.formObj = this.$resetFields(this.formObj)
      this._classTree()
      this.showModal = true
      this.sampleId = sampleId
      this.sampleData = data
      this._page()
      this.selectData = []
      this._hideLoading()
      count = 0
    },
    _page: async function(data) {
      const result = await meterPrint.pageSampleTemplate(data)
      if (result) {
        this.getPage = result
      }
    },
    _search() {
      // this.$refs.pageTable._pageChange(1)
      this._page(this.formObj)
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'singleSelect':
          this.selectData = [data]
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _ok() {
      if (this.selectData.length === 0) {
        this.$Message.warning('请选择一个原始记录模板！')
        this._hideLoading()
      } else {
        // 校验多样品多项目原始记录模板
        const url =
          Global.recordURL +
          '/meter/v1/sample/certificate_record_data_bind?' +
          this.selectData[0].id
        const param = {
          sampleId: this.sampleId,
          tempId: this.selectData[0].id,
          remark: this.selectData[0].remark,
          dataSource: this.sampleData
        }
        console.log(url, param)
        // this.$refs.iframeModal._createIframe(url, param)
        this.$emit('on-result-change', param)
      }
    },
    _recordChange() {
      this.$emit('on-result-change')
    },
    // 保存原始记录信息
    _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)
              })
            }
            this.$store
              .dispatch('EnvItem/saveFormForItem', tempData)
              .then(() => {
                if (this.$store.state.EnvItem.success) {
                  this.$Message.success('添加成功')
                  this._recordChange()
                  this.$refs.iframeModal._closeIframe()
                  // 关闭所有layx弹框
                  // layx.destroyAll('recordAddTemplate');
                }
              })
          }
        }
        count = count + 1
      }
    }
  }
}
</script>
