<template>
  <div class="report-container report-preview" >
    <div class="report-form-container">
      <!--检索条件-->
      <!--下面是搜索条件-->
      <el-form label-position="right" class="simple-search-form-outline" inline >
        <template  v-for="(query, index) in queryArrObj">
          <!--时间条件-->
          <template v-if="query.ifQueryTime===1">
            <el-form-item :label="query.kpiName" v-if="query.timeTypeId===1">
              <date-signal v-model="query.valueArr" :offset="query.timeDefaultOffset">
              </date-signal>
            </el-form-item>
            <el-form-item :label="query.kpiName" v-if="query.timeTypeId===2">
              <date-signal v-model="query.valueArr" :showButton="true" :offset="query.timeDefaultOffset">
              </date-signal>
            </el-form-item>
            <el-form-item :label="query.kpiName" v-if="query.timeTypeId===3">
              <date-week v-model="query.valueArr" :offset="query.timeDefaultOffset">
              </date-week>
            </el-form-item>
            <el-form-item :label="query.kpiName" v-if="query.timeTypeId===4">
              <date-range v-model="query.valueArr" :offset="query.timeDefaultOffset">
              </date-range>
            </el-form-item>
            <!--<el-form-item label="月" v-if="query.timeTypeId===5">-->
            <!--<date-month v-model="query.value">-->
            <!--</date-month>-->
            <!--</el-form-item>-->

          </template>

          <!--搜索条件-->
          <template v-if="query.ifQuerySearch===1">
            <el-form-item :label="query.kpiName" v-if="query.searchTypeId===1||query.searchTypeId===2">
              <el-input placeholder="请输入内容" v-model="query.value"  @input.native="queryUpdate(index)" @change.native="queryUpdate(index)" value="query.value" @keyup.native.enter="getList">
              </el-input>
            </el-form-item>

            <el-form-item :label="query.kpiName" v-if="query.searchTypeId===3">
            <el-select v-model="query.valueArr" placeholder="请选择" clearable filterable  multiple collapse-tags>
              <el-option
                v-for="(item,idx) in query.queryOptions"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            </el-form-item>
          </template>
        </template>

        <el-form-item v-if="queryArr.length>0">
          <el-button type="primary" @click="getList">查询</el-button>
        </el-form-item>

      </el-form>
    </div>
    <div class="report-download-container">
      <div>
        <el-button type="primary" @click="download">下载</el-button>
      </div>
      <div class="report-data-label-filter">
        <el-form  inline>
          <el-form-item label="聚合KPI" v-if="useOperableGroup" >
            <el-select multiple collapse-tags v-model="groupKpiCodes" placeholder="请选择"  filterable  >
              <el-option
                v-for="(item,idx) in operableGroupKpis"
                :key="item.kpiCode"
                :label="item.rname"
                :value="item.kpiCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="KPI 名称">
            <el-select multiple collapse-tags v-model="selectedKpis" placeholder="请选择"  filterable  >
              <el-option
                v-for="(item,idx) in kpiOptions"
                :key="item.prop"
                :label="item.title"
                :value="item.prop">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="report-data-container" :class="reportLayer">
      <!--数据展示-->
      <div class="report-table-container">
        <!--table-->
        <table-component :searchParam="searchForm" :tableOption="{tableLabel: tableColumn, resizable: true, defaultSort: {prop: queryDefaultSortKpiCode ,order: queryDefaultOrder === 'desc' ?  'descending': 'ascending' },}" :drillDown="getSubReport" :ifTotal="ifTotal" :totalShowType="totalShowType" :ifPage="ifPage"></table-component>
      </div>
      <div class="report-chart-container " :class="chartLayer">
        <!--echarts-->
        <div class="line-chart" :id="'lineChart_'+groupIndex" v-if="ifBarAndLine"></div>
        <div class="pie-chart" :id="'pieChart_'+groupIndex" v-if="ifPie"></div>
      </div>
    </div>
    <!--下钻弹窗-->
    <el-dialog :title="subReport.reportName" :visible.sync="dialogTableVisible" v-if="!!ifDrillDown" width="80%">
      <report v-if="isReloadAlive"
              :queryDefaultSortKpiCode="subReport.queryDefaultSortKpiCode"
              :queryDefaultOrder="subReport.queryDefaultOrder"
              :ifOutsideParam="subReport.ifOutsideParam"
              :ifOutsideParamValue="ifOutsideParamValue"
              :groupIndex="subReport.reportId"

              :ifDrillDown="subReport.ifDrillDown"
              :drillDownRelated="subReport.drillDowns"
              :extraSearchCoindition="extraCondition"

              :reportId="subReport.reportId"
              :ifTotal="subReport.ifTotal"
              :totalShowType="subReport.totalShowType"
              :ifPage="subReport.ifPage"
              :queryArr="subReport.querys"
              :tableLabelArr="subReport.kpis"
              :ifBarAndLine="subReport.barAndLineCharts.length>0"
              :ifPie="subReport.pieViews.length>0"

              :reportLayer="layerClass.reportClass"
              :chartLayer="layerClass.chartClass"
              :chartColor="chartTheme.data"

              :useOperableGroup="subReport.useOperableGroup"
              :operableGroupKpis="subReport.operableGroupKpis"
              :defaultGroupKpis="subReport.defaultGroupKpis"
      ></report>
    </el-dialog>


  </div>
