<template>
  <div class="custom-analyse">
    <el-container>
      <el-aside width="350px">
        <!-- <el-container>
          <el-header class="custom-analyse-tabs">
            <el-tabs v-model="activeTab" type="card">
              <el-tab-pane label="分析项" name="TabItem"></el-tab-pane>
              <el-tab-pane label="数据" name="TabData"></el-tab-pane>
              <el-tab-pane label="样式" name="TabStyle"></el-tab-pane>
              <el-tab-pane label="辅助线" name="TabLine" :disabled="enable.indexOf(form.setting.type) === -1"></el-tab-pane>
            </el-tabs>
          </el-header>
          <el-main class="nopadding"> -->
            <!-- <component
                :is="activeTab"
                :active-item="activeItem"
                @edit="handleEdit"
                @delete="handleDelete"
                @select="handleSelect"
            ></component> -->
          <!-- </el-main>
        </el-container> -->
        <TabItem :active-item="activeItem" @edit="handleEdit" @delete="handleDelete" @select="handleSelect"></TabItem>
      </el-aside>
      <el-container>
        <el-header>
          <template>
            <div class="custom-analyse-options">
              <span class="text">专利数量<span class="number">{{ patentNum }} 件</span></span>
              <el-button size="small" type="primary" @click="handleAdd3">添加组</el-button>
              <el-dropdown size="small">
                <el-button size="small" type="warning">
                  更多菜单<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>
          </template>
        </el-header>
        <el-main class="custom-analyse-chart-img-box">
          <div v-if="showChart">
            <chart ref="chartDom" :form="from" :width="form.setting.width + form.setting.widthUnit" :height="form.setting.height + form.setting.heightUnit" />
          </div>
        </el-main>
      </el-container>
    </el-container>

    <addAnalyseGroup ref="addAnalyseGroup" :projectId="projectId" @save="queryAnalyseGroup"></addAnalyseGroup>
    <el-drawer
        title="图表配置"
        :visible.sync="drawer"
        direction="rtl"
        :before-close="handleClose"
        size="500px">
        <div style="width:500px">
          <component :is='components'></component> 
        </div>
    </el-drawer>
  </div>
</template>

