<template>
  <div class="height_100 custom-analyse">
    <el-container>
      <el-aside width="350px">
        <TabItem :active-item="activeItem" :treeList="treeList" @edit="handleEdit" @delete="handleDelete" @select="handleSelect" @handleAdd3="handleAdd3"></TabItem>
      </el-aside>
      <el-main>
        <el-header style="height:45px !important">
          <template>
            <div class="custom-analyse-options">
                <div>
                    <el-button type="text" size="small" @click="openDrawer(1)">分析栏位</el-button>
                    <el-button type="text" size="small" @click="openDrawer(2)">图形配置</el-button>
                </div>
                <div>
                    <span class="text">专利数量<span class="number">{{ patentNum }} 件</span></span>
                    
                    <el-dropdown size="small">
                        <el-button size="small" type="text">
                        更多菜单<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="handleScreenshot">截图</el-dropdown-item>
                        <el-dropdown-item @click.native="handleAdd1(0)">保存修改</el-dropdown-item>
                        <el-dropdown-item @click.native="handleAdd1(1)">另存为</el-dropdown-item>
                        <el-dropdown-item @click.native="handleExport">导出数据</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </div>
          </template>
        </el-header>
        <el-main class="custom-analyse-chart-img-box">
          <div v-if="showChart">
            <chart ref="chartDom" :width="form.setting.width + form.setting.widthUnit" :height="form.setting.height + form.setting.heightUnit" />
          </div>
        </el-main>
      </el-main>
    </el-container>
    <addAnalyseGroup ref="addAnalyseGroup" :projectId="projectId" :treeList="treeList" @save="getTreeList"></addAnalyseGroup>
    <el-drawer
        :title="title"
        :visible.sync="drawer"
        direction="rtl"
        :before-close="handleClose"
        size="500px">
            <el-container>
                <el-main>
                    <component :is='components'></component> 
                </el-main>
                <el-footer class="footer-common">
                    <el-button @click="handleClose">取 消</el-button>
                    <el-button type="primary" @click="submit" :loading="loadingBtn">确 定</el-button>
                </el-footer>
            </el-container>
            
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import html2canvas from "html2canvas";
import { downLoad, findChildren, getTreeLastChildren, getTreeDataList, downLoadBase64 } from "@/utils";
import { detectionChartType, getFormPermissions, getTreeNameByIds, getXAxisName, getSourceName } from "@/utils/chart";
import { customPage } from "./mixins";
import moment from "moment";
import addAnalyseGroup from './components/dialog/addAnalyseGroup.vue'
import Chart from "./components/Charts/index.vue";
import TabItem from "./components/Tabs/Item";
import TabData from "./components/Tabs/Data";
import TabStyle from "./components/Tabs/Style";
export default {
  components: {
    addAnalyseGroup,
    Chart,
    TabItem,
    TabData,
    TabStyle
  },
  mixins: [customPage],
  props: {},
  data() {
    return {
        enable:[],
        activeItem:[],
        // treeList:[],
        showChart:false,
        title:'',
        drawer:false,
        components:'TabData',
        saveType: 1,
        loadingBtn:false,
        id:null,
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['userinfo']),
    search(){
        var a = this.$route.query.search
        if(a){
            a = JSON.parse(a)
        }
        return a
    },
    projectId(){
        return this.$route.query.projectId
    },
    patentNum(){
        return this.$route.query.patentNum || 0
    },
  },
  created() {},
  mounted() {
    this.getData()
  },
  methods: {
    openDrawer(type){
        var components = {
            1:'tabData',
            2:'tabStyle'
        }
        this.title = type == 1?'数据':'样式配置'
        this.components = components[type]
        this.drawer = true
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },


    reset() {

    },
    // 获取？？？
    async getData() {
        await this.getTreeList()
        if (this.treeList.length === 0 || this.treeList[0].children.length === 0) {
          this.handleAdd()
          this.showChart = false
          this.saveType = 1
          this.openDrawer(1)
        } else {
          this.activeItem = [this.treeList[0].id]
          await this.handleSelect(this.treeList[0].children[0].id)
        }
        this.showPage = true

    },
    handleDelete(value) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const response = await this.$api.delAnalyseGroup({id:value.id})
        this.$message.success('删除成功')
        await this.getTreeList()
        if (this.form.id === value.id) {
          const tree = this.treeList.find(item => item.id === value.parentId)
          if (tree && tree.children.length) {
            await this.handleSelect(tree.children[tree.children.length - 1].id)
          } else {
            this.handleAdd()
          }
        }
      })
    },
    // 获取需要进行的每一个分析项
    async getTreeList() {
      this.loading = true
      const response = await this.$api.queryAnalyseGroup({ projectId: this.projectId })
      // 获取到的数据存
      this.$store.commit('SET_CHART_TREE', response.data)
      this.setChildren(this.treeList, 'isDisabled')
      this.loading = false
    },
    handleClose() {
      this.drawer = false
    },
    setChildren(arr, key) {
      arr.forEach(item => {
        if (item.children && item.children.length) {
          this.setChildren(item.children, key)
        } else {
          this.$set(item, key, item.type === 1)
        }
      })
    },
    refreshChart() {
      this.$nextTick(() => {
        let chartDom = this.$refs.chartDom
        if (chartDom) {
          chartDom.refreshChart()
        }
      })
    },
    onChange() {
      if (this.saveType || !this.form2.id) {
        this.form2.name = getSourceName(this.form.schema.x.field, this.form.schema.x.expand, this.form.schema.x.num)
        const tree = this.treeList.find(item => item.id === this.form2.parentId)
        if (tree) {
          this.form2.sort = tree.children.length + 1
        }
      } else {
        this.form2.name = this.tempForm.name
        this.form2.sort = this.tempForm.sort
      }
    },
    handleAdd3() {
      var form = {
            type:1,
            permissions: 2,
            parentId: 0,
            sort: this.treeList.length + 1,
            name: '',
        }
        var title = '添加组'
        this.$refs.addAnalyseGroup.open(title,form)
    },
    async handleScreenshot() {
      const canvas = await html2canvas(this.$refs.chartDom.$el)
      const base64 = canvas.toDataURL('image/jpg')
      downLoadBase64(base64, '图片.png')
    },
    async handleAdd1(saveType) {
      this.saveType = saveType
    //   this.onChange()
      var title = '保存自定义分析'
      let data = {}
        if(this.saveType == 1){

        }else{
            data.id = this.id
        }
      if (this.id && this.saveType == 0) {
        const response = await this.$api.queryAnalyseDetail({id:this.id})
        data = response.data
      }
      var form2 = {
        ...data,
        type:2,
        // setting: this.form.setting,
        // schema: this.form.schema,
        // source: this.form.source,
        projectId: this.projectId
      }
      form2.setting = this.form.setting
      form2.schema = this.form.schema
      form2.source = this.form.source
      this.$refs.addAnalyseGroup.open(title,form2)
    },
    handleAdd() {
      let table = []
      for (let i = 0; i < 10; i++) {
        table.push({
          min: 0,
          max: 0,
          color: null
        })
      }
      let form = {
        search:this.search,
        setting: {
          type: 1,
          showType: 0,
          tableType: 0,
          theme: "customed",
          titleSize: 14,
          dataSize: 14,
          axisSize: 14,
          dataLabel: false,
          dataLabel2: false,
          dataLabel3: false,
          title1Dir: 0,
          title1: "",
          title2: "",
          dataPosition: "top",
          fontFamily: "sans-serif",
          fontFamily2: "sans-serif",
          fontFamily3: "sans-serif",
          fontFamily4: "sans-serif",
          fontWeight: false,
          fontWeight2: false,
          nameLocation: "end",
          nameLocation2: "end",
          width: "100",
          height: "650",
          widthUnit: "%",
          heightUnit: "px",
          splitLine: false,
          splitLine2: false,
          legend: true,
          gridTop: "10",
          gridLeft: "10",
          gridBottom: "10",
          gridRight: "10",
          labelColor: "#000000",
          legendColor: "#000000",
          legendLocation: "top",
          legendFontSize: "13",
          fontSize: "13",
          fontSize2: "13",
          fontColor: "#000000",
          fontColor2: "#000000",
          show: true,
          show2: true,
          interval: true,
          interval2: true,
          rotate: "0",
          rotate2: "0",
          paddingTop: 10,
          paddingBottom: 10,
          paddingRight: 10,
          paddingLeft: 10,
          paddingTop2: 0,
          paddingLeft2: 0,
          paddingBottom2: 0,
          paddingRight2: 0,
          type2: "scroll",
          barWidth: "",
          scatterSize: "0",
          config: {
            color: [],
            line: {
              name: "",
              first: "",
              second: "",
              operator: 0,
              enable: false
            },
            table: table
          }
        },
        schema: {
          x: {
            num: 10,
            // field:'PA'
          },
          y: {
            num: 10
          },
        },
        source: {
          x: [],
          y: []
        },
      }
      this.$store.commit('SET_CHART_FORM', form)
    },
    handleEdit(value,type) {
      var title = '编辑组'
      var form = { ...value }
      form.type = type
      this.$refs.addAnalyseGroup.open(title,form)
    },
    getDataCountParams() {
      let source = {
        x: [],
        y: [],
      }
      let schema = {
        x: {},
        y: {}
      }
      let merge = {
        x: 0,
        y: 0
      }
      Object.keys(source).forEach(dimension => {
        if (this.form.schema[dimension].type === 6) {
          if (this.form.setting.type === 20) {
            source[dimension] = this.getTreeAllNode(dimension)
            merge[dimension] = 1
          } else if (this.form.setting.type === 30) {
            source[dimension] = this.getTreeLastChildren(dimension)
          } else {
            source[dimension] = this.getPatentTreeChildren(dimension)
            merge[dimension] = 1
          }
        } else {
          source[dimension] = this.form.source[dimension].filter(item => item.selected)
        }
      })
      Object.keys(schema).forEach(dimension => {
        schema[dimension] = {
          expand: this.form.schema[dimension].expand || 0,
          field: this.form.schema[dimension].field || 0,
          num: this.form.schema[dimension].num,
          type: this.form.schema[dimension].type,
          ptype: this.form.schema[dimension].ptype,
          merge: merge[dimension]
        }
      })
      return { source, schema }
    },
    async getDataCount() {
      if (this.reloadData) {
        var data = {}
        var sign = false
        var count = []
        var dimensions = []
        console.log(this.form)
        if(this.form.schema.x.field && this.form.schema.y.field){
            sign = true
            dimensions = ['x','y']
        }else{
            sign = false
            dimensions = ['x']
            
        }
        if (!this.form.setting.type) {
            if(sign){
               this.form.setting.type = 2 
            }else{
                this.form.setting.type = 1
            }
        }else{
            var chartType = this.$constants.chartType.find(item=>{
                return item.value == this.form.setting.type
            }).type
            if(sign && chartType == 1){
                this.form.setting.type = 2 
            }else if(!sign && chartType == 2){
                this.form.setting.type = 1
            }
        }
        dimensions.forEach(dimension=>{
            var form = this.form
            var obj = form.schema[dimension]
            if(obj.filedKind == 0){
                count.push(
                    {
                        field:'field',
                        fieldId:form.schema[dimension].field,
                        topN: form.schema[dimension].num,
                        values:this.selected[dimension]
                    }
                )
            }else if(form.schema[dimension].type == 'DateTime'){
                count.push(
                    {
                        field:form.schema[dimension].field,
                        topN: form.schema[dimension].num,
                        format:form.schema[dimension].expand,
                        values:this.selected[dimension]
                    }
                )
            }else{
                if(['classify'].includes(form.schema[dimension].groupBy)){
                    count.push(
                    {
                        field:form.schema[dimension].expand,
                        topN: form.schema[dimension].num,
                        values:this.selected[dimension]
                    }
                    )
                }else{
                    count.push(
                    {
                        field:form.schema[dimension].field,
                        topN: form.schema[dimension].num,
                        values:this.selected[dimension]
                    }
                    )
                }
                
            }
        })
        
        var params = {
            ...this.form.search,
            countVOS:count
        }
        try{
            const response = await this.$api.esCountAnalysis(params)
            if(sign){
                var res = Object.keys(response.data.analyseMap)
                for(var i = 0;i<res.length;i++){
                    // var x = this.form.source.x[i]
                    // data[x.name] = {}
                    // for(var j = 0;j<this.form.source.y.length;j++){
                    //     data[x.name][this.form.source.y[j].name] = this.form.source.y[j].number
                    // }
                    var analyseMapData = response.data.analyseMap[res[i]]
                    var obj = {}
                    for(var j =0 ;j<analyseMapData.length;j++){
                        obj[analyseMapData[j].name] = analyseMapData[j].number
                    }
                    data[res[i]] = obj
                }
            }else{
                for(var i = 0;i<response.data.detailDTOS.length;i++){
                    data[response.data.detailDTOS[i].name] = response.data.detailDTOS[i].number
                }
            }
            
        } catch (e) {
            data = []
        }
        this.$store.commit('SET_DATA_COUNT', data)
        this.refreshChart()
        this.$store.commit('SET_RELOAD_DATA', false)
        this.showChart = true
      }
    },
    getTreeAllNode(dimension) {
      const tree = getTreeDataList(this.form.source[dimension], [])
      return tree.map(item => { return { id : item.id } })
    },
    getTreeLastChildren(dimension) {
      const tree = getTreeDataList(this.form.source[dimension], [])
      const data = tree.filter(item => this.treeKey[dimension].indexOf(item.id) !== -1)
      let arr = data.filter(item =>  !item.children || !item.children.length)
      data.map(item => arr.push(...getTreeLastChildren(item.children || [], [])))
      return arr.map(item => { return { id : item.id } })
    },
    getPatentTreeChildren(dimension) {
      const tree = getTreeDataList(this.form.source[dimension], [])
      const selected = this.treeKey[dimension].map(item => item)
      let arr = []
      selected.map(item => {
        const node = tree.find(t => t.id === item)
        arr.push(node)
        arr.push(...getTreeLastChildren(node.children || [], []))
      })
      return arr.map(item => { return { id : item.id } })
    },
    getTreeNodeName(node, tree) {
      const path = node.path.split('/').map(p => parseInt(p, 0))
      let name = []
      path.map(item => {
        const n = tree.find(x => x.id === item)
        if (n) {
          name.push(n.name)
        }
      })
      return name.join('/')
    },
    getExportParams() { 
      const xAxis = getXAxisName(this.patentField, this.form.schema.x.field, this.form.schema.x.expand)
      let type = this.form.schema.y.field ? 2 : 1
      type = this.form.setting.type === 21 ? 3 : type
      let count = JSON.parse(JSON.stringify(this.count))
      const xt = this.form.schema.x.type === 6
      const yt = this.form.schema.y.type === 6
      const xs = getTreeDataList(this.form.source.x, [])
      const ys = getTreeDataList(this.form.source.y, [])
      if (xt && !yt) {
        for (let key in count) {
          const xn = xs.find(item => item.id === parseInt(key))
          const name = this.getTreeNodeName(xn, xs)
          if (xn) {
            count[name] = count[key]
            delete count[key]
          }
        }
      }
      if (xt && yt) {
        for (let xk in count) {
          const xn = xs.find(item => item.id === parseInt(xk))
          const xa = this.getTreeNodeName(xn, xs)
          let data = {}
          for (let yk in count[xk]) {
            const yn = ys.find(item => item.id === parseInt(yk))
            const ya = this.getTreeNodeName(yn, ys)
            if (yn) {
              data[ya] = count[xk][yk]
            }
          }
          if (xn) {
            count[xa] = data
            delete count[xk]
          }
        }
      }
      if (!xt && yt) {
        for (let key in count) {
          let data = {}
          for (let y in count[key]) {
            const yn = ys.find(item => item.id === parseInt(y))
            const ya = this.getTreeNodeName(yn, ys)
            if (yn) {
              data[ya] = count[key][y]
              delete count[y]
            }
          }
          count[key] = data
        }
      }
      return { count, type, xAxis }
    },
    async handleExport() {
        if(!this.form.schema.x.field && !this.form.schema.y.field){
            this.$message.error('请先添加数据')
            return false
        }
        var data = Object.keys(this.count)
        var head = ''
        var body = ''
        if(this.form.schema.x.field && this.form.schema.y.field){
            head = `<td>${this.form.schema.x.name}</td>`
            for(var i = 0;i<this.selected.y.length;i++){
                head = head + `<td>${this.selected.y[i]}</td>`
            }
            for(var i = 0;i<data.length;i++){
                body = body + `<tr><td>${data[i]}</td>`
                for(var j = 0;j<this.selected.y.length;j++){
                    body = body + `<td>${this.count[data[i]][this.selected.y[j]]}</td>`
                }
                body = body + '</tr>'
            }
        }else{
            head = `<td>${this.form.schema.x.name}</td><td>数量</td>`
            for(var i = 0;i<data.length;i++){
                body = body + `<tr><td>${data[i]}</td><td>${this.count[data[i]]}</td></tr>`
            }
        }
        if(!head && !body){
            this.$message.error('导出失败，请重试')
            return false
        }
        // return false
        // Worksheet名
        const worksheet = 'Sheet1'
        const uri = 'data:application/vnd.ms-excel;base64,'

        // 下载的表格模板数据
        const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
          xmlns:x="urn:schemas-microsoft-com:office:excel"
          xmlns="http://www.w3.org/TR/REC-html40">
          <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
          <x:Name>${worksheet}</x:Name>
          <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
          </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
          </head><body><table><tr>${head}</tr>${body}</table></body></html>`
        // 下载模板
        let link = document.createElement('a')
        link.setAttribute('href', uri + window.btoa(unescape(encodeURIComponent(template))))
        link.setAttribute('download', moment().format('YYYYMMDDHHmmss') + '.xls')
        link.click()
        link = null
    },
    resetChartType() {
      this.form.setting.type = null
      this.$store.dispatch('resetSettingColor')
    },
    async submit() {
      if (!this.form.schema.x.field) {
        this.$message.error('请选择一维数据')
        return false
      }else{
        if(this.form.source.x.length == 0){
          this.$message.error('一维数据为空')
          return false
        }
      }
      if(this.form.schema.y.field){
        if(this.form.source.y.length == 0){
          this.$message.error('二维数据为空')
          return false
        }
      }
      const chartType = this.$constants.chartType.find(c => c.value === this.form.setting.type)
      const { op, cg } = detectionChartType(chartType || {}, this.form)
      if (op && cg) {
        this.resetChartType()
      }
      
      this.getDataCount()
      this.refreshChart()
      this.showChart = true
      this.handleClose()
    },
    async handleSelect(key) {
        this.id = key
      let source = {
        x: [],
        y: []
      }
      this.$store.commit('SET_RELOAD_DATA', true)
      this.activeName = '1'
      this.loading = true
      const response = await this.$api.queryAnalyseDetail({id:key})
      this.$store.commit('SET_CHART_FORM', JSON.parse(JSON.stringify(response.data)))
      this.form.search = this.search
      if (this.enable.indexOf(this.form.setting.type) === -1) {
        this.form.setting.config.line.enable = false
      }
      for (let key in response.data.source) {
        source[key] = response.data.source[key]
        if (response.data.source[key].length === 0 || response.data.schema[key].type === 6) {
          await this.$store.dispatch('getSourceDataList', key)
          if (response.data.setting.title1) {
            this.form.setting.title1 = response.data.setting.title1
          }
          if (response.data.setting.title2) {
            this.form.setting.title2 = response.data.setting.title2
          }
        }
      }
      for (let key in response.data.schema) {
        if (this.form.schema[key].type !== 6) {
          this.$set(this.selected, key, this.form.source[key].slice(0, response.data.schema[key].num).map(item => item.name))
          this.form.source[key].map(item => {
            item.selected = this.selected[key].indexOf(item.name) !== -1
          })
        } else {
          this.treeKey[key] = source[key].map(item => parseInt(item.name))
          this.selected[key] = getTreeNameByIds(this.form.source[key], this.treeKey[key])
        }
      }
      await this.$store.dispatch('getItemSettingColor', [])
      await this.getDataCount()
      this.$nextTick(() => {
        this.loading = false
      })
    },

  }
};
</script>
<style lang="scss" scoped>
.custom-analyse {
  .custom-analyse-chart-img-box {
    background: #ffffff;
  }
  .custom-analyse-chart-title {
    padding: 20px;
    span {
      font-weight: bold;
      font-size: 16px;
    }
  }
  .custom-analyse-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 20px;
    .number {
      padding-left: 10px;
      color: #409EFF;
    }
    .text {
      font-size: 13px;
      padding-right: 20px;
    }
  }
}
</style>