import * as echarts from '../ec-canvas/echarts'
import { mergeOptions } from '../ec-canvas/defaultOption'
var util = require('../../../utils/util');
var api = require('../../../config/api.js');

let ecXdata, ecYdata, rateXdata, rateYdata, ec2Xdata, ec2Ydata, ec3Xdata, ec3Ydata
const dayLength = 7
Component({
  /**
   * 组件的初始数据
   */
  data: {
    userInfo: {},
    detail: {},
    activeType: 0,
    brandNameList: [],
    index: 0,
    // ec2: {
    //   onInit: init2Chart
    // },
    // barEc: {
    //   onInit: initBarChart
    // },
    dataNumList: [
      {
        value: 0,
        label: '店铺浏览量',
        key: 'pvTotalNum',
        bgColor: 'rgba(255, 205, 60, 0.1)',
        color: '#FFCD3C'
      },
      {
        value: 0,
        label: '用户访问量',
        key: 'uvTotalNum',
        bgColor: 'rgba(77,174,255,0.1)',
        color: '#4DAEFF'
      },
      {
        value: 0,
        label: '用户咨询量',
        bgColor: 'rgba(23,210,210,0.1)',
        color: '#17D2D2',
        key: 'totalTalkNum'
      },
      {
        value: 0,
        label: '店铺商品数',
        bgColor: 'rgba(246,151,88,0.1)',
        color: '#F69758',
        key: 'goodsNum'
      }
    ],
    chartTypes: [
      {
        icon: 'data_booth',
        name: '店铺数据',
        value: 0
      },
      {
        icon: 'data_visitor',
        name: '访客数据',
        value: 1
      },
      {
        icon: 'data_wares',
        name: '商品数据',
        value: 2
      },
    ]
  },

  lifetimes: {
    
  },
  async ready () {
    this.userInfo = wx.getStorageSync('userinfoDetail')
    this.brandList = this.userInfo.brandList
    this.setData({
      userInfo: this.userInfo,
      brandNameList: [this.userInfo.brandName]
    })
    await this.getBrandList()
    this.getData()
  },
  methods: {
    changeActiveType (e) {
      const { value } = e.currentTarget.dataset
      this.setData({
        activeType: value
      })
    },
    async getData () {
      let userInfo = this.userInfo
      if (!userInfo || !userInfo.userId) {
        return
      }
      
      let res = await util.request(api.SceneReport ,{
        guideId: userInfo.userId,
        brandId: this.brandList[this.data.index].brandId,
        startDate: fotmatDate(new Date(new Date().getTime() - 86000000), 'yyyy-MM-dd'),
        size: dayLength
      }, 'get')
      if (res.code !== 0) {
        wx.showModal({
          title: '未查询到店铺统计信息',
        })
        return
      }
      let data = res.data
      let hotVisitHistory = this.formatData(data.hotVisitHistory)
      ec3Xdata = hotVisitHistory.xaxis
      ec3Ydata = hotVisitHistory.result
      let sceneVisit = this.formatData(data.pvHistory)
      ecXdata = sceneVisit.xaxis
      ecYdata = sceneVisit.result
      let uvVisit = this.formatData(data.uvHistory)
      ec2Xdata = uvVisit.xaxis
      ec2Ydata = [uvVisit.result]
      let dealHistory = this.formatData(data.dealHistory)
      let goodsDetailVisitHistory = this.formatData(data.goodsDetailVisitHistory)
      rateXdata = goodsDetailVisitHistory.xaxis
      rateYdata = goodsDetailVisitHistory.result.map((item, index) => ((dealHistory.result[index] || 0) * 100 / (item || 1)).toFixed(1))
      let talkHistory = this.formatData(data.talkHistory)
      ec2Ydata[1] = talkHistory.result
      let dataNumList = this.data.dataNumList.map(item => {
        if (data[item.key]) {
          item.value = formatNum(data[item.key])
        }
        return item
      })
      this.setData({
        // detail: data,
        dataNumList,
        ec: {
          onInit: initChart
        },
        ec2: {
          onInit: init2Chart
        },
        ec3: {
          onInit: init3Chart
        },
        rateEc: {
          onInit: initRateChart
        }
      })
    },
    formatData (data) {
      if (typeof data === 'string') {
        data = JSON.parse(data)
      }
      if (!(data instanceof Array)) {
        data = []
      }
      let originData = []
      if (data.length < dayLength) {
        let today = new Date(fotmatDate(new Date(), 'yyyy-MM-dd')).getTime()
        
        for (let i =0; i < dayLength; i++) {
          let theDay = today - (dayLength - i) * 86400000
          let inData = {}
          let date = fotmatDate(new Date(theDay), 'yyyy-MM-dd')
          inData[date] = data.find(item => item[`${date} 00:00:00`]) ? data.find(item => item[`${date} 00:00:00`])[`${date} 00:00:00`] : 0
          originData.push(inData)
        }
      } else {
        originData = data
      }
      let xaxis = originData.map(item => Object.keys(item)[0].slice(5,10))
      let result = originData.map(item => item[Object.keys(item)[0]])
      return {
        result,
        xaxis,
      }
    },
    async getBrandList () {
      let res = await util.request(api.GetAdminBrands ,{
        userId: this.userInfo.userId,
      })
      let list = res.data
      let brandNameList = list.map(item => item.brandName.slice(0,15))
      this.brandList = list
      this.setData({
        brandNameList
      }) 
    },
    bindPickerChange (e) {
      let index = e.detail.value
      let brand = this.brandList[index]
      console.log(e)
      this.setData({
        index
      })
      this.reset()
      wx.nextTick(() => {
        this.getData()
      })
    },
    reset() {
      this.setData({
        ec: '',
        ec2: '',
        ec3: '',
        rateEc: '',
        dataNumList: [
          {
            value: 0,
            label: '店铺浏览量',
            key: 'pvTotalNum',
            bgColor: 'rgba(255, 205, 60, 0.1)',
            color: '#FFCD3C'
          },
          {
            value: 0,
            label: '用户访问量',
            key: 'uvTotalNum',
            bgColor: 'rgba(77,174,255,0.1)',
            color: '#4DAEFF'
          },
          {
            value: 0,
            label: '用户咨询量',
            bgColor: 'rgba(23,210,210,0.1)',
            color: '#17D2D2',
            key: 'totalTalkNum'
          },
          {
            value: 0,
            label: '店铺商品数',
            bgColor: 'rgba(246,151,88,0.1)',
            color: '#F69758',
            key: 'goodsNum'
          }
        ],
      })
    }
  }
})

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);
  
  var option = {
    title: {
      text: ''
    },
    tooltip: {
      formatter: `{a}: {c} \n${new Date().getFullYear()}-{b}`,
      axisPointer: {
        lineStyle: {
          color: '#FFCD3C'
        }
      }
    },
    color: ['#FFCD3C'],
    xAxis: {
      boundaryGap: false,
      data: ecXdata
    },
    series: [
      {
        data: ecYdata,
        type: 'line',
        name: '浏览量',
        symbolSize: 2,
        showSymbol: false,
        symbol: 'circle',
        smooth: 0.5,
        areaStyle: {
          opacity: 0.1
        },
      },
    ]
  };

  chart.setOption(mergeOptions(option));
  return chart;
}

function init3Chart(canvas, width, height, dpr, xdata,) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);
  
  var option = {
    title: {
      text: ''
    },
    color: ['#0075DC'],
    tooltip: {
      formatter: `{a}: {c} \n${new Date().getFullYear()}-{b}`,
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(255, 205, 60, 0.1)'
        },
        lineStyle: {
          color: 'rgba(255, 205, 60, 0.1)'
        }
      }
    },
    xAxis: {
      data: ec3Xdata,
      boundaryGap: true
    },
    series: [
      {
        data: ec3Ydata,
        type: 'bar',
        name: '浏览量',
        itemStyle: {
          barBorderRadius: [5,5,0,0],
        },
        barWidth: 10,
        emphasis: {
          itemStyle: {
            opacity: 1
          }
        }
      },
    ]
  };

  chart.setOption(mergeOptions(option));
  return chart;
}

function init2Chart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    xAxis: {
      data: ec2Xdata
    },
    tooltip: {
      formatter: `访问量: {c0} \n咨询量: {c1} \n${new Date().getFullYear()}-{b}`,
      axisPointer: {
        lineStyle: {
          color: '#FFCD3C'
        }
      }
    },
    series: [
      {
        data: ec2Ydata[0] || [],
        type: 'line',
        name: '客户访问量',
        symbolSize: 2,
        showSymbol: false,
        symbol: 'circle',
        smooth: 0.5,
        color: '#0075DC',
        areaStyle: {
          opacity: 0.1
        },
      },
      {
        data:  ec2Ydata[1] || [],
        type: 'line',
        name: '客户咨询量',
        symbolSize: 2,
        showSymbol: false,
        symbol: 'circle',
        color: '#FFCD3C',
        smooth: 0.5,
        areaStyle: {
          opacity: 0.1
        },
      },
    ]
  };

  chart.setOption(mergeOptions(option));
  return chart;
}

function initRateChart(canvas, width, height, dpr,) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);
  
  var option = {
    title: {
      text: ''
    },
    color: ['#FFCD3C'],
    tooltip: {
      formatter: `{a}: {c}% \n ${new Date().getFullYear()}-{b}`
    },
    xAxis: {
      data: rateXdata,
      axisLine: {
        show: true
      }
    },
    // yAxis: {
    //   max: 100
    // },
    series: [
      {
        data: rateYdata,
        type: 'line',
        name: '转化率',
        symbolSize: 2,
        showSymbol: false,
        symbol: 'circle'
      },
    ]
  };

  chart.setOption(mergeOptions(option));
  return chart;
}

function fotmatDate (date, fmt='yyyy.MM.dd') {
  if (!(date instanceof Date)) {
    date = changeDateFormat(date)
  }
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}

// 转格式 否则IOS下会有问题
function changeDateFormat(cellval) {
	var dateVal = cellval + "";
	if (cellval != null) {
    dateVal = dateVal.slice(0, 19)
		dateVal = dateVal.replace("T"," ").replace("Z","").replace(/-/g, "/");
		var date = new Date(dateVal);
		
		date = new Date(date.setHours(date.getHours()));
		
		return date
	}
}

// 数值太大转为带万的文字
function formatNum (num) {
  return num >= 10000 ? num >= 1000000 ? `99W+` : `${(num/10000).toFixed(2).replace(/[.]?0+$/g,"")}W` : num
}