const _Http = getApp().globalData.http,
  currency = require("../../../utils/currency"),
  CNY = (value, symbol = "￥", precision = 2) => currency(value, {
    symbol,
    precision
  }).format();
import * as echarts from '../../ec-canvas/echarts';
Component({
  options: {
    addGlobalClass: true
  },
  lifetimes: {
    attached: function () {
      getApp().globalData.Language.getLanguagePackage(this)
      this.setData({
        "content.dataid": wx.getStorageSync('userMsg').userid,
        "content.username": wx.getStorageSync('userMsg').name,
      })
    }
  },
  data: {
    year: new Date().getFullYear().toString(),
    "content": {
      enddate: new Date().toISOString().split('T')[0],
      dateType: "15-30天",
      dataType: "",
      where: {
        dateType: "15-30天",
        type: "",
        tradingstatus: "",
        grade: "",
      },
      pageNumber: 1,
      pageSize: 20,
      pageTotal: 1
    },
    types: [],
    grades: [],
    tradingstatus: [{
      remarks: '全部',
      value: ''
    }, {
      remarks: '未成交',
      value: '未成交'
    }, {
      remarks: '已成交',
      value: '已成交'
    }, {
      remarks: '多次成交',
      value: '多次成交'
    }],
  },
  methods: {
    async getList(init = false) {
      if (this.data.grades.length == 0) {
        _Http.basic({
          "classname": "sysmanage.develop.optiontype.optiontype",
          "method": "optiontypeselect",
          "content": {
            "pageNumber": 1,
            "pageSize": 1000,
            "typename": "agentgrade",
            "parameter": {}
          },
        }).then(res => {
          console.log("客户分类", res)
          if (res.code == 1) {
            res.data.unshift({
              remarks: '全部',
              value: ''
            })
            this.setData({
              grades: res.data
            })
          }

        })
      }
      if (init.detail != undefined) init = init.detail;
      let content = this.data.content
      const {
        dataid,
        type,
        username,
        isleave
      } = getCurrentPages()[getCurrentPages().length - 1].data;
      if (content.dataid != dataid || content.type != type || isleave != isleave) init = true
      content.dataid = dataid;
      content.type = type;
      content.username = username;
      content.where.isleave = isleave;
      if (init) {
        content.pageNumber = 1;
        content.pageSize = 20;
      }
      if (content.pageNumber > content.pageTotal) return;
      _Http.basic({
        "id": 20231018093704,
        content
      }).then(res => {
        console.log("有效客户未跟进天数分析", res)
        this.selectComponent('#ListBox').automaticSetHei();
                this.selectComponent('#ListBox').RefreshToComplete();
        if (res.code != '1') return wx.showToast({
          title: res.data,
          icon: "none"
        })
        this.setData({
          list: res.pageNumber == 1 ? res.data : this.data.list.concat(res.data),
          "content.pageNumber": res.pageNumber + 1,
          "content.pageSize": res.pageSize,
          "content.pageTotal": res.pageTotal,
          "total": res.total,
        })
        try {
          this.selectAllComponents("#Filtrate").forEach(v => v.onCancel())
        } catch (error) {}
        if (init) _Http.basic({
          "id": 20231017162504,
          content
        }).then(res1 => {
          console.log("图标", res1)
          this.initChart(res1.data)
        })
      })
    },
    initChart(data) {
      let projecttype = [...new Set(data.map(v => getApp().globalData.Language.getMapText(v.key)))]
      let source = [
        ['product'].concat(projecttype),
      ];

      data.forEach(v => {
        if (!source.find(item => item[0] === getApp().globalData.Language.getMapText(v.datetype))) {
          source.push([getApp().globalData.Language.getMapText(v.datetype)])
        }
        let index = source.findIndex(item => item[0] === getApp().globalData.Language.getMapText(v.datetype));
        source[index].push(v.value);
      })
      if (this.data.types.length == 0) {
        let types = projecttype.map(v => {
          return {
            remarks: v,
            value: v,
          }
        })
        types.unshift({
          remarks: '全部',
          value: ''
        })
        this.setData({
          types
        })
      }
      let that = this,
        countDown = null,
        datetypes = [...new Set(data.map(v => v.datetype))];

      function changeDateType(params) {
        clearTimeout(countDown)
        countDown = setTimeout(() => {
          if (datetypes[params.dataIndex] === that.data.content.dateType) return;
          that.setData({
            "content.dateType": datetypes[params.dataIndex],
            "content.where.dateType": datetypes[params.dataIndex],
            "content.pageNumber": 1,
          })
          that.getList();
        }, 200)
      }
      let option = {
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            changeDateType(params[0]);
            let filteredParams = params.filter(item => item.value !== 0);
            if (filteredParams.length === 0) return '';
            let tooltipText = `${params[0].axisValue}\n`;
            filteredParams.forEach((item, index) => {
              if (item.value[index + 1] != 0) {
                tooltipText += `${item.marker} ${item.dimensionNames[index + 1]}: ${item.value[index + 1]}\n`;
              }
            });
            return tooltipText;
          }
        },
        dataset: {
          source
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value'
        },
        series: projecttype.map(() => ({
          type: 'bar',
          barMaxWidth: 30
        }))
      };
      this.chartComponent = this.selectComponent('#mychart');
      this.chartComponent.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
          width,
          height,
          devicePixelRatio: dpr
        });
        chart.setOption(option);
        return chart;
      });
    },
    changeDate({
      detail
    }) {
      this.setData({
        "content.enddate": detail
      })
      this.getList(true)
    },
    changeType1({
      detail
    }) {
      console.log(detail)
      this.setData({
        "content.where.tradingstatus": detail,
      })
      this.getList(true)
    },
    changeType2({
      detail
    }) {
      this.setData({
        "content.where.type": detail,
      })
      this.getList(true)
    },
    changeType3({
      detail
    }) {
      this.setData({
        "content.where.grade": detail,
      })
      this.getList(true)
    },
  }
})