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],
      where: {
        dateType: "15-30天",
        projecttype: ""
      },
      pageNumber: 1,
      pageSize: 20,
      pageTotal: 1
    },
    types: [],
    filterShow: false,
    filtratelist: [{
      label: "项目状态",
      index: null,
      showName: "value", //显示字段
      valueKey: "status", //返回Key
      selectKey: "value", //传参 代表选着字段 不传参返回整个选择对象
      value: "", //选中值
      type: "checkbox",
      list: [{
        value: "跟进中"
      }, {
        value: "已成交"
      }, {
        value: "已失败"
      }, {
        value: "已结案"
      }]
    }]
  },
  methods: {
    async getList(init = false) {
      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": 20231019095904,
        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"
        })
        res.data = res.data.map(v => {
          v.signamount_due = CNY(v.signamount_due)
          return v
        })
        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": 20231019095804,
          content
        }).then(res1 => {
          console.log("图标", res1)
          this.initChart(res1.data)
        })
      })
    },
    initChart(data) {
      let projecttype = [...new Set(data.map(v => getApp().globalData.Language.getMapText(v.projecttype)))]
      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.split("-")[0],
          }
        })
        types.unshift({
          remarks: '全部',
          value: ''
        })
        console.log("types", types)
        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.where.dateType) return;
          that.setData({
            "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)
    },
    clickOpen() {
      this.setData({
        filterShow: true
      })
    },
    /* 处理筛选 */
    handleFilter({
      detail
    }) {
      if (detail.name == "confirm") {
        this.setData({
          "content.where.status": detail.status
        })
        this.selectComponent('#Filtrate1').setShowArrText(detail.status)
        this.getList(true)
      } else if (detail.name == 'reset') {
        this.setData({
          "content.where.status": []
        })
        this.selectComponent('#Filtrate1').setShowArrText([])
        this.getList(true)
      }
    },
    changeType2({
      detail
    }) {
      this.setData({
        "content.where.projecttype": detail,
      })
      this.getList(true)
    },
  }
})