<template>
  <div class="height100">
    <!-- 页签 -->
    <ul class="m-tabs__header mrgb5" v-if="pages.length > 0">
      <li class="font12" :class="{ active: pagesACV == item.value }" v-for="(item, index) in pages" :key="index" @click="pagesFn(item.value)"><span class="text fl transition__all_3s">{{ item.name }}</span></li>
    </ul>
    <div class="flexYbox" :style="{ height: pages.length > 0 ? 'calc(100% - 35px)':'100%' }">
      <div class="">
        <screen v-model="screen" @loadSuccess="screenSuccess"></screen>
      </div>
      <div class="hidden flex">
        <div class="height100" style="position: absolute; width: 100%;">
        <ts-table
          :source="source"
          width="100%"
          height="100%"
          ref="biModTable"
          v-if="initState == true"
          :merge-cells="mergeCells"
          @loadSuccess="tableSuccess"
        ></ts-table>
        </div>
      </div>
    </div>
    <div v-if="remak" v-html="remak" class="font12 red"></div>
    <div>
      <div v-for="(item, index) in imgForm" :key="index" class="fl hidden" :style="{ width: imgForm.length > 1 ? '50%':'100%' }">
        <ts-g2-chart :title="item.title" :chartType="item.type" :data="item._data" height="200"></ts-g2-chart>
      </div>
    </div>
    <diaLog :source="detailSource" width="100%" height="100%" ref="reportFormsDetail" @close="detailClose" @open="detailOpen">
      <div class="flexYbox height100">
        <div class="mrgb5">
          <ts-button type="button" icon="iconfont icon-daochu" class="fr" @click="exportExcel(filename)">导出</ts-button>
        </div>
        <div class="hidden flex">
          <ts-table :source="detailTableSource" ref="reportFormsdetailTableSource" width="100%" height="100%" v-if="detailTableShow == true"></ts-table>
        </div>
      </div>
    </diaLog>
  </div>
</template>

<script>
import screen from './screen'

export default {
  name: 'reportForms',
  components: {
    screen
  },
  props: {
    value: {
      type: [String, Number, Object],
      default: function () {
        return {}
      }
    },
    params: {
      type: [String, Number, Object],
      default: function () {
        return {}
      }
    }
  },
  data: function() {
    return {
      initState: false,
      postData: {},
      source: {},
      screen: {},
      remak: '',
      formData: [],
      imgForm: [],
      setData: {},
      mergeCells: [],
      totalSet: [],
      pages: [],
      pagesName: '',
      pagesACV: '',
      pageConfig: [],
      detailSource: {
        title: '详细查询', // 标题
        closeBtn: true, // 关闭按钮区域，boolean 默认：false
      },
      detailTableSource: this.detailSourceFn(),
      detailTableShow: false,
      filename: ''
    }
  },
  created () {
    this.postData.id = this.params.id
    this.init()
  },
  mounted () {
    window['_biFn' + this.postData.id] = this.detailFn
  },
  methods: {
    exportExcel(){
      const _this = this
      let data = JSON.parse(JSON.stringify( _this.detailTableSource.postData))
      this.$api({
        url: '/ts-query/api/user/query/table/export/excel',
        method: 'post',
        data: data,
        responseType: 'blob'
      }).then(function (res) {
        // 请求成功
        let blob = res.data
        if(blob.size > 0) {
          let reader = new FileReader()
          reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
          reader.onload = function (e) {
            // 转换完成，创建一个a标签用于下载
            let a = document.createElement('a')
            a.download = new Date().getTime() + '.' + 'xls'
            a.href = e.target.result;
            document.body.appendChild(a)
            a.click()
            a.remove()
          }
        }
      }).catch(function (error) {
          // 请求失败
      })

    },
    detailSourceFn() {
      return {
        rownumbers: true,
        url: '/ts-query/api/user/query/table/query',
        method: 'post',
        colModel: [],
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        showOverflow: true,
        postData: {}
      }
    },
    // 合并菜单
    mergeMenu () {
      const _this = this
      this.$api({
        url: '/ts-query/api/user/combine/page/' + this.params.mid,
        method: 'get',
        data: {
          query: true
        }
      }).then(function (res) {
        if (res.success === true) {
          _this.pageConfig = JSON.parse(res.object.pageConfig || '[]')
        } else {
          _this.$utils.msg(_this, res.message || '数据加载失败！','warning')
        }
      })
    },
    // 非合并菜单
    init () {
      const _this = this
      this.$api({
        url: '/ts-query/api/user/query/table/select/' + this.params.id,
        method: 'get',
        data: {
          query: true
        }
      }).then(function (res) {
        // 请求成功
        _this.setData = res.object
        _this.formData = JSON.parse(res.object.formData || '[]')
        // _this.postData.parameters = JSON.stringify(res.object.dateInitValues)
        _this.screen = {
          data: res.object.savedConditions,
          dates: res.object.dateInitValues || [],
          params: _this.params
        }
        _this.remak = res.object.queryDescription // 备注
      }).catch(function (error) {
          // 请求失败
      })
    },
    // 页签切换
    pagesFn (val) {
      this.pagesACV = val
      this.postData[this.pagesName] = val
      this.refresh(this.postData)
    },
    // 筛选加载完成
    screenSuccess (d, pages) {
      let arr = []
      let str = ''
      this.postData = { ...this.postData, ...d }
      if (pages && pages.str) {
        str = pages.str.split(';')
        for (let i in str) {
          let v = str[i].split(',')
          if (i === '0') {
            this.pagesACV = v[1]
          }
          arr[i] = {
            name: v[0],
            value: v[1]
          }
        }
        this.pages = arr
        this.postData[pages.name] = this.pagesACV
        this.pagesName = pages.name
      }
      if (typeof this.setData.tableColumns === 'object') {
        this.source = this.sourceFn(this.setData)
        this.initState = true
      }
    },
    // 列表数据
    sourceFn (data) {
      let col = this.colFn(data.tableColumns)
      let totalSet = []
      data.tableColumns.forEach(v => {
        if (v.combine === true) {
          totalSet.push(v.name)
        }
      })
      return {
        url: '/ts-query/api/user/query/table/query',
        method: 'post',
        postData: this.postData,
        colModel: col,
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        // sord: 'desc', // 排序
        sortname: 'create_date', // 初始化排序字段
        totalSet: totalSet, // 合计设置，填写需要合计的列, 无合计时不填写
        offPage: false,
        checkboxChange (rowid, data) {
          // rowid：行id  data：选中行数据
        },
        checkboxAll (selection) {
          // selection：选中行数据
        }
      }
    },
    // 表头
    colFn (arr) {
      const _this = this
      let d = []
      let totalSet = [] // 合计字段
      arr.forEach((v, i) => {
        let _a = {
          title: v.title || v.name,
          field: v.name,
          width: v.width || 140,
          align: v.align || 'left',
          sortable: v.sort
        }
        if(v.subQueryId) {
          let o = { ...v }
          _a.type = 'html'
          _a.formatter = function({ cellValue, row, column }) {
            let con = '<a style="height:14px; overflow:hidden;color:var(--base-acv);cursor:pointer;" onClick="window._biFn' + _this.postData.id + '(\'' + o.subQueryId + '\', \'' + o.subQueryParam + '\', \'' + cellValue + '\')">' + cellValue + '</a>'
            return con
          }
        }
        // 是否冻结
        if(arr[i].frost === true) {
          _a.frozen = true
          _a.sortable = false
        }
        if (d.hidden === true) {
          _a.hidden = true
        }
        // 表尾
        totalSet.push(v.name)
        if (v.type === 'NUMBER') {
          
        }
        // 合并列
        if(arr[i].combine == true) {
          this.mergeCells.push(v.name)
        }
        if (v.children) {
          _a.children = this.colFn(arr[i].children)
        }
        d.push(_a);
      })
      this.totalSet = [...this.totalSet, ...totalSet]
      return d
    },
    // 列表加载完成
    tableSuccess (data) {
      let totalSet = [] // 合计字段
      let d = {}
      this.imgForm = []
      if (data === null) {
        return false
      }
      this.formData.forEach((v, i) => {
        v._data = this.fmtData(data, v)
        this.imgForm.push(v)
      })
      data = data || []
      if (data.length > 0) {
        d = data[0]
      }
      Object.keys(d).forEach(item => {
        let val = Number(d[item] || 0)
        if (!isNaN(val) && typeof val == 'number') {
          totalSet.push(item)
        }
      })
      if (totalSet.length > 0) {
        // this.source.totalSet = totalSet
      }
    },
    // 图表数据格式
    fmtData (data, arr) {
      let d = []
      for (let i in data) {
        let _d = {}
        for (let l in arr.data) {
          let unit = '' // 单位
          let val = data[i][arr.data[l].ratherval]
          let lastChar = val.charAt(val.length - 1) // 取值最后一位
          val = val.substr(0, val.length - 1)
          val = val.split(',').join('')
          switch(lastChar) {
            case '万':
              unit = '万'
              break
            case '%':
              unit = '%'
              break
            case '-':
              val = 0
              break
          }
          val = Number(val)
          _d = {
            column: arr.data[l].column,
            category: data[i][arr.data[l].rathernamecode],
            value: val,
            unit: unit
          }
          d.push(_d);
        }
      }
      return d
    },
    // 刷新
    refresh (data) {
      if (data) {
        this.postData = { ...this.source.postData, ...data }
        this.source.postData = { ...this.source.postData, ...data }
      }
      this.$nextTick(()=>{
      this.$refs.biModTable.refresh()
      })
    },
    // 详情
    detailFn (id, name, text) {
      const _this = this
      let d = JSON.parse(JSON.stringify(this.postData))
      d.id = id
      d[name] = text
      this.$api({
        url: '/ts-query/api/user/query/table/select/' + id,
        method: 'get',
        data: {
          query: true
        }
      }).then(function (res) {
        _this.detailTableSource.colModel = _this.colFn(res.object.tableColumns)
        _this.detailTableSource.postData = d
        _this.filename = text
        _this.$refs.reportFormsDetail.open()
        if( _this.$refs.reportFormsdetailTableSource){
          _this.$refs.reportFormsdetailTableSource.refresh()
        }
      }).catch(function (error) {
          // 请求失败
      })
    },
    // 详情打开
    detailOpen () {
      this.detailTableShow = true
    },
    // 详情关闭
    detailClose () {
      this.detailTableShow = false
    }
  },
  watch: {
    '$route' (to, from) {
    }
  },
  destroyed () {
    delete window['_biFn' + this.postData.id]
  }
}
</script>

<style scoped>
  .m-tabs{
    height: 300px;
}
.m-tabs__outbox{
    height: calc(100% - 2px);
    border: 1px #e8e8e8 solid;
    overflow: hidden;
}
.m-tabs__header{
    height: 30px;
    background-color: #fff;
    padding-bottom: 3px;
}
.m-tabs__header li{
  height: 26px;
  float: left;
  line-height: 26px;
  padding: 4px 0 3px 0;
  margin: 0 10px;
  position: relative;
  cursor: pointer;
  font-size:14px ;
}
.m-tabs__header li.active{
    border-bottom: 2px solid var(--theme_color);
  color: var(--theme_color);
}
.m-tabs__header li .text:hover{
   color: var(--theme_color);
}
.m-tabs__header li .icon{
  width: 16px;
  height: 16px;
  display: inline-block;
  overflow: hidden;
  line-height: 16px;
  border-radius: 100%;
  color: #999;
  position: absolute;
  right: 8px;
  top: 5px;
  cursor: pointer;
}
.m-tabs__header li .icon:hover{
    color: var(--base-black);
}
.m-tabs__header li.active{
    color: var(--base-acv);
}
li:first-child{
  margin: 0 10px 0 5px;
}
.m-tabs__box{
    /* width: calc(100% - 14px);
    height: calc(100% - 43px); */
    width: 100%;
    height: calc(100% - 30px);
    position: relative;
    /* padding: 6px; */
    overflow: hidden;
}
.m-tabs__con{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 10;
    overflow: hidden;
    overflow-y: auto;
    background-color: #fff;
}
.m-tabs-con__item{
    height: 100%;
    display: none;
}
.m-tabs-con__active{
    display: block;
}
</style>