</template>

<script>

  import Axios from 'axios'
  import tableComponent from './table.vue'
  import dateMonth from './date-month.vue'
  import dateRange from './date-range.vue'
  import dateSignal from './date-signal.vue'
  import dateWeek from './date-week.vue'

  import {kpiColors} from '@/views/Report/ReportManagement/kpi-color'
  import {barLineOption,pieOption} from '@/views/Report/ReportManagement/echarts-option'

  import {layerClass} from '@/views/Report/ReportManagement/layer-class'
  import {echartsThemes} from '@/views/Report/ReportManagement/echarts-color-themes'

  import {deepCopy, randomStr, numberFormateThousand, GetDateStr} from '@/utils/util'
  export default {
    name: "report",
    components: { tableComponent, dateMonth,dateRange,dateSignal,dateWeek},
    props: {
      queryDefaultSortKpiCode: {
        default: ''
      },
      useOperableGroup: {
        default: false
      },
      // 可选聚合kpi 数组对象
      operableGroupKpis: {
        default: []
      },
      // 默认聚合KPI数组对象
      defaultGroupKpis: {
        default: []
      },
      queryDefaultOrder: {
        default: ''
      },
      ifOutsideParamValue: {
        default: ''
      },
      ifOutsideParam: {
        default: 0
      },
      ifBarAndLine: {
        default: false
      },
      ifPie: {
        default: false
      },
      ifDrillDown: {
        default: null
      },
      // 下钻条件
      drillDownRelated: {
        default: ()=>([]),
      },
      extraSearchCoindition: {
        default: ()=>([]),
      },
      reportId: {
        default: 0,
      },
      // 给echart用的唯一id
      groupIndex: {
        // 这个随机数在一次执行队列里输出的都一样，所以不适用于分组展示的情况
        default: randomStr(),
      },
      // 是否合计
      ifTotal: {
        default: 1,
      },
      // 合计展示位置
      totalShowType: {
        default: 1,
      },
      // 是否分页
      ifPage: {
        default: 1,
      },
      // 检索条件
      queryArr: {
        default: ()=>([]),
      },
      // 列信息
      tableLabelArr: {
        default: ()=>([]),
      },
      // 分组字段值
      groupKpiCode: {
        default: ''
      },
      // 分组字段值
      groupKpiValue: {
        default: ''
      },
      // table和charts的布局关系
      reportLayer: {
        default: 'report-layer-column'
      },
      // chart接chart的布局关系
      chartLayer: {
        default: 'chart-layer-row'
      },
      // chart的颜色配置
      chartColor: {
        default: ()=>([]),
      },
    },
    data() {
      return {
        isReloadAlive: false,
        extraCondition:[],
        subReport: {
          layoutId: 1,
          colorGroupId:1,
        },
        dialogTableVisible: false,
        searchForm: {
          page: 1,
          pageSize: 10,
        },
        selectedKpis:[],

        // 图表默认配置
        barLineOption: barLineOption,
        pieOption: pieOption,

        // 维表对应值
        kpiColors: kpiColors,

        queryArrObj: {},
        // 聚合条件
        groupKpiCodes: []

      }
    },
    computed: {
      currentGroupKpiCodes: {
        get: function(){
          let {groupKpiCodes} = this
          return groupKpiCodes
        },
      },
      currentOrder: {
        get: function(){
          let {sort, order} = this.searchForm
          return {
            sort: sort || this.queryDefaultSortKpiCode,
            order: order || this.queryDefaultOrder
          }
        },
      },
      weekTime: {
        get: function(){
          return 7*(24*60*60*1000)
        },
      },
      /* 布局 */
      layerClass: {
        get: function () {
          let {layoutId} = this.subReport
          return layerClass[layoutId]
        },
        set: function (val) {}
      },
      /* 表颜色 */
      chartTheme: {
        get: function () {
          let {colorGroupId} = this.subReport
          return echartsThemes[colorGroupId]
        },
        set: function (val) {}
      },
      searchFormTemp: {
        get: function(){
          let {sort, order} = this.currentOrder
          let searchForm = {
            groupKpiCodes: this.currentGroupKpiCodes,
            reportId: this.reportId,
            queryKpis: [],
            sort,
            order,
            page: 1,
            pageSize: 10,
            ifOutsideParam: this.ifOutsideParam,
            ifOutsideParamValue: this.ifOutsideParamValue,
            ifTotal: this.ifTotal,
            totalShowType: this.totalShowType,
            ifPage: this.ifPage,
            groupKpi: {
              kpiCode: this.groupKpiCode,
              value: this.groupKpiValue
            }
          }

          searchForm.queryKpis=this.queryArr.concat(this.extraSearchCoindition)

          return searchForm
        }
      },
      kpiOptions: {
        get: function(){
          let kpiColors=this.kpiColors
          return this.tableLabelArr.map(kpi=>{
            let ext={}
            // let colorOption={depend: 'color',option: kpiColors}
            if(kpi.ifDrillDown && kpi.subreportId){
              Object.assign(ext, {methods: 'drillDown'})
            }
            return Object.assign(ext,{
              prop: kpi.kpiCode,
              ifNumber: kpi.ifNumber,
              title: kpi.rname,
              sort: !!kpi.ifQueryOrderBy,
              kpiColors,
              queryColorId: kpi.queryColorId,
              queryColorLower: kpi.queryColorLower,
              queryColorUpper: kpi.queryColorUpper,
              ifDrillDown: kpi.ifDrillDown,
              ifRelated: kpi.ifRelated,
              subreportId: kpi.subreportId
            })
          })
        }
      },
      tableColumn: {
        get: function(){
          return this.kpiOptions.filter(kpi=>{
            return this.selectedKpis.indexOf(kpi.prop)>=0
          }).map(kpi=>{
            // console.log(kpi)
            if(kpi.ifNumber){
              kpi.formatter=this.formateNumber
            }
            return kpi
          })
        }
      },
    },
    watch:{
      defaultGroupKpis(val){
        if(val && val.length>0){
          let ids = val.map(item=>item.kpiCode)
          this.groupKpiCodes = ids
        }else{
          this.groupKpiCodes = []
        }
      },
      extraSearchCoindition(val){
        this.searchForm=this.searchFormTemp
      },
      reportId(val){
        this.selectedKpis=this.tableLabelArr.map(kpi=>{
          return kpi.kpiCode
        })
        this.getQueryObj()
      },
      queryArr(val) {
        this.getQueryObj()
      },
    },
    created(){
    },
    mounted(){
      this.selectedKpis=this.tableLabelArr.map(kpi=>{
        return kpi.kpiCode
      })

      if(this.defaultGroupKpis && this.defaultGroupKpis.length>0){
        let ids = this.defaultGroupKpis.map(item=>item.kpiCode)
        this.groupKpiCodes = ids
      }else{
        this.groupKpiCodes = []
      }
      this.getQueryObj()
    },
    methods: {
      reload() {
        this.isReloadAlive = false;
        this.$nextTick(function(){
          this.isReloadAlive = true;
        })
      },
      formateNumber(row,col){
        let value=row[col.prop]

        return numberFormateThousand(value)
      },
      formateDateRange(query){
        let arr=[]
        return arr
      },
      getQueryObj(){
        let arr=this.queryArr
        let obj={}
        arr.forEach((current,index)=>{
          current.valueArr=[]
          if(current.ifQueryTime===1){
            // 偏移量
            let {timeDefaultOffset}=current
            // 时间类型，加默认值处理
            if(current.timeTypeId===1 || current.timeTypeId===2){
            //  单日
              let date = GetDateStr((new Date()).getTime(), (-1)*(timeDefaultOffset))
              current.valueArr=[date,date]
            }
            if(current.timeTypeId===3){
              //  单周
              let date = (new Date()).getTime() - this.weekTime*timeDefaultOffset
              current.valueArr = [GetDateStr(date, 0), GetDateStr(date, 7)]
            }
            if(current.timeTypeId===4){
              //  日期范围
              current.valueArr = [GetDateStr((new Date()).getTime(), (-1)*(timeDefaultOffset)), GetDateStr((new Date()).getTime(), 0)]
            }
          }
          obj[index]=current
          // console.log(current)
        })
        this.queryArrObj = obj

        this.getList()
      },

      queryUpdate(index){
        // Vue.set(this.queryArr,index,this.queryArr[index])
      },

      // 获取下钻报表
      getSubReport(row,col){
        // 加载子报表
        let id=col.subreportId
        this.$api.report.view({id: id}).then(res=>{
          if(res.code==1){
            this.subReport=res.data
            this.dialogTableVisible=true
            this.drillDown(row,col)
            this.reload()
          }
        })
      },
      // 下钻
      drillDown(row,col){
        // 获取额外减缩条件
        let {drillDownRelated}=this
        let extraCondition=[]
        let kpi = drillDownRelated.find(item=>{
          return item.kpiCode === col.prop
        })
        if(kpi){
          kpi.kpiDrills.forEach(drill=>{
            let obj={
              ifQuerySearch: 1,
              searchTypeId: 2,
              kpiCode: drill.relatedSubKpiCode,
              value: row[drill.relatedKpiCode],
              timeRelatedSelected: drill.timeRelatedSelected,
              timeRangeOffset: drill.timeRangeOffset
            }
            extraCondition.push(obj)
          })
        }
        this.extraCondition=extraCondition


      },


      loadPie(){
        let _this=this
        /* 合成检索条件 */
        let params = Object.assign({reportType: 2},this.searchForm)
        this.$api.report.getReportData(params)
          .then(res => {
            if (res.code == 1) {
              let  data = res.data.pie
              _this.getPieChart(data)
            }
          })
      },
      loadBarAndLine(){
        let _this=this
        /* 合成检索条件 */
        let params = Object.assign({reportType: 1},this.searchForm)
        this.$api.report.getReportData(params)
          .then(res => {
            if (res.code == 1) {
            let  data = res.data.barOrLine
            _this.getBarLineChart(data)

            }
          })
      },
      getList(){
        this.searchForm=deepCopy(this.searchFormTemp)
        if(this.ifBarAndLine){
          this.loadBarAndLine()
        }
        if(this.ifPie){
          this.loadPie()
        }
      },

      getBarLineChart(data){
        let xAxisColor={
          axisLabel: {
            show: true,
            textStyle: {
              color: '#7f8d9a'
            }
          },
          nameTextStyle:{
            color: '#7f8d9a',
          },
          axisLine:{
            lineStyle:{
              color: '#7f8d9a',
              width: 1
            }
          },
        }
        let yAxisColor={
          axisLabel: {
            show: true,
            textStyle: {
              color: '#7f8d9a'
            },
            formatter: '{value}'
          },
          axisLine:{
            lineStyle:{
              color: '#7f8d9a',
              width: 1
            },
          },
          splitLine:{
            show:true,
            lineStyle:{
              color: '#7f8d9a',
              width: 1
            }
          },
        }
        let xAxis=data.xAxis
        let yAxis=data.yAxis
        let series=data.series

        series.forEach(item=>{
          if(item.unit){
            item.name=item.name+'('+item.unit+')'
          }
        })

        yAxis.forEach((item)=>{
          Object.assign(item,yAxisColor)
        })


        Object.assign(xAxis,xAxisColor)

        let barWidth=20

        let barSeries=series.filter(item=>{
          return item.type==="bar"
        })

        let barNum=barSeries.length

        if(barNum>40){
          barWidth=800/barNum
        }

        if(barWidth<5){
          barWidth=5
        }

        series.map((item)=>{
          return Object.assign(item,{barWidth})
        })



        let option=this.barLineOption
        option.color=this.chartColor
        option.xAxis=[xAxis]
        option.yAxis=yAxis
        option.series=series


        // console.log(JSON.stringify(option))

        let myChart = this.$echarts.init(document.getElementById('lineChart_'+this.groupIndex))

        // 绘制图表
        myChart.setOption(option,true)

        this.$nextTick(function () {
          myChart.resize()
        })
      },
      getPieChart(data){

        let option=this.pieOption
        option.color=this.chartColor
        option.series.data=data.series


        // console.log(JSON.stringify(option))

        let myChart = this.$echarts.init(document.getElementById('pieChart_'+this.groupIndex))

        // 绘制图表
        myChart.setOption(option,true)

        this.$nextTick(function () {
          myChart.resize()
        })
      },


      download(){
        let params={
          ...this.searchForm,
          reportType: 0
        }
        this.fileDownLoad(params)
      },

      fileDownLoad(params){
        function createObjectURL(object) {
          return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
        }

        var xhr = new XMLHttpRequest();
        xhr.open('post',Axios.defaults.baseURL+'/rpm/report/downloadReportFile',true);
        xhr.setRequestHeader("token", localStorage.getItem('token'));
        xhr.setRequestHeader("Content-Type","application/json");
        xhr.responseType = 'blob';
        xhr.onload = function (e) {
          if (this.status == 200) {
            var blob = this.response;
            var filename = "report.csv";
            // console.log(this.response)
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, filename);
            } else {
              var a = document.createElement('a');
              var url = createObjectURL(blob);
              a.href = url;
              a.download = filename;
              document.body.appendChild(a);
              a.click();
              window.URL.revokeObjectURL(url);
            }

          }
        };
        xhr.send(JSON.stringify(params));
      }
    },
  }
</script>