<script>
import Chart from "./components/Charts/index.vue";
import { mapGetters } from "vuex";
import { downLoad, findChildren, getTreeLastChildren, getTreeDataList, downLoadBase64 } from "@/utils";
import { customPage } from "./mixins";
import moment from "moment";
import TreeSelect from '@riophae/vue-treeselect'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { detectionChartType, getFormPermissions, getTreeNameByIds, getXAxisName, getSourceName } from "@/utils/chart";
import TabItem from "./components/Tabs/Item";
import TabData from "./components/Tabs/Data";
// import TabLine from "./components/Tabs/Line";
import html2canvas from "html2canvas";
import addAnalyseGroup from './components/dialog/addAnalyseGroup.vue'
export default {
  components: {
    TreeSelect,
    Chart,
    TabItem,
    TabData,
    TabStyle,
    TabLine,
    addAnalyseGroup
  },
  mixins: [customPage],
  data() {
    return {
      components:'',
      activeTab: 'TabItem',
      enable: [2, 5, 6, 8, 9, 17],
      saveType: 0,
      form2: {},
      rules: {
        parentId: [
          {required: true, message: '请选择上级目录', trigger: 'change'},
        ],
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
        ],
        permissions: [
          {required: true, message: '请输选择使用权限', trigger: 'change'},
        ],
        sort: [
          {required: true, message: '请输入显示次序', trigger: 'blur'},
        ],
      },
      showChart: true,
      showPage: false,
      loadingBtn2: false,
      loadingBtn3: false,
      activeName: '1',
      activeItem: [],
      loading: false,
      loadingBtn: false,
      title: '',
      chartTitle: '',
      dialogVisible: false,
      loadData: true,
      drawer: false,
      tempForm: {
        name: '',
        sort: 0
      },
    }
  },
  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
    },
  },
  mounted() {
    this.getData()
  },
  methods: {
    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
        } else {
          this.activeItem = [this.treeList[0].id]
          await this.handleSelect(this.treeList[0].children[0].uid)
        }
        this.showPage = true

    },
    handleDelete(value) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const response = await this.$api.deleteCustomItem(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].uid)
          } else {
            this.handleAdd()
          }
        }
      })
    },
    // 获取需要进行的每一个分析项
    async getTreeList() {
      this.loading = true
      const response = await this.$api.getCustomTree({ 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()
      this.title = '保存自定义分析'
      let data = {
        parentId: null,
        permissions: 2,
        name: '',
        sort: 0
      }
      if (this.form.uid) {
        const response = await this.$api.getCustomItem(this.form.uid)
        data = response.data
        this.tempForm.name = data.name
        this.tempForm.sort = data.sort
      }
      this.form2 = {
        id: data.id,
        parentId: data.parentId,
        type: 1,
        permissions: data.permissions,
        name: data.name,
        sort: data.sort,
        setting: this.form.setting,
        schema: this.form.schema,
        source: this.form.source,
        projectId: this.projectId
      }
      this.dialogVisible = true
    },
    handleAdd() {
      let table = []
      for (let i = 0; i < 10; i++) {
        table.push({
          min: 0,
          max: 0,
          color: null
        })
      }
      let form = {
        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: "0",
          gridLeft: "0",
          gridBottom: "0",
          gridRight: "0",
          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: 0,
          paddingBottom: 0,
          paddingRight: 0,
          paddingLeft: 0,
          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
          },
          y: {
            num: 10
          },
        },
        source: {
          x: [],
          y: []
        },
      }
      this.form = form
      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) {
        const { source, schema } = this.getDataCountParams()
        let params = {
          type: this.form.setting.type,
          schema: schema,
          source: source,
          patentKey: this.patentKey,
          projectId: this.projectId
        }
        this.loading = true
        try {
          const response = await this.$api.getDataCount(params)
          this.$store.commit('SET_DATA_COUNT', response.data)
          this.refreshChart()
          this.$store.commit('SET_RELOAD_DATA', false)
          this.loading = false
          this.showChart = true
        } catch (e) {
          this.loading = false
          this.showChart = false
        }
      }
    },
    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() {
      this.loadingBtn3 = true
      const { count, type, xAxis } = this.getExportParams()
      this.$api.exportCustomItem(count, type, xAxis).then(response => {
        downLoad(response, moment().format('YYYYMMDDHHmmss') + '.xls')
        this.loadingBtn3 = false
      }).catch(error => {
        this.loadingBtn3 = false
      })
    },
    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()
      }
      if (!this.form.setting.type) {
        this.$message.error('请选择图表类型')
        return false
      }
      await this.getDataCount()
      this.refreshChart()
      this.showChart = true
    },
    async handleSelect(key) {
      let source = {
        x: [],
        y: []
      }
      this.$store.commit('SET_RELOAD_DATA', true)
      this.activeName = '1'
      this.loading = true
      const response = await this.$api.getCustomItem(key)
      this.$store.commit('SET_CHART_FORM', JSON.parse(JSON.stringify(response.data)))
      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
      })
    },
    handleConfirm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loadingBtn = true
          let form = JSON.parse(JSON.stringify(this.form2))
          for (let key in form.schema) {
            form.schema[key].field = form.schema[key].field || 0
            form.schema[key].expand = form.schema[key].expand || 0
            if (form.schema[key].type === 6) {
              form.source[key] = this.treeKey[key].map(item => { return { name: item, selected: true } })
            }
          }
          try {
            let response
            if (typeof form.parentId === 'string') {
              form.parentName = form.parentId
              form.parentId = undefined
            }
            if (form.type) {
              form.permissions = getFormPermissions(form)
            }
            if (!this.saveType && form.id) {
              response = await this.$api.editCustomItem(form)
              this.$message.success('编辑成功')
            } else {
              form.id = null
              response = await this.$api.addCustomItem(form)
              this.activeItem.push(response.data.parentId)
              this.$message.success('添加成功')
              if (form.type) {
                await this.handleSelect(response.data.uid)
              }
            }
            if (form.type) {
              this.chartTitle = response.data.name
            }
            await this.getTreeList()
            this.loadingBtn = false
            this.handleClose()
          } catch (e) {
            this.loadingBtn = false
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
  }
}
</script>

<style lang="scss">
.custom-analyse {
  .custom-analyse-tabs {
    .el-tabs__header {
      margin-top: 35px !important;
      margin-left: 22px;
    }
  }
  .custom-analyse-chart-img-box {
    background: #ffffff;
  }
  .custom-analyse-chart-title {
    padding: 20px;
    span {
      font-weight: bold;
      font-size: 16px;
    }
  }
  .custom-analyse-options {
    padding: 20px;
    .number {
      padding-left: 10px;
      color: #409EFF;
    }
    .text {
      font-size: 13px;
      padding-right: 20px;
    }
  }
}
</style>