export const settingData = {
    props: {
      form: Object
    },
   
  }

export const settingMethod = {
    data() {
        return {
            form:{
                setting: {
                  backgroundColor:'rgb(255 255 255)',
                  text:{
                    text:'',
                    show: true,
                    link:'',
                    target: 'blank',
                    subtext: '',
                    sublink:'',
                    subtarget: 'blank',
                    left: 'center',
                    bottom: 0,
                    backgroundColor: 'rgba(0,0,0,0)',
                    borderColor: "#ccc",
                    borderWidth: 0,
                    padding: 5,
                    itemGap: 10,
                    textStyle:{
                      fontSize: 14,
                      fontWeight: false,
                      color: '#464646',
                    },
                    subtextStyle:{
                      fontSize: 14,
                      fontWeight: false,
                      color: '#464646',
                    }
                  },
                  yMin:0,
                  splitNumber:'',
                  yMax:'',
                  type: 2,
                  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: "500",
                  widthUnit: "%",
                  heightUnit: "px",
                  splitLine: false,
                  splitLine2: true,
                  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: 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: []
                  }
                },
                schema: {
                  x: {
                    num: 10
                  },
                  y: {
                    num: 10
                  },
                },
                source: {
                  x: [],
                  y: []
                },
              },
            selected:{},
        }
    },
    watch:{
        form(val){
            // console.log(val)
        }
    },
    methods: {
        handleAdd() {
            let table = []
            for (let i = 0; i < 10; i++) {
              table.push({
                min: 0,
                max: 0,
                color: null
              })
            }
            this.form = {
              setting: {
                type: 2,
                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.$store.commit('SET_CHART_FORM', form)
            // this.drawer = true
          },
    },
}
export const chartOption = {
    // mixins: [customPage],
    props: {
      width: String,
      height: String
    },
    data() {
      return {}
    },
    methods: {
      async handleScreenshot(id, name) {
        const canvas = await html2canvas(document.getElementById(id))
        const base64 = canvas.toDataURL('image/jpg')
        downLoadBase64(base64, name + '.png')
      },
      getDataLabel() {
        return {
          show: this.form.setting.dataLabel,
          fontSize: this.form.setting.dataSize,
          position: this.form.setting.dataPosition,
          fontFamily: this.form.setting.fontFamily2,
          color: this.form.setting.labelColor,
          formatter: (val) => {
            switch (val.seriesType) {
              case 'sunburst':
                return val.name
              case 'heatmap':
                return val.value[2]
              case 'tree':
                return val.data.name
              case 'scatter':
                return !val.data[2] ? '' : val.data[2]
              case 'treemap':
                return `${val.name} (${val.value})`
              case 'map':
                return val.value ? `${val.name} \n ${val.value}` : ''
              default:
                if (val.value) {
                  return val.value
                } else {
                  return ''
                }
            }
          }
        }
      },
      getAxisName(dimension) {
        return this.form.setting[dimension]
      },
      getAxisData(dimension) {
        return this.selected[dimension]
      },
      getColor(name) {
        const color = this.form.setting.config.color.find(item => item.name === name);
        return color ? color.color : undefined
      },
      getDataCount(x, y, b = true) {
        if (b) {
          if (this.form.schema.x.type === 6) {
            const xn = getTreeDataList(this.form.source.x, []).find(item => item.name === x)
            if (xn) {
              x = xn.id
            }
          }
          if (this.form.schema.y.type === 6) {
            const yn = getTreeDataList(this.form.source.y, []).find(item => item.name === y)
            if (yn) {
              y = yn.id
            }
          }
        }
        if (x && y) {
          if (this.count[x]) {
            return this.count[x][y] || 0
          } else {
            return 0
          }
        }
        if (x && !y) {
          return this.count[x] || 0
        }
        if (!x && !y) {
          return random(0, 100)
        }
      },
      getSeriesData() {
        let data = [], count = this.count
        let source = this.selected.x
        switch (this.$options.name) {
          case 'CLine':
          case 'CArea':
          case 'CBar':
          case 'CColumn':
            source.map(s => {
              const color = this.form.setting.config.color.find(item => item.name === s);
              data.push({
                value: this.getDataCount(s),
                itemStyle: {
                  color: color ? color.color : undefined
                }
              })
            })
            break
          case 'CDoughnut':
          case 'CPie':
            source.map(s => {
              const color = this.form.setting.config.color.find(item => item.name === s);
              data.push({
                value: this.getDataCount(s),
                name: s,
                label: {
                  show: this.form.setting.dataLabel,
                  fontSize: this.form.setting.dataSize,
                  fontFamily: this.form.setting.fontFamily2,
                  color: this.form.setting.labelColor,
                  position: this.form.setting.dataPosition,
                  formatter: ({ value, name, percent }) => {
                    let text = ""
                    if (this.form.setting.dataLabel) {
                      text += name
                    }
                    if (this.form.setting.dataLabel2) {
                      text += `-${value}件`
                    }
                    if (this.form.setting.dataLabel3) {
                      text += `/${percent}%`
                    }
                    return text
                  }
                },
                itemStyle: {
                  color: color ? color.color : undefined
                }
              })
            })
            break
        }
        return data
      },
      getAxisLabel(type, axis) {
        return  {
          interval: axis === 'x' ? (this.form.setting.interval ? 0 : undefined) : (this.form.setting.interval2 ? 0 : undefined),
          rotate: axis === 'x' ? this.form.setting.rotate : this.form.setting.rotate2,
          color: axis === 'x' ? this.form.setting.fontColor : this.form.setting.fontColor2,
          show: axis === 'x' ? this.form.setting.show : this.form.setting.show2,
          fontSize: axis === 'x' ? this.form.setting.fontSize : this.form.setting.fontSize2,
          fontFamily: axis === 'x' ? this.form.setting.fontFamily : this.form.setting.fontFamily2,
          fontWeight: (axis === 'x' ? this.form.setting.fontWeight : this.form.setting.fontWeight2) ? 'bold' : 'normal'
        }
      },
      getNameTextStyle(axis) {
        return {
          padding: axis === 'x' ? [this.form.setting.paddingTop, this.form.setting.paddingLeft, this.form.setting.paddingBottom, this.form.setting.paddingRight] : [this.form.setting.paddingTop2, this.form.setting.paddingLeft2, this.form.setting.paddingBottom2, this.form.setting.paddingRight2],
          color: axis === 'x' ? this.form.setting.fontColor : this.form.setting.fontColor2,
          fontSize: axis === 'x' ? this.form.setting.fontSize : this.form.setting.fontSize2,
          fontFamily: axis === 'x' ? this.form.setting.fontFamily : this.form.setting.fontFamily2,
          fontWeight: (axis === 'x' ? this.form.setting.fontWeight : this.form.setting.fontWeight2) ? 'bold' : 'normal'
        }
      },
      dateTimeSort() {
        let temp = JSON.parse(JSON.stringify(this.selected.x))
        let data = []
        let t, y, m
        temp.map(item => {
          switch (this.form.schema.x.expand) {
            case 9:
            case 12:
              data.push({
                name: item,
                time: new Date(item).getTime()
              })
              break
            case 10:
              t = item.split('-')
              y = t[0]
              m = (parseInt(t[1].replaceAll('Q', '')) - 1) * 3 + 1
              data.push({
                name: item,
                time: new Date(y + '-' + m).getTime()
              })
              break
            case 11:
              t = item.split('-')
              y = t[0]
              m = parseInt(t[1].replaceAll('H', '')) * 6
              data.push({
                name: item,
                time: new Date(y + '-' + m).getTime()
              })
              break
            case 13:
            case 14:
            case 15:
              t = item.split('-')
              y = t[0]
              data.push({
                name: item,
                time: new Date(y + '-01').getTime()
              })
              break
          }
        })
        this.selected.x = data.sort((a, b) => a.time - b.time).map(item => item.name)
      },
      get1AxisOption(type, areaStyle) {
        if (this.form.schema.x.ptype === 2) {
          this.dateTimeSort()
        }
        let xAxis = {
          name: this.getAxisName('title1'),
          nameTextStyle: this.getNameTextStyle('x'),
          type: 'category',
          data: this.getAxisData('x'),
          nameLocation: this.form.setting.nameLocation,
          splitLine: {
            show: this.form.setting.splitLine
          },
          axisLabel: this.getAxisLabel('category', 'x')
        }
        let yAxis = {
          name: this.getAxisName('title2'),
          nameTextStyle: this.getNameTextStyle('y'),
          type: 'value',
          nameLocation: this.form.setting.nameLocation2,
          splitLine: {
            show: this.form.setting.splitLine2
          },
          axisLabel: this.getAxisLabel('value', 'y')
        }
        let series = [{
          data: this.getSeriesData(),
          type: type,
          areaStyle: areaStyle,
          itemStyle: {
            color: this.form.setting.config.color[0].color
          },
          barWidth: this.form.setting.barWidth,
          label: this.getDataLabel()
        }]
        let grid = {
          top: this.form.setting.gridTop + '%',
          left: this.form.setting.gridLeft + '%',
          right: this.form.setting.gridRight + '%',
          bottom: this.form.setting.gridBottom + '%',
          containLabel: true,
        }
        return {
          xAxis,
          yAxis,
          series,
          grid
        }
      },
      get2AxisOption(type, stack) {
        if (this.form.schema.x.ptype === 2) {
          this.dateTimeSort()
        }
        const enable = this.form.setting.config.line.enable
        const operator = this.form.setting.config.line.operator
        let backgroundColor = this.form.setting.backgroundColor
        // let series = this.selected.data
        let series = this.selected.y.map(y => {
            return {
              name: y,
              type: type,
              stack: stack,
              itemStyle: {
                color: this.getColor(y)
              },
              barWidth: this.form.setting.barWidth,
              data: this.selected.data.find(item => item.name == y).data,
              label: this.getDataLabel(),
              connectNulls:true,
            }
          })
        let xAxis = {
          name: this.form.setting.title1,
          nameTextStyle: this.getNameTextStyle('x'),
          type: 'category',
          nameLocation: this.form.setting.nameLocation,
          data: this.selected.x,
          splitLine: {
            show: this.form.setting.splitLine
          },
          axisLabel: this.getAxisLabel('category', 'x')
        }
        let yAxis = {
          min:this.form.setting.yMin,
          splitNumber:this.form.setting.splitNumber,
          // max:this.form.setting.yMax,
          name: this.form.setting.title2,
          nameTextStyle: this.getNameTextStyle('y'),
          type: 'value',
          nameLocation: this.form.setting.nameLocation2,
          splitLine: {
            show: this.form.setting.splitLine2
          },
          axisLabel: this.getAxisLabel('value', 'y')
        }
        let legend =this.selected.y.length>1? [...this.selected.y]:[]
        let toolbox = {
          show: true,
          right:'50px',
          feature:{
            saveAsImage: {
              show:true,
              excludeComponents :['toolbox'],
              pixelRatio: 2
            },
            magicType: {
              show: true,
              type: [ 'bar', 'stack']
            },
            dataZoom:{
              show:true
            },
            dataView:{
              show: true,
              lang: ['数据视图', '关闭', '导出Excel'],
              optionToContent: function(opt){
                  //axisData是你想定义的表格第一列的数据，我这里设置为柱形图的x轴数据
                  var axisData = opt.xAxis[0].data;
                  //tAxis[0]为你想定义的表格第一行的数据
                  var txisData = [];
                  if(opt.series.length>1){
                    txisData.push('产品名称')
                  }
                  txisData.push(opt.xAxis[0].name)
                  txisData.push(opt.yAxis[0].name)
                  var series = opt.series;
                  //表头
                  var tdHeads = '';
                  var tdBodys = '';
                  var nameData = txisData;
                  for (var i = 0; i < nameData.length ; i++) {
                      tdHeads += '<td style="padding: 0 10px;width:100px">' + nameData[i] + '</ td >';
                  }
                  var table = '<table id="Mytable" border="1" class="table table-bordered table-striped table-hover" style="width:100%;text-align:center" ><tbody><tr>' + tdHeads + ' </tr>';
                
                  for(var i = 0; i<series.length;i++){
                    for(var j =0;j<axisData.length;j++){
                      if(series.length>1){
                        if(j==0){
                          tdBodys += '<td rowspan="'+ axisData.length +'" colspan="1">' + series[i].name + '</td>';
                        }
                      }
                      tdBodys += '<td>' + axisData[j] + '</td>';
                      var temp = series[i].data[j]
                      if (temp != null && temp != undefined) {
                          tdBodys += '<td>' + temp + '</td>';
                      } else {
                          tdBodys += '<td>'+ " " +'</td>';
                      }
                      table += '<tr style="mso-number-format:'+'\@'+';">' + tdBodys + '</tr>';
                      tdBodys = '';
                    }
                   
                  }
                  table += '</tbody></table>';
                  return table;
              },
              contentToOption: function (HTMLDomElement, opt) {
                    // Worksheet名
                    const worksheet = 'Sheet1'
                    const url = '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]-->
                      ${HTMLDomElement.innerHTML}`
                    // 下载模板
                    let link = document.createElement('a')
                    link.setAttribute('href', url + window.btoa(unescape(encodeURIComponent(template))))
                    link.setAttribute('download', opt.title[0].text+'.xls')
                    link.click()
              },

            }
          }
        }
        // if (enable && ([5, 6].indexOf(this.form.setting.type) !== -1)) {
        //   let name = this.form.setting.config.line.name
        //   series.push({
        //     name: name,
        //     type: 'line',
        //     yAxisIndex: 1,
        //     data: getLineDataArr(this.form, this.selected, this.count),
        //     itemStyle: {
        //       color: this.form.setting.config.line.color
        //     },
        //     label: {
        //       ...this.getDataLabel(),
        //       formatter({ value }) {
        //         return operator === 1 ? `${Math.round(parseFloat(value) * 100)} %` : value
        //       }
        //     }
        //   })
        //   yAxis.push({
        //     type: 'value',
        //     name: name,
        //   })
        //   legend.push(name)
        // }
        let grid = {
          top: this.form.setting.gridTop + '%',
          left: this.form.setting.gridLeft + '%',
          right: this.form.setting.gridRight + '%',
          bottom: this.form.setting.gridBottom + '%',
          containLabel: true
        }
        let title = JSON.parse(JSON.stringify(this.form.setting.text))
        title.textStyle.fontWeight = this.form.setting.text.textStyle.fontWeight?'bold':'normal'
        title.subtextStyle.fontWeight = this.form.setting.text.subtextStyle.fontWeight?'bold':'normal'
        return {
          backgroundColor,
          title,
          legend: {
            show: this.form.setting.legend,
            data: legend,
            textStyle: {
              fontFamily: this.form.setting.fontFamily3,
              color: this.form.setting.legendColor,
              fontSize: this.form.setting.legendFontSize
            },
            ...this.getLegendLocation(),
            type: this.form.setting.type2,
          },
          grid,
          xAxis,
          yAxis,
          series,
          toolbox
        }
      },
      getLegendLocation() {
        let x = ''
        let y = ''
        switch (this.form.setting.legendLocation) {
          case 'top':
            x = 'center'
            y = 'top'
            break
          case 'left':
            x = 'left'
            y = 'center'
            break
          case 'bottom':
            x = 'center'
            y = 'bottom'
            break
          case 'right':
            x = 'right'
            y = 'center'
            break
        }
        return {
          x: x,
          y: y,
          orient: ['top', 'bottom'].indexOf(this.form.setting.legendLocation) !== -1 ? 'horizontal' : "vertical",
        }
      },
      dispose(id){
        const chartDom = document.getElementById(id);
        const myChart = this.$echarts.init(chartDom);
        myChart.dispose();
      },
      initChart(id, chartOption) {
        // console.log(id,chartOption)
        const chartDom = document.getElementById(id);
        const myChart = this.$echarts.init(chartDom);
        myChart.clear();
        myChart.setOption(chartOption)
        // this.$store.commit('SET_MY_CHART', myChart)
        return myChart
      },
    }
  }
  
  export const chartOptionMixins = {
    data() {
        return {
            // form:{},
            selected:{}
        }
    },
    mixins: [chartOption],
    mounted() {
    //   this.$nextTick(() => {
    //     this.initChart(this.id, this.getOption())
    //   })
    },
    methods:{
        setColor(){
            const defaultColor = [
                '#5470c6',
                '#91cc75',
                '#fac858',
                '#ee6666',
                '#73c0de',
                '#3ba272',
                '#fc8452',
                '#9a60b4',
                '#ea7ccc',
              ]
              let index = 0
              if (this.selected.y.length>0) {
                this.form.setting.config.color = this.selected.y.map(item => {
                  if (index >= defaultColor.length) {
                    index = 0
                  }
                  return {
                    name: item,
                    color: defaultColor[index++]
                  }
                })
              }
        }
    }
  }