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 {
      apiOptions: [],
      /* 报表实际阶段 */
      reportStep: 0,
      /* 页面当前显示阶段 */
      currentStep: 1,

      chartTypeOptions: [],
      chartSourceOptions: [],

      /* 报表对象 */
      formInfoStep1: {
        /*
        * 第一步
        * */
        // 图表分类ID ,
        chartClassId: null,
        // 图表名称
        chartName: '',
        // 图表类型.1 柱折图 2 饼型图 3 地图 ,
        chartType: null,
        // 数据来源
        dataSource: 1
      },

      formInfoStep2: {
        /*
        * 第二步
        * */
        /* kpi 列表 */
        kpis: []
      },

      formInfoStep3: {
        /*
        * 第三步
        * */
        /* 颜色组 */
        colorGroupId: 1,

        /* 饼图 */
        pieKpiIds: [],
        /* 柱折混合图 */
        barAndLineCharts: [{
          kpiId: '',
          axis: 1,
          position: '',
          graph: ''
        },{
          kpiId: '',
          axis: 2,
          position: 1,
          graph: 1
        }],
        // 地图颜色
        mapColor: 1,
        // 热力图
        ifThermalMap: false,
        // 散点图
        ifScatterMap: false,
        thermalMapId: '',
        scatterMapId: '',
      },








      isInit: true,
      sonReportOptions:[],
      kpiColorPopover: false,
      kpiColors: kpiColors,
      echartsThemes: echartsThemes,
      /* 树过滤条件 */
      filterText: '',

      /* 接口返回的菜单树 */
      menu: [],
      /* 接口返回的主体树 */
      topic: [],
      /* 级联组件配置 */
      defaultCascaderProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      /* 树组件配置 */
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      /* 报表类型 */
      reportTypeOptions: [],
      /* 统计图类型 */
      eChartsOptions: [],
      /* 统计图xy轴 */
      eChartsXYOptions: [],
      /* 统计图左右 */
      eChartsLROptions: [],
      /* 柱/折 */
      eChartsTypeOptions: [],
      /* 统计图配色方案 */
      eChartsColorOptions: [],
      /* 展示系统 */
      displaySystemOptions: [],
      /* 报表布局 */
      eChartsLayerOptions: [],
      /* 搜索条件类型 */
      searchTypeOptions: [],
      /* 时间条件类型 */
      dateRangeOptions: [],
      /* 展示方式 */
      displayModeOptions: [],
      /* 报表层级 */
      reportLevelOptions:[],

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

      /* 接口返回的kpi */
      resTags: [],
      /* kpi过滤条件 */
      filterKPIText: '',
      /* 报表查询结果 */
      /* 查询报表接口返回格式 */
      reportDetailRes:  {},

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

    }
  },
  watch: {
    // 区分数据来源
    dataSource(val) {
      this.getTree()
    },
    currentStep(val) {
      this.filterText = ''
      this.filterKPIText = ''
      this.resTags = []
    },
    /* KPI左侧分类监听树过滤条件 */
    filterText(val) {
      this.$refs.topicTree.filter(val);
    },

    /* 监听报表信息的变化，更新step1-5的对象回显信息 */
    reportDetailRes(report) {
      /* 解构返回结果 */
      let {chartClassId,chartName,chartType,dataSource,
        kpis,
        colorGroupId,pieKpiIds,barAndLineCharts,mapCharts
      } = report

      /* 这里更新formInfoStep1 */
      Object.assign(this.formInfoStep1,{
        chartClassId,chartName,chartType,dataSource,
      })

      Object.assign(this.formInfoStep2,{
        kpis: kpis.map(kpi=>({kpiId:kpi.kpiId,rname:kpi.rname,ifTime:kpi.ifTime,ifNumber:kpi.ifNumber, kpiCode: kpi.kpiCode}))
      })

      /* 这里更新formInfoStep3 */
      Object.assign(this.formInfoStep3,{
        colorGroupId,
      })

      if(pieKpiIds && pieKpiIds.length>0){
        Object.assign(this.formInfoStep3,{
          pieKpiIds
        })
      }
      if(barAndLineCharts && barAndLineCharts.length>0){
        Object.assign(this.formInfoStep3,{
          barAndLineCharts
        })
      }
      if(mapCharts && mapCharts.length>0){
        //
        // let scatterMap ={
        //   mapType: 1
        // }
        // let thermalMap = {
        //   mapType: 2
        // }
        // let mapCharts=[]
        // if(ifThermalMap){
        //   Object.assign(thermalMap,{mapColor,kpiId: thermalMapId })
        //   mapCharts.push(thermalMap)
        // }
        // if(ifScatterMap){
        //   Object.assign(scatterMap,{mapColor,kpiId: scatterMapId })
        //   mapCharts.push(scatterMap)
        // }
        // formInfoStep3={mapCharts}
        mapCharts.forEach(current=>{
          if(current.mapType === 1){
            Object.assign(this.formInfoStep3,{
              ifScatterMap: true,
              mapColor: current.mapColor,
              scatterMapId: current.kpiId
            })
          }
          if(current.mapType === 2){
            Object.assign(this.formInfoStep3,{
              ifThermalMap: true,
              mapColor: current.mapColor,
              thermalMapId: current.kpiId
            })
          }

        })
      }

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

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

    // activityId
    id: {
      // getter
      get: function () {
        return this.$route.params.id || null
      },
      // setter
      set: function (newValue) {
      }
    },
    isAdd: {
      // getter
      get: function () {
        return !this.$route.params.id
      },
      // setter
      set: function (newValue) {
      }
    },
    isEdit: {
      // getter
      get: function () {
        return !!this.$route.params.id
      },
      // setter
      set: function (newValue) {
      }
    },







    /* 布局 */
    layerClass: {
      get: function () {
        let {layoutId} = this.formInfoStep3
        return layerClass[layoutId]
      },
      set: function (val) {}
    },
    /* 只有数字类型的已选kpi集合 */
    numberKpis: {
      get: function(){
        let kpis=this.formInfoStep2.kpis
        let arr=kpis.filter(kpi=>{
          return kpi.ifNumber == 1
        })
        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) {
      }
    },

    /* 转换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: {
    /* 点击上方步骤条图标进行切换 */
    switchStep(index){
      if(index<=this.reportStep+1){
        if(this.$refs['formInfoStep1']){
          this.$refs['formInfoStep1'].validate(v=>{
            if(v){
              this.currentStep = index
            }
          })
        }else{
          this.currentStep = index
        }
      }
    },

    // 上一步
    lastStep(){
      let {currentStep} = this
      if(this.$refs['formInfoStep1']){
        this.$refs['formInfoStep1'].validate(v=>{
          if(v){
            this.currentStep--
          }
        })
      }else{
        this.currentStep--
      }
    },

    // 下一步
    nextStep(){
      let {currentStep} = this
      if(this.$refs['formInfoStep'+currentStep]){
        this.$refs['formInfoStep'+currentStep].validate(v=>{
          if(v){
            this.currentStep++
            if(this.currentStep>this.reportStep){
              this.reportStep++
            }
          }
        })
      }else{
        this.currentStep++
        if(this.currentStep>this.reportStep){
          this.reportStep++
        }
      }
    },
    getTree(){
      if(this.formInfoStep1.dataSource === 2 ){
        this.getAPITree()
      }else{
        this.getKPITree()
      }
    },
    /* 获取整个api主题树 */
    getAPITree(){
      this.$api.chart.listProjectAndInterfaceTree().then(res=>{
        if(res.code==1){
          this.topic=res.data.map(item=>{
            return Object.assign({code: item.id, pcode: item.pid},item)
          })
        }
      })
    },
    /* 获取整个kpi主题树 */
    getKPITree(){
      this.$api.report.topicForZtree().then(res=>{
        if(res.code==1){
          this.topic=res.data
        }
      })
    },

    /* 步骤二的点击左侧树，加载右侧kpi */
    searchKPI(data,node){
      let params={
        id: data.data.id
      }
      if(this.formInfoStep1.dataSource === 2 ){
        this.$api.chart.listInterfaceOutParams(params).then(res=>{
          this.resTags=res.data.map(item=>{
            return {id: item.paramId, name: item.nodeName}
          })
        })
      }else{
        this.$api.report.listKpiConfigs(params).then(res=>{
          this.resTags=res.data
        })
      }
    },
    onDataSourceChange(){
      this.formInfoStep1.chartType=null
      this.formInfoStep2.kpis=[]
    },

    // 提交保存
    add(){
      let refForm=this.$refs['formInfoStep3']

      if(refForm){
        // 判断组件设置是否通过验证
        refForm.validate((valid) => {
          if (valid) {
            let {colorGroupId, pieKpiIds, barAndLineCharts,mapColor,ifThermalMap,ifScatterMap,thermalMapId,scatterMapId}=this.formInfoStep3
            let formInfoStep3={}
            if(this.formInfoStep1.chartType === 1){
              formInfoStep3={colorGroupId, barAndLineCharts}
            }else if(this.formInfoStep1.chartType === 2){
              formInfoStep3={colorGroupId, pieKpiIds}
            }else{
              if(!ifThermalMap && !ifScatterMap){
                this.$message.error('热力图和散点图至少选择一项')
                return
              }

              let scatterMap ={
                mapType: 1
              }
              let thermalMap = {
                mapType: 2
              }
              let mapCharts=[]
              if(ifThermalMap){
                Object.assign(thermalMap,{mapColor,kpiId: thermalMapId })
                mapCharts.push(thermalMap)
              }
              if(ifScatterMap){
                Object.assign(scatterMap,{mapColor,kpiId: scatterMapId })
                mapCharts.push(scatterMap)
              }
              formInfoStep3={mapCharts}
            }
            let params = Object.assign({},this.formInfoStep1,this.formInfoStep2,formInfoStep3)
            this.$api.chart.save(params).then(res=>{
              if (res.code == 1) {
                this.$message.success(res.msg)
                this.goBack()
              }
            })
          }
        })
      }
    },

    // 提交保存
    update(){
      let refForm=this.$refs['formInfoStep3']

      if(refForm){
        // 判断组件设置是否通过验证
        refForm.validate((valid) => {
          if (valid) {
            let {colorGroupId, pieKpiIds, barAndLineCharts,mapColor,ifThermalMap,ifScatterMap,thermalMapId,scatterMapId}=this.formInfoStep3
            let formInfoStep3={}
            if(this.formInfoStep1.chartType === 1){
              formInfoStep3={colorGroupId, barAndLineCharts}
            }else if(this.formInfoStep1.chartType === 2){
              formInfoStep3={colorGroupId, pieKpiIds}
            }else{
              if(!ifThermalMap && !ifScatterMap){
                this.$message.error('热力图和散点图至少选择一项')
                return
              }

              let scatterMap ={
                mapType: 1
              }
              let thermalMap = {
                mapType: 2
              }
              let mapCharts=[]
              if(ifThermalMap){
                Object.assign(thermalMap,{mapColor,kpiId: thermalMapId })
                mapCharts.push(thermalMap)
              }
              if(ifScatterMap){
                Object.assign(scatterMap,{mapColor,kpiId: scatterMapId })
                mapCharts.push(scatterMap)
              }
              formInfoStep3={mapCharts}
            }
            let params = Object.assign({id:this.id},this.formInfoStep1,this.formInfoStep2,formInfoStep3)
            this.$api.chart.update(params).then(res=>{
              if (res.code == 1) {
                this.$message.success(res.msg)
                this.goBack()
              }
            })
          }
        })
      }
    },

    //  如果有id，则获取id对应的报表信息
    init(){
      /* 获取图表分类菜单 */
      this.getMenuTree()
      // 获取kpi树
      this.getTree()

      if(this.isEdit){
        this.getDetail()
        this.reportStep = 2
        this.currentStep = 3
      }

      /* 获取维表选项 */
      this.getOptions()
    },

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















    initChart(){
      let {colorGroupId}=this.formInfoStep3
      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)
    },

    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()
        }
      }
    },

    /* 第五步，删除柱折图kpi */
    delBarAndLineChart(index){
      this.formInfoStep3.barAndLineCharts.splice(index,1)
    },
    /* 第五步，添加柱折图kpi */
    addBarAndLineChart(){
      this.formInfoStep3.barAndLineCharts.push({
        kpiId: '',
        axis: 2,
        position: 1,
        graph: 1
      })
    },

    /* kpi全选 */
    selectAllTag(){
      let {chartType, dataSource} = this.formInfoStep1
      let kpis=this.selectedKPIs

      if(dataSource === 2 && chartType !== 3){
        // 如果是接口数据源，且不是地图
        // kpi只能来自一个接口
        if(kpis.length>0 && this.searchTags.findIndex(item=>{
          return item.id ===kpis[0]
        })<0){
          // 已选，且不是来自同一个接口
          this.$message.error('饼图和柱折混合图的kpi只能来自同一个接口')
          return
        }
      }

      let tags = this.searchTags.filter(tag=>{
        return kpis.indexOf(tag.id)<0
      }).map(tag=>{
        let ifNumber = tag.hasOwnProperty('ruleType') ? (tag.ruleType ==='number'?1:0) : 1
        return {
          ifNumber,
          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添加操作 */
    addTag(tag){
      let {chartType, dataSource} = this.formInfoStep1
      let kpis=this.selectedKPIs

      if(dataSource === 2 && chartType !== 3){
        // 如果是接口数据源，且不是地图
        // kpi只能来自一个接口
        if(kpis.length>0 && this.searchTags.findIndex(item=>{
          return item.id ===kpis[0]
        })<0){
          // 已选，且不是来自同一个接口
          this.$message.error('饼图和柱折混合图的kpi只能来自同一个接口')
          return
        }
      }

      let ifNumber = tag.hasOwnProperty('ruleType') ? (tag.ruleType ==='number'?1:0) : 1
      if(this.selectedKPIs.indexOf(tag.id)<0){
        let obj={
          rname: tag.name,
          kpiId: tag.id,
          ifNumber
        }
        this.formInfoStep2.kpis.push(obj)
      }
    },

    /* 步骤二的左侧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.chartMenu.getTree({}).then(res=>{
        if(res.code==1){
          this.menu=res.data
        }
      })
    },
    /* KPI左侧分类树过滤 */
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /* 获取维表数据 */
    getOptions(){

      /* 图表类型 */
      this.$api.report.listType({id:17}).then(res=>{
        if(res.code==='1'){
          this.chartTypeOptions=res.data
        }
      })
      /* 图表数据源 */
      this.$api.report.listType({id:16}).then(res=>{
        if(res.code==='1'){
          this.chartSourceOptions=res.data
        }
      })

      /* 报表类型 */
      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
        }
      })
    },
    /* 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()
    },
    // 查看页切换为修改页
    updateProductView(){
      this.dialogState=2
    },


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

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