<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">
                <PTVXETable 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>
                </PTVXETable>
              </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: '',
      selectData: [],
      itemIds: [],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '确定', type: 'primary' }
      ]
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('', 380)
    }
  },
  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('', 85)
      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) {
      this.formObj = this.$resetFields(this.formObj)
      this.entrustId = entrustId
      this._classTree()
      this.showModal = true
      this.itemIds = ids
      this.formObj.businessTypeList = 0
      this._page()
      this.selectData = []
      this._hideLoading()
      count = 0
    },
    // _page() {
    //   // 只查实验室的
    //   console.log('page')
    //   // this.$refs.pageTable._page(
    //   //   '',
    //   //   'ElnTemplate/page',
    //   //   this.$serializeFormSearch(this.formObj)
    //   // )
    // },
    _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 'page':
          this.selectData = []
          this.getPage = this.$store.state.ElnTemplate.page
          break
        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 {
        // 校验多样品多项目原始记录模板
        const param = {
          ids: '1289126946969550850',
          tempId: this.selectData[0].id
        }
        console.log(param)
        this._createOriginalRecord()
        // this._check(param)
        // this.$store.dispatch('EnvItem/checkLimit', param).then(() => {
        //   const result = this.$store.state.EnvItem.success
        //   if (result) {
        //     // 不是多样品项目模板或者数量小于限值,填写原始记录
        //     // (3)originalTemplateId不为0也不为undefined ---- 填写过或者绑定过
        //     this._bindOriginalRecord()
        //   } else {
        //     this.$msgTip('warning', '所选数据超过，原始记录模板设置最大值！')
        //     this._hideLoading()
        //   }
        // })
      }
    },
    _check: async function(param) {
      const result = await soilTest.checkLimit(param)
      console.log(result)
    },
    _createOriginalRecord() {
      // const result = await soilTest.searchItem({ ids: this.itemIds.join(',') })
      // console.log(result)
      this.showModal = false
      const url =
        Global.recordURL + '/print/v1/eln/template_YT_' + this.selectData[0].id
      const params = {
        ids: this.itemIds.join(',')
        // allSampleCount: '',
        // normalSampleCount: '',
        // itemCount: '',
        // parallelCount: '',
        // labelSample: ''
      }
      this.$refs.iframeModal._createIframe(url, params)

      localStorage.setItem('recordStatus', 'addLabRecord')
    },
    // 生成原始记录
    _bindOriginalRecord() {
      this.$store
        .dispatch('EnvItem/allCommonSampleCount', {
          ids: this.itemIds.join(',')
        })
        .then(() => {
          const result = this.$store.state.EnvItem.list
          let allSampleCount = ''
          let normalSampleCount = ''
          let itemCount = ''
          let parallel = ''
          let labelSample = ''

          result.forEach(item => {
            if (item.sampleCountType === 'all') {
              allSampleCount = item.sampleCountInteger
            } else if (item.sampleCountType === 'normal') {
              normalSampleCount = item.sampleCountInteger
            } else if (item.sampleCountType === 'item') {
              itemCount = item.sampleCountInteger
            } else if (item.sampleCountType === 'parallel') {
              parallel = item.sampleCountInteger
            } else if (item.sampleCountType === 'mark') {
              labelSample = item.sampleCountInteger
            }
          })
          this.showModal = false

          const url =
            Global.recordURL +
            '/print/v1/eln/template_YT_' +
            this.selectData[0].id
          const params = {
            ids: this.itemIds.join(','),
            allSampleCount: allSampleCount,
            normalSampleCount: normalSampleCount,
            itemCount: itemCount,
            parallelCount: parallel,
            labelSample: labelSample
          }
          this.$refs.iframeModal._createIframe(url, params)

          localStorage.setItem('recordStatus', 'addLabRecord')
          // this.$layx('recordAddTemplate', '原始记录添加', Global.recordURL + '/print/v1/eln/template_YT_'
          //   + this.selectData[0].id
          //   + '?bindUri=' + encodeURIComponent(bindUri))
        })
    },
    _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)
            }
            // 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>
