import routerUserMenu from '@/mixins/router-user-menu'
import breadcrumbComponent from '@/components/breadcrumb.vue'

import simpleSelectTree from '@/components/simple-select-tree.vue'

import {toTree, familyTree} from '@/utils/util'

import {echartsThemes} from '../echarts-color-themes'
import {kpiColors} from '../kpi-color'
import {pieOptionData, lineAndBarOptionData} from '../echarts-demo'

import {layerClass} from '../layer-class'

import Sortable from 'sortablejs'
import draggable from 'vuedraggable'
/**
 * 页面组件设置
 *
 *  version = "1.0.0";
 *  author = "徐飞";
 *  email = "xu.fei@data-u.com";
 * */
export default {
  name: 'detail',
  components:{ breadcrumbComponent, simpleSelectTree, draggable},
  mixins: [routerUserMenu],
  data () {
    return {
      isInit: true,
      sonReportOptions:[],
      kpiColorPopover: false,
      kpiColors: kpiColors,
      echartsThemes: echartsThemes,
      /* 树过滤条件 */
      filterText: '',

      /* 接口返回的菜单树 */
      menu: [],
      /* 接口返回的主体树 */
      topic: [],
      /* 级联组件配置 */
      defaultCascaderProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      /* 树组件配置 */
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      /* 报表实际阶段 */
      reportStep: 0,
      /* 页面当前显示阶段 */
      currentStep: 1,

      /* 报表类型 */
      reportTypeOptions: [],
      /* 统计图类型 */
      eChartsOptions: [],
      /* 统计图xy轴 */
      eChartsXYOptions: [],
      /* 统计图左右 */
      eChartsLROptions: [],
      /* 柱/折 */
      eChartsTypeOptions: [],
      /* 统计图配色方案 */
      eChartsColorOptions: [],
      /* 展示系统 */
      displaySystemOptions: [],
      /* 报表布局 */
      eChartsLayerOptions: [],
      /* 搜索条件类型 */
      searchTypeOptions: [],
      /* 时间条件类型 */
      dateRangeOptions: [],
      /* 展示方式 */
      displayModeOptions: [],
      /* 报表层级 */
      reportLevelOptions:[],

      /* kpi标记颜色 */
      kpiColorOptions: [],
      /* 合计展示 */
      totalShowTypeOptions: [],

      /* 接口返回的kpi */
      resTags: [],
      /* kpi过滤条件 */
      filterKPIText: '',

      /* 报表对象 */
      formInfoStep1: {
        /*
        * 第一步
        * */
        /* 报表id */
        id: '',
        /* 报表名 */
        reportName: '',
        /* 展示系统、所属项目 */
        displaySystem: 1,
        /* 展示类型、展示方式 */
        showType: 1,
        /* 报表层级 */
        reportLevel: 1,
        /* 所属菜单 */
        menuCode: '',
      },
      /* 报表对象 */
      formInfoStep2: {
        /*
        * 第二步
        * */
        /* 报表id */
        id: '',
        /* kpi 列表 */
        kpis: []
      },
      /* 报表对象 */
      formInfoStep3: {
        /*
        * 第三步
        * */
        /* 报表id */
        id: '',
        ifOutsideParam: 0,
        // 是否使用可操作聚合,1使用 0不使用
        useOperableGroup: 0,
        // 使用可操作聚合字段kpiId列表
        operableGroupKpis: null,
        reportOutsideParams: [{
          paramDesc: '',
          paramKey: '',
          paramType: 1
        }],
        /* 检索条件 */
        queryKpis: [
          {
            kpiId: '',
            ifQuerySearch: '',
            ifQueryTime: '',
            searchTypeId: '',
            timeTypeId: '',
            timeDefaultOffset: 0
          }
        ],
        colorKpis: [
          {
            kpiId: '',
            queryColorId: 1,
            queryColorLower: '',
            queryColorUpper: '',
            kpiPop: false
          }
        ],
        /* 聚合 */
        groupKpis: [],
        /* 排序 */
        orderKpis: [],
        queryDefaultSortKpi: '',
        queryDefaultOrder: 'desc',
        totalKpis: [],
        /* 是否分页 */
        ifPage: 1,
        /* 是否合计 */
        ifTotal: 1,
        /* 合计展示位置 */
        totalShowType: 1
      },
      /* 报表对象 */
      formInfoStep4: {
        /*
        * 第四步
        * */
        /* 报表id */
        id: '',
        /* 是否下钻 */
        ifDrillDown: 0,
        /* 下钻kpi集合 */
        drillDowns: [
          {
            kpiId: '',
            subreportId: '',

            // 新增参数
            ifRelated: 0,

            // 这里存储子表kpi下拉项选项
            sonReportKpiOptions: [],

            kpiDrills: [
              {
                relatedKpiCode: '',
                relatedKpiId: '',
                relatedSubKpiCode: '',
                relatedSubKpiId: '',
                timeRelatedSelected: 1,
                timeRangeOffset: 0,
              }
            ],
          },
        ],
        ifRelated: 0,
        relatedKpis: []
      },
      /* 报表对象 */
      formInfoStep5: {
        /*
        * 第五步
        * */
        /* 报表id */
        id: '',
        /* 布局：上图下表或上表下图 */
        layoutId: 1,
        /* 颜色组 */
        colorGroupId: 1,
        /* 分组字段 */
        groupKpi: '',

        /* 分组字段 */
        ifPie: 0,
        /* 分组字段 */
        ifBarAndLine: 0,
        /* 分组字段 */
        pieKpiIds: [],
        /* 分组字段 */
        barAndLineCharts: [{
          kpiId: '',
          axis: 1,
          position: '',
          graph: ''
        },{
          kpiId: '',
          axis: 2,
          position: 1,
          graph: 1
        }],
      },
      formInfoStep6:{
        id: ''
      },
      /* 报表查询结果 */
      /* 查询报表接口返回格式 */
      reportDetailRes:  {},

      /* 步骤二修改标签名临时存储 */
      temp:'',
      tempId:-1,

      // 组件id（修改和查看）
      id: '',
      // 页面打开类型，0：新建，1：查看，2：修改
      dialogState: 0,

      /* 步骤六table假数据 */
      tableData: [{},{},{}],
      tableLabel:[
        {
          prop: '1',
          title: '字段名1',
        },
        {
          prop: '12',
          title: '字段名2',
        },
        {
          prop: '13',
          title: '字段名2',
        }
      ],
    }
  },
  watch: {
    currentStep(val) {
      if(val===6){
        this.$nextTick(()=>{
          this.initChart()
        })
      }
    },
    /* KPI左侧分类监听树过滤条件 */
    filterText(val) {
      this.$refs.topicTree.filter(val);
    },

    /* 监听报表信息的变化，更新step1-5的对象回显信息 */
    reportDetailRes(report) {
      /* 解构返回结果 */
      let {currentStep,id,ifFinish,ifOutsideParam,reportOutsideParams,queryDefaultSortKpi,queryDefaultOrder,totalKpis,drillDowns,
        reportName,displaySystem,showType,reportLevel,menuCode,
        kpis,
        ifPage,ifTotal,totalShowType,useOperableGroup,operableGroupKpis,
        ifDrillDown,ifRelated,
        layoutId,colorGroupId,chart,ifBarAndLine,ifPie,pieKpiIds,barAndLineCharts
        }=report


      if(drillDowns === null){
        drillDowns = []
      }
      if(totalKpis === null){
        totalKpis = []
      }

      this.id=id
      this.getMenuTree()
      /* 更新当前步骤状态 */
      if(this.isInit){
        this.currentStep=currentStep===6?1:currentStep
        if(this.$refs['formInfoStep'+this.currentStep]){
          this.$nextTick(()=>{
            this.$refs['formInfoStep'+this.currentStep].clearValidate()
          })
        }
      }
      this.reportStep=currentStep

      /* 首先判断这个对象存储的是几个阶段的数据，再按照阶段处理formInfoStep1-5 */
      if(currentStep>=1){
        /* 这里更新formInfoStep1 */
        Object.assign(this.formInfoStep1,{
          id,reportName,displaySystem,showType,reportLevel,menuCode
        })
      }
      if(currentStep>=2){
        /* 这里更新formInfoStep2 */
        Object.assign(this.formInfoStep2,{
          id,
          kpis: kpis.map(kpi=>({kpiId:kpi.kpiId,rname:kpi.rname,ifTime:kpi.ifTime,ifNumber:kpi.ifNumber, kpiCode: kpi.kpiCode}))
        })

        /* 预览table表头 */
        let label=kpis.map(kpi=>{
          return {
            prop: kpi.kpiId,
            title: kpi.rname
          }
        })
        this.tableLabel=label
      }
      if(currentStep>=3){
        let groupKpis=kpis.filter(kpi=>{
          return kpi.ifQueryGroupBy===1
        })

        groupKpis.sort((a,b)=>{
          return a.queryGroupBySort>b.queryGroupBySort
        })

        groupKpis=groupKpis.map(kpi=>kpi.kpiId)

        let orderKpis=kpis.filter(kpi=>{
          return kpi.ifQueryOrderBy===1
        }).map(kpi=>kpi.kpiId)


        if(!reportOutsideParams || reportOutsideParams.length === 0){
          reportOutsideParams = [{
            paramDesc: '',
            paramKey: '',
            paramType: 1,
          }]
        }

        if(operableGroupKpis!== null && operableGroupKpis.length === 0){
          operableGroupKpis = null
        }
        /* 这里更新formInfoStep3 */
        Object.assign(this.formInfoStep3,{
          id,ifPage,ifTotal,groupKpis, orderKpis, totalShowType,ifOutsideParam,reportOutsideParams,queryDefaultSortKpi,queryDefaultOrder,totalKpis,useOperableGroup,operableGroupKpis,
        })
        let queryKpis=kpis.filter(kpi=>{
          return kpi.ifQuerySearch === 1 || kpi.ifQueryTime === 1
        }).map(kpi=>{
          return {
            kpiId: kpi.kpiId,
            ifTime: kpi.ifTime,
            ifQuerySearch: kpi.ifQuerySearch,
            ifQueryTime: kpi.ifQueryTime,
            searchTypeId: kpi.searchTypeId,
            timeTypeId: kpi.timeTypeId,
            timeDefaultOffset: kpi.timeDefaultOffset,
            rname: kpi.rname,
            queryGroupBySort: kpi.queryGroupBySort,
            querySearchSort: kpi.querySearchSort
          }
        }).sort((a,b)=>{
          return a.querySearchSort>b.querySearchSort ? -1 : 1
        })
        queryKpis.sort((a,b)=>{
          return a.querySearchSort>b.querySearchSort
        })
        if(queryKpis.length>0){
          Object.assign(this.formInfoStep3,{
            queryKpis
          })
        }

        let colorKpis=kpis.filter(kpi=>{
          return kpi.ifQueryColor===1
        }).map(kpi=>{
          return {
            kpiPop: false,
            kpiId: kpi.kpiId,
            queryColorId: kpi.queryColorId,
            queryColorLower: kpi.queryColorLower,
            queryColorUpper: kpi.queryColorUpper
          }
        })
        if(colorKpis.length>0){
          Object.assign(this.formInfoStep3,{
            colorKpis
          })
        }else{
          Object.assign(this.formInfoStep3,{
            colorKpis: [{
                kpiId: '',
                queryColorId: 1,
                queryColorLower: '',
                queryColorUpper: '',
                kpiPop: false
              }]
          })
        }
      }

      if(currentStep>=4){
        let relatedKpis=kpis.filter(kpi=>{
          return kpi.ifRelated === 1
        }).map(kpi=>{
          return kpi.kpiId})

        /* 这里更新formInfoStep4 */
        Object.assign(this.formInfoStep4,{
          id,
          ifDrillDown,
          ifRelated,
          relatedKpis
        })
        drillDowns=drillDowns.map(kpi=>{
          if(kpi.kpiDrills.length === 0){
            kpi.kpiDrills = [
              {
                relatedKpiCode: '',
                relatedKpiId: '',
                relatedSubKpiCode: '',
                relatedSubKpiId: '',
                timeRelatedSelected: 1,
                timeRangeOffset: 0,
              }
            ]
          }
          return {
            kpiId: kpi.kpiId,
            subreportId: kpi.subreportId,
            ifRelated: kpi.ifRelated,
            kpiDrills: kpi.kpiDrills
          }
        })
        drillDowns.forEach(kpi=>{
          this.loadSubKpis(kpi,true)
          this.onRelatedKpiChange(kpi)
        })
        if(drillDowns.length>0){
          Object.assign(this.formInfoStep4,{
            drillDowns
          })
        }


      }
      if(currentStep>=5){
        /* 这里更新formInfoStep5 */
        Object.assign(this.formInfoStep5,{
          id,
          layoutId,colorGroupId,ifBarAndLine,ifPie
        })

        if(pieKpiIds && pieKpiIds.length>0){
          Object.assign(this.formInfoStep5,{
            pieKpiIds
          })
        }

        if(barAndLineCharts && barAndLineCharts.length>0){
          Object.assign(this.formInfoStep5,{
            barAndLineCharts
          })
        }

        let groupKpi=kpis.filter(kpi=>{
          return kpi.ifGroupShow === 1
        })
        if(groupKpi.length>0){
          Object.assign(this.formInfoStep5,{
            groupKpi:groupKpi[0].kpiId
          })
        }
      }

      this.$nextTick(()=>{
        if(currentStep && this.$refs['formInfoStep'+currentStep]){
          this.$refs['formInfoStep'+currentStep].clearValidate()
        }
      })
    }
  },

  computed: {
    operableGroupKpis: {
      get: function () {
        let {kpis} = this.formInfoStep2
        let {operableGroupKpis} = this.formInfoStep3
        let arr=[]
        if(operableGroupKpis){
          arr = kpis.filter(item=>{
            return operableGroupKpis.indexOf(item.kpiId) >= 0
          })
        }
        return arr
      },
      set: function (val) {}
    },
    step3DefaultSortKpiOptions: {
      get: function () {
        let {kpis} = this.formInfoStep2
        let {orderKpis} = this.formInfoStep3
        return kpis.filter(item=>{
          return orderKpis.indexOf(item.kpiId) >= 0
        })
      },
      set: function (val) {}
    },
    /* 布局 */
    layerClass: {
      get: function () {
        let {layoutId} = this.formInfoStep5
        return layerClass[layoutId]
      },
      set: function (val) {}
    },
    totalKpis: {
      get: function(){
        let kpiIds=this.formInfoStep3.totalKpis
        let kpis=this.formInfoStep2.kpis
        let selectedKpis=[]

        kpiIds.forEach(current=>{
          let res=kpis.filter(kpi=>{
            return kpi.kpiId===current
          })
          selectedKpis=selectedKpis.concat(res)
        })
        return selectedKpis
      },
    },
    groupKpis: {
      get: function(){
        let kpiIds=this.formInfoStep3.groupKpis
        let kpis=this.formInfoStep2.kpis
        let selectedKpis=[]

        kpiIds.forEach(current=>{
          let res=kpis.filter(kpi=>{
            return kpi.kpiId===current
          })
          selectedKpis=selectedKpis.concat(res)
        })
        return selectedKpis
      },
    },
    /* 只有数字类型的已选kpi集合 */
    numberKpis: {
      get: function(){
        let kpis=this.formInfoStep2.kpis
        let arr=kpis.filter(kpi=>{
          return kpi.ifNumber == 1
        })
        return arr
      },
    },
    drillDownsIds: {
      get: function(){
        let kpis=this.formInfoStep4.drillDowns
        let arr=kpis.map(kpi=>{
          return kpi.kpiId
        })
        return arr
      },
    },
    colorKpisIds: {
      get: function(){
        let kpis=this.formInfoStep3.colorKpis
        let arr=kpis.map(kpi=>{
          return kpi.kpiId
        })
        return arr
      },
    },
    /* 经过滤的kpi */
    searchTags: {
      // getter
      get: function(){
        let filterKPIText=this.filterKPIText
        let obj=[]

        if(filterKPIText){
          obj=this.resTags.filter(tag=>{
            return tag && tag.name && (tag.name.indexOf(filterKPIText) >= 0)
          })
        }else{
          obj=this.resTags.filter(tag=>{
            return tag && tag.name
          })
        }

        return obj
      },
    },

    /* 这里需要一个显示已选的kpi的id数组，用来禁用已选kpi的二次选中 */
    selectedKPIs:{
      // getter
      get: function(){
        let objs=this.formInfoStep2.kpis
        return objs.map(kpi=>kpi.kpiId)
      },
      // setter
      set: function (newValue) {
      }
    },
    // 组件设置是否只读
    readonly: {
      // getter
      get: function(){
        return (this.dialogState === 1)
      },
      // setter
      set: function (newValue) {
      }
    },

    /* 转换menu菜单树数据格式 */
    menuOptions:{
      get: function(){
        let tree=this.menu
        // 线性数组转成树后渲染
        let defaultProps={
          id: 'menuCode',
          parent_id: 'pcode',
          label: 'menuName'
        }
        let newTree=toTree(tree,'0',defaultProps)
        return newTree
      }
    },

    /* 转换kpi主题树数据格式 */
    topicOptions:{
      get: function(){
        let tree=this.topic
        // 线性数组转成树后渲染
        let defaultProps={
          id: 'code',
          parent_id: 'pcode',
          label: 'name'
        }
        let newTree=toTree(tree,"0",defaultProps)
        return newTree
      }
    }
  },
  mounted () {
    // 初始化
    this.init()
  },
  methods: {
    initChart(){
      let {colorGroupId}=this.formInfoStep5
      let theme=this.echartsThemes[colorGroupId].data

      console.log(this.echartsThemes[colorGroupId])

      let myLineChart = this.$echarts.init(document.getElementById("lineChart"))
      lineAndBarOptionData.color=theme
      // 绘制图表
      myLineChart.setOption(lineAndBarOptionData,true)


      let myPieChart = this.$echarts.init(document.getElementById("pieChart"))
      pieOptionData.color=theme
      // 绘制图表
      myPieChart.setOption(pieOptionData,true)

    },
    test(val){
      console.log(val)
    },
    onOperableGroupKpisChange(){
      this.formInfoStep3.groupKpis = []
    },
    // KPI选择 时间设置
    testQueryKpis(rule, value, callback){
      if(value.ifQueryTime === 1){
        let {timeDefaultOffset} = value
        if(timeDefaultOffset <0){
          callback(new Error('前推时间必须为大于等于0的整数'))
        }else  if(timeDefaultOffset%1 !== 0){
          callback(new Error('前推时间必须为大于等于0的整数'))
        }else{
          callback();
        }
      }else{
        callback();
      }
    },

    testNumber(rule, value, callback){
      let timeRangeOffset = value
      console.log(timeRangeOffset)
      if(timeRangeOffset <0){
        callback(new Error('参数必须为大于等于0的整数'))
      }else  if(timeRangeOffset%1 !== 0){
        callback(new Error('参数必须为大于等于0的整数'))
      }else{
        callback();
      }
    },

    testQueryColorLower(rule, value, callback){
      if(value.queryColorLower!==null&&value.queryColorUpper!==null&&value.queryColorLower!==''&&value.queryColorUpper!==''){
        if(parseFloat(value.queryColorLower)>parseFloat(value.queryColorUpper)){
          callback(new Error('下限不能大于上限'));
        }else{
          callback();
        }
      }else{
        callback();
      }
    },
    testQueryColorUpper(rule, value, callback){
      if(value.queryColorLower!==null&&value.queryColorUpper!==null&&value.queryColorLower!==''&&value.queryColorUpper!==''){
        if(parseFloat(value.queryColorLower)>parseFloat(value.queryColorUpper)){
          callback(new Error('上限不能小于下限'));
        }else{
          callback();
        }
      }else{
        callback();
      }
    },
    seeNextStep(){
      this.isInit=false
      this.getDetail()
      this.currentStep++
    },
    seeLastStep(){
      this.isInit=false
      this.getDetail()
      this.currentStep--
    },
    /* 选择kpi时更新kpi类型 */
    updateQueryKpi(kpi ,val){
      let kpis=this.reportDetailRes.kpis.filter(kpi=>{
       return kpi.kpiId===val
      })

      let target=kpis[0]
      kpi.ifTime=target.ifTime
      kpi.ifQueryTime=target.ifTime
      kpi.ifQuerySearch=target.ifTime==1?0:1

      if(kpi.ifQueryTime===1){
        kpi.timeTypeId=1
        kpi.searchTypeId=0
      }
      if(kpi.ifQuerySearch===1){
        kpi.timeTypeId=0
        kpi.searchTypeId=1
      }
    },
    postStepSuccess(res,next){
      if(res.code=== '1'){
        this.$message.success(res.msg)
        this.reportDetailRes=res.data
        if(next){
          this.seeNextStep()
        }
      }
    },
    nextStep(next){
      let currentStep = this.currentStep
      let params = this['formInfoStep'+currentStep]

      let id=this.reportDetailRes.id||''
      params.id=id
      if(currentStep == 1){
        this.$api.report.saveOne(params).then(res=>{
          console.log(res)
          this.postStepSuccess(res, next)
        })
      }else  if(currentStep == 2){
        this.$api.report.saveTwo(params).then(res=>{
          console.log(res)
          this.postStepSuccess(res, next)
        })
      }else  if(currentStep == 3){
        this.$api.report.saveThree(params).then(res=>{
          console.log(res)
          this.postStepSuccess(res, next)
        })
      }else  if(currentStep == 4){
        params.drillDowns.forEach(kpi=>{
          kpi.kpiDrills.forEach(item=>{
            item.timeRangeOffset = Number(item.timeRangeOffset)
          })
        })
        console.log(params)
        console.log(params)
        console.log(params)
        this.$api.report.saveFour(params).then(res=>{
          console.log(res)
          this.postStepSuccess(res, next)
        })
      }else  if(currentStep == 5){
        this.$api.report.saveFive(params).then(res=>{
          console.log(res)
          this.postStepSuccess(res, next)
        })
      }else  if(currentStep == 6){
        this.$api.report.saveSix(params).then(res=>{
          console.log(res)
          if(res.code=== '1'){
            this.$message.success(res.msg)
            this.reportStep=6
            this.goBack()
          }
        })
      }
    },


    kpiColorSelect(id, kpi){
      kpi.queryColorId=id
      kpi.kpiPop=false
    },
    /* 第五步，删除柱折图kpi */
    delBarAndLineChart(index){
      this.formInfoStep5.barAndLineCharts.splice(index,1)
    },
    /* 第五步，添加柱折图kpi */
    addBarAndLineChart(){
      this.formInfoStep5.barAndLineCharts.push({
        kpiId: '',
        axis: 2,
        position: 1,
        graph: 1
      })
    },
    /* 第四步，删除kpi下钻 */
    delKpiDrillDown(index){
      this.formInfoStep4.drillDowns.splice(index,1)
    },
    /* 第三步，添加kpi下钻 */
    addKpiDrillDown(){
      this.formInfoStep4.drillDowns.push({
        kpiId: '',
        subreportId: '',
        // 新增参数
        ifRelated: 0,

        kpiDrills: [
          {
            relatedKpiCode: '',
            relatedKpiId: '',
            relatedSubKpiCode: '',
            relatedSubKpiId: '',
            timeRelatedSelected: 1,
            timeRangeOffset: 0,
          }
        ],
        // 这里存储下拉项选项
        sonReportKpiOptions: []
        })
    },
    /* 第三步，删除kpi颜色设置 */
    delKpiColor(index){
      this.formInfoStep3.colorKpis.splice(index,1)
    },
    /* 第三步，添加kpi颜色设置 */
    addKpiColor(){
      this.formInfoStep3.colorKpis.push({
        kpiId: '',
        queryColorId: 1,
        queryColorLower: '',
        queryColorUpper: '',
        kpiPop: false
      })
    },
    /* 第三步，清空kpi颜色设置 */
    refreshKpiColor(index){
      this.formInfoStep3.colorKpis.splice(index,1,{
        kpiId: '',
        queryColorId: 1,
        queryColorLower: '',
        queryColorUpper: '',
        kpiPop: false
      })
    },
    /* 第三步，删除字段设置 */
    delReportOutsideParams(index){
      this.formInfoStep3.reportOutsideParams.splice(index,1)
    },
    /* 第三步，添加k字段设置 */
    addReportOutsideParams(){
      this.formInfoStep3.reportOutsideParams.push({
        paramDesc: '',
        paramKey: '',
        paramType: 1
      })
    },
    /* 第三步，清空字段设置 */
    refreshReportOutsideParams(index){
      this.formInfoStep3.reportOutsideParams.splice(index,1,{
        paramDesc: '',
        paramKey: '',
        paramType: 1
      })
    },
    /* 第三步，删除kpi检索设置 */
    delKpiSearch(index){
      this.formInfoStep3.queryKpis.splice(index,1)
    },
    /* 第三步，添加kpi检索设置 */
    addKpiSearch(){
      this.formInfoStep3.queryKpis.push({
        kpiId: '',
        ifQuerySearch: '',
        ifQueryTime: '',
        searchTypeId: '',
        timeTypeId: '',
        timeDefaultOffset: 0,
      })
    },
    /* 第三步，清空kpi颜色设置 */
    refreshKpiSearch(index){
      this.formInfoStep3.queryKpis.splice(index,1,{
        kpiId: '',
        ifQuerySearch: '',
        ifQueryTime: '',
        searchTypeId: '',
        timeTypeId: '',
      })
    },
    getList(){},
    /* kpi全选 */
    selectAllTag(){
      let kpis=this.selectedKPIs
      let tags = this.searchTags.filter(tag=>{
       return kpis.indexOf(tag.id)<0
      }).map(tag=>({
        rname: tag.name,
        kpiId: tag.id}))
      this.formInfoStep2.kpis=this.formInfoStep2.kpis.concat(tags)
    },
    /* 删除已选kpi */
    removeTag(tag,index){
      this.formInfoStep2.kpis.splice(index,1)
    },
    /* 删除已选kpi */
    removeGroupKpi(tag,index){
      this.formInfoStep3.groupKpis.splice(index,1)
    },
    /* 删除已选kpi */
    removeTotalKpi(tag,index){
      this.formInfoStep3.totalKpis.splice(index,1)
    },
    /* 步骤二的点击kpi添加操作 */
    addTag(tag){
      if(this.selectedKPIs.indexOf(tag.id)<0){
        let obj={
          rname: tag.name,
          kpiId: tag.id
        }
        this.formInfoStep2.kpis.push(obj)
      }
    },
    /* 步骤二的点击左侧树，加载右侧kpi */
    searchKPI(data,node){
      let params={
        id: data.data.id
      }
      this.$api.report.listKpiConfigs(params).then(res=>{
        this.resTags=res.data
      })
    },

    /* 步骤二的左侧kpi主题树节点渲染 */
    // 修改节点文本，自定义图标，return内是jsx语法
    renderContent(h, { node, data, store }) {
      if(node.level == 1){
        return (
          <div class='tree-node'>
            <i class={node.level == 1 ? 'el-icon-menu' : (data.children&&data.children.length > 0 ? 'el-icon-datau-hangyeguanli1' : 'el-icon-document')}></i>
            <span>{node.label}</span>
          </div>
        )
      }
      return (
        <div class='tree-node'>
          <i class={node.level == 1 ? 'el-icon-menu' : (data.children&&data.children.length > 0 ? 'el-icon-datau-hangyeguanli1' : 'el-icon-document')}></i>
          <span>{node.label}</span>
        </div>
      )
    },
    /* 获取整个菜单树 */
    getMenuTree(){
      this.$api.menu.getTree({}).then(res=>{
        if(res.code==1){
          this.menu=res.data
        }
      })
    },
    /* 获取整个kpi主题树 */
    getKPITree(){
      this.$api.report.topicForZtree().then(res=>{
        if(res.code==1){
          this.topic=res.data
        }
      })
    },
    /* KPI左侧分类树过滤 */
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /* 获取维表数据 */
    getOptions(){
      /* 报表类型 */
      this.$api.report.listType({id:1}).then(res=>{
        if(res.code==='1'){
          this.reportTypeOptions=res.data
        }
      })
      /* 统计图类型 */
      this.$api.report.listType({id:2}).then(res=>{
        if(res.code==='1'){
          this.eChartsOptions=res.data
        }
      })
      /* 统计图XY轴 */
      this.$api.report.listType({id:9}).then(res=>{
        if(res.code==='1'){
          this.eChartsXYOptions=res.data
        }
      })
      /* 统计图左右 */
      this.$api.report.listType({id:10}).then(res=>{
        if(res.code==='1'){
          this.eChartsLROptions=res.data
        }
      })
      /* 统计图柱/折 */
      this.$api.report.listType({id:13}).then(res=>{
        if(res.code==='1'){
          this.eChartsTypeOptions=res.data
        }
      })
      /* 统计图配色方案 */
      this.$api.report.listType({id:11}).then(res=>{
        if(res.code==='1'){
          this.eChartsColorOptions=res.data
        }
      })
      /* 展示系统 */
      this.$api.report.listType({id:3}).then(res=>{
        if(res.code==='1'){
          this.displaySystemOptions=res.data
        }
      })
      /* 报表布局 */
      this.$api.report.listType({id:4}).then(res=>{
        if(res.code==='1'){
          this.eChartsLayerOptions=res.data
        }
      })
      /* 搜索条件类型 */
      this.$api.report.listType({id:5}).then(res=>{
        if(res.code==='1'){
          this.searchTypeOptions=res.data
        }
      })
      /* 时间条件类型 */
      this.$api.report.listType({id:6}).then(res=>{
        if(res.code==='1'){
          this.dateRangeOptions=res.data
        }
      })
      /* 展示方式 */
      this.$api.report.listType({id:7}).then(res=>{
        if(res.code==='1'){
          this.displayModeOptions=res.data
        }
      })
      /* 报表层级 */
      this.$api.report.listType({id:8}).then(res=>{
        if(res.code==='1'){
          this.reportLevelOptions=res.data
        }
      })

      /* kpi配色方案 */
      this.$api.report.listType({id:12}).then(res=>{
        if(res.code==='1'){
          this.kpiColorOptions=res.data
        }
      })
      /* kpi配色方案 */
      this.$api.report.listType({id:15}).then(res=>{
        if(res.code==='1'){
          this.totalShowTypeOptions=res.data
        }
      })
    },
    /* 点击上方步骤条图标进行切换 */
    switchStep(index){
      if(index<=this.reportStep+1){
        this.currentStep=index
        this.isInit=false
        this.getDetail()
      }
    },

    /* KPI页面。已选修改KPI显示名 */
    tagClick(index){
      this.tempId=index
      this.$nextTick(()=>{
        this.$refs['tag-input'+index][0].focus()
      })
    },

    /* KPI页面保存已选KPI修改后的名 */
    updateTagText(item,e){
      this.tempId=-1
      if(this.temp.trim()){
        item.rname=this.temp;
        this.temp=''
      }
      this.$forceUpdate()
    },

    //  如果有id，则获取id对应的报表信息
    init(){
      // 获取url参数
      let params = this.$route.params
      if(params.hasOwnProperty('id')){
        // 如果有id，则加载组件对象
        this.id = params.id
        this.getDetail()
      }
      // 根据页面参数设置当前页面类型
      this.dialogState = params.id ? 2 : 0
      /* 获取维表选项 */
      this.getOptions()
      /* 获取菜单 */
      this.getMenuTree()
      /* 获取主题 */
      this.getKPITree()
      this.listSonReport()
    },
    listSonReport(){
      this.$api.report.listSonReport().then(res=>{
        if(res.code==1){
          this.sonReportOptions=res.data
        }
      })
    },
    /* 第四步，删除字段设置 */
    delKpiDrillParam(arr,index){
      arr.splice(index,1)
    },
    /* 第四步，添加k字段设置 */
    addKpiDrillParam(arr){
      arr.push({
          relatedKpiCode: '',
          relatedKpiId: '',
          relatedSubKpiCode: '',
          relatedSubKpiId: '',
          timeRelatedSelected: 1,
          timeRangeOffset: 0,
        })
    },
    onSubRelatedKpiChange(kpi,sonReportKpiOptions){
      let {relatedSubKpiId} = kpi
      if(relatedSubKpiId){
        let relatedKpi = sonReportKpiOptions.find(item=>{
          return item.kpiId === relatedSubKpiId
        })
        kpi.relatedSubKpiCode = relatedKpi.kpiCode
      }
    },
    onRelatedKpiChange(kpi){
      let {kpiDrills} = kpi
      kpiDrills.forEach(current=>{
        let {relatedKpiId} = current
        if(relatedKpiId){
          let relatedKpi = this.formInfoStep2.kpis.find(item=>{
            return item.kpiId === relatedKpiId
          })
          current.relatedKpiCode = relatedKpi.kpiCode
          if(relatedKpi.ifTime){
            current.relatedKpiIsTime = 1
          }else{
            current.relatedKpiIsTime = 0
          }
        }
      })
    },
    loadSubKpis(kpi, ifInit){
      let {subreportId} = kpi
      if(!ifInit){
        kpi.relatedSubKpiId = ''
      }
      if(subreportId){
        this.$api.report.getById({id: subreportId}).then(res=>{
          if(res.code==1){
            kpi.sonReportKpiOptions=res.data.kpis
            this.$forceUpdate()
          }
        })
      }else{
        kpi.sonReportKpiOptions=[]
      }
    },
    /*
    * 后面需要根据实际情况优化↓
    * */

    // 获取组件对象
    getDetail(){
      let params = { id: this.id }
      let _this=this
      this.$api.report.getById(params)
        .then(res => {
          if (res.code == 1) {
            if(res.data){
              _this.reportDetailRes=res.data
            }
          }
        })
    },

    // 查看页切换为修改页
    updateProductView(){
      this.dialogState=2
    },

    // 提交保存
    add(next){
      let _this = this
      _this.isInit=false

      /* 单独判断第二步 */
      if(_this.currentStep===2){
        if(this.formInfoStep2.kpis.length===0){
          this.$message.error("KPI不能为空")
          return
        }
      }

      let refForm=this.$refs['formInfoStep'+_this.currentStep]

      if(refForm){
        // 判断组件设置是否通过验证
        refForm.validate((valid) => {
          if (valid) {
            _this.nextStep(next)
          } else {
            return false
          }
        })
      }else{
        _this.nextStep(next)
      }

    },

    // 拖拽中触发，返回拖拽元素id
    getdata (evt) {
      console.log(evt.draggedContext.element.id)
    },

    // 拖拽结束触发，返回拖拽元素
    datadragEnd (evt) {
      console.log('拖动前的索引 :' + evt.oldIndex)
      console.log('拖动后的索引 :' + evt.newIndex)
    },
  }
}
