// package5/pages/report/index.js

// import * as echarts from '../../../pages/ec-canvas/echarts.min';
import { getOpData } from '../echarts-data.js'
const api = require('../../../utils/api.js');
const util = require('../../../utils/util.js')
const app = getApp()
const Constants = require('../../../utils/Constants.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    createTimeType: {
        text: "本月",
        value: 3
      },
      csmAnalysisHome: {
        designCsmCount: 1,
        orderCsmCount: 0,
        csmCount: 0,
        offerCsmCount: 3,
        offerAmount: 128242.62,
        orderRate: 0,
        agreedMmeasureCount: 0,
        offerRate: 0,
        completeMmeasureCount: 0
      },
      currentDate: 1706679819364,
      ec: {},
      lastDate: {
        text: "本月",
        value: 3
      },
      month: [
        "2024-01-01",
        "2024-01-31"
      ],
      monthFlag: false,
      monthName: "2024年1月",
      monthOnChoose: 1706679819264, 
    option1: [
      {
        "text": "本日",
        "value": 1
      },
      {
        "text": "本周",
        "value": 2
      },
      {
        "text": "本月",
        "value": 3
      },
      {
        "text": "本年",
        "value": 5
      },
      {
        "text": "自定义",
        "value": 5
      }
    ],
    orderAnalysis: {
      "outAmount": 64759,
      "activityAmount": 640362.4,
      "rejectAmount": -2997,
      "kpiRate": 0,
      "csmUnitPrice": 75515,
      "mmRate": 0,
      "kpiAmount": 0,
      "csmCount": 13,
      "yyRate": -70.35,
      "specsAmount": 265492,
      "sumAmount": 981695
    },
    orgFlag: false,
    orgIds: [],
    orgNames: null,
    repayAnalysis: {
      "repayRate": 0,
      "mmRate": -31.3,
      "kpiAmount": 0,
      "debtCount": 12,
      "repayAmount": 179614,
      "yyRate": 0,
      "debtAmount": 802551
    },
    value1: 3, 
    csmFromOrder: {
      "avgAmount": 327231.67,
      "fromCount": 3,
      "items": [
        {
          "customerQty": 11,
          "fromName": "自然客流",
          "kpiIndex": 1,
          "orderAmount": 671292,
          "rate": 68.38
        },
        {
          "customerQty": 1,
          "fromName": "选用1",
          "kpiIndex": 2,
          "orderAmount": 164807,
          "rate": 16.79
        },
        {
          "customerQty": 1,
          "fromName": "自然进店",
          "kpiIndex": 3,
          "orderAmount": 145596,
          "rate": 14.83
        }
      ],
      "sumAmount": 981695
    },
    spuAnalysis: {
      "items": [
        {
          "countRate": 79.9,
          "kpiIndex": 1,
          "specsName": "智能马桶",
          "sumAmount": 781009.7,
          "sumCount": 155
        },
        {
          "countRate": 5.67,
          "kpiIndex": 2,
          "specsName": "坐便器",
          "sumAmount": 36333,
          "sumCount": 11
        },
        {
          "countRate": 13.92,
          "kpiIndex": 3,
          "specsName": "龙头类",
          "sumAmount": 34897.7,
          "sumCount": 27
        },
        {
          "countRate": 0.52,
          "kpiIndex": 4,
          "specsName": "淋浴房",
          "sumAmount": 1,
          "sumCount": 1
        },
        {
          "countRate": 0.52,
          "kpiIndex": 4,
          "specsName": "定制淋浴房",
          "sumAmount": 1,
          "sumCount": 1
        }
      ],
      "sumAmount": 852241.4,
      "sumCount": 194
    },
    indexOrgOrder: {
      "avgAmount": 981695,
      "items": [
        {
          "kpiIndex": 1,
          "kpiOrderAmount": null,
          "kpiOrderRate": 0,
          "orderAmount": 981695,
          "orgName": "北海富安居店"
        }
      ],
      "orgCount": 1,
      "sumAmount": 981695
    },
    indexOrgRepay: {
      "avgAmount": 179613,
      "items": [
        {
          "kpiIndex": 1,
          "kpiRepayAmount": null,
          "kpiRepayRate": 0,
          "orgName": "北海富安居店",
          "repayAmount": 179613
        }
      ],
      orgCount: 1,
      sumAmount: 179613
    },
    indexStaffOrder:  {
      "avgAmount": 196339,
      "items": [
        {
          "kpiIndex": 1,
          "kpiOrderAmount": null,
          "kpiOrderRate": 0,
          "orderAmount": 737252,
          "staffName": "无库无ERP00001"
        },
        {
          "kpiIndex": 2,
          "kpiOrderAmount": null,
          "kpiOrderRate": 0,
          "orderAmount": 194122,
          "staffName": "东科-于继渤"
        },
        {
          "kpiIndex": 3,
          "kpiOrderAmount": null,
          "kpiOrderRate": 0,
          "orderAmount": 19656,
          "staffName": "张德亮"
        },
        {
          "kpiIndex": 4,
          "kpiOrderAmount": null,
          "kpiOrderRate": 0,
          "orderAmount": 17665,
          "staffName": "石静"
        },
        {
          "kpiIndex": 5,
          "kpiOrderAmount": null,
          "kpiOrderRate": 0,
          "orderAmount": 13000,
          "staffName": "王英杰"
        }
      ],
      "staffCount": 5,
      "sumAmount": 981695
    },
    indexStaffRepay: {
      "avgAmount": 89806.5,
      "items": [
        {
          "kpiIndex": 1,
          "kpiRepayAmount": null,
          "kpiRepayRate": 0,
          "repayAmount": 177616,
          "staffName": "东科-于继渤"
        },
        {
          "kpiIndex": 2,
          "kpiRepayAmount": null,
          "kpiRepayRate": 0,
          "repayAmount": 1997,
          "staffName": "无库无ERP00001"
        }
      ],
      staffCount: 2,
      sumAmount: 179613
    }
  },

  dateClick(e){
    if(e.detail === 0){
      this.selectComponent("#month-components").toggle(true)  
      this.dropdowncommit({currentTarget:{dataset:{type:'month'}}})
    }else{
      this.getReportData()
    }
  },
 /**
   * @desc : 日期组件后的回调
   * @author : 于继渤
   * @date : 2022/5/24 12:16
   */
  dateCommit(e) {
    let dateType = e.detail.dateType
    if (dateType === 'accountdate') {
      if(e.detail.dateDefault.text === '自定义'){
        this.setData({
          value1: 0,
        })
      }
      if(e.detail.dateDefault.text === '本日'){
        this.setData({
          value1: 1,
        })
      }
      if(e.detail.dateDefault.text === '本周'){
        this.setData({
          value1: 2,
        })
      }
      if(e.detail.dateDefault.text === '本月'){
        this.setData({
          value1: 3,
        })
      }
      let data = e.detail.date
      console.log(e)
      this.setData({
        month: data,
        createTimeType: e.detail.dateDefault
      })
      this.selectComponent('#create-time-type').toggle();
    }
     this.getReportData()
  },

  /** 去详细 */
  toDetail(e){
    wx.navigateTo({
      url: '/package-business-analysis/pages'+e.currentTarget.dataset.url +'?orgIds='+encodeURIComponent(JSON.stringify(this.data.orgIds))+ '&orgNames=' + encodeURIComponent(JSON.stringify(this.data.orgNames))
      +'&dateType='+this.data.value1 + '&date='+this.data.month
    })
  },

  formatDate(value) {
    var time = new Date(value);
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    return year + "年" + month + "月"
  },







  dropdowncommit(e) {
    this.setData({
      [e.currentTarget.dataset.type + 'Flag']: true
    })
  },

  /** 下拉多选关闭 */
  muticloseAll(e) {
    this.setData({
      orgFlag: false
    })
    this.selectComponent("#org-components").toggle()
  },

  /** 下拉多选确定 */
  mutiSearchAll(e) {
    this.setData({
      orgIds: e.detail.idList,
      orgNames: e.detail.names,
      orgFlag: false
    })
    this.selectComponent("#org-components").toggle(false)
    this.getReportData()
  },

  onShow() {
    this.echartsKhlyfb = this.selectComponent("#echarts-khlyfb")
    this.echartsCpfb = this.selectComponent("#echarts-cpfb")

    this.echartsBmcj = this.selectComponent("#echarts-bmcj")
    this.echartsBmsk = this.selectComponent("#echarts-bmsk")
    
    this.echartsYwycj = this.selectComponent("#echarts-ywycj")
    this.echartsYwysk = this.selectComponent("#echarts-ywysk")

  },

  /** 设置echarts */
  setEcharts(name, { data, labelKey, valueKey, type }) {
    this[name].init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      });
      canvas.setChart(chart);
      chart.setOption(getOpData(data, labelKey, valueKey, type));
      return chart;
    });
  },
  /** 根据月份查出第一天和最后一天 参数是时间戳*/
  getBeginDateAndEndDate(timestamp) {
    // let date = new Date(timestamp)
    // let year = date.getFullYear();
    // let month = date.getMonth() + 1;
    // let yearAndMonth = year + '-' + (month>=10?month:'0'+month);
    // return { beginDate:yearAndMonth+'-01',endDate:yearAndMonth +'-'+ new Date(year,month,0).getDate()}


    let month = this.data.month
    let monthStart = month[0] ? month[0]  :''
    let monthEnd = month[1] ? month[1]  :''
    if(month && month[0] && (month[0].indexOf('/') != -1)){
     monthStart =   month[0].replaceAll('/','-')
    }
    if(month && month[1] && (month[1].indexOf('/') != -1)){
      monthEnd =   month[1].replaceAll('/','-')
     }
    return { beginDate:monthStart,endDate:monthEnd}
  },
  /** 查询所有报表信息 */
  /** 查询页面展示的所有 */
  getReportData() {
    let params = {
      orderAnalysis: Object.assign(this.getBeginDateAndEndDate(this.data.month),{ userId: app.globalData.user.userId, cpId: app.globalData.user.ascpId, orgIds: this.data.orgIds, type: 'f_report_s001_order_analysis_home' ,dateType:this.data.value1}),
      repayAnalysis: Object.assign(this.getBeginDateAndEndDate(this.data.month),{ userId: app.globalData.user.userId, cpId: app.globalData.user.ascpId, orgIds: this.data.orgIds, type: 'f_report_s001_repay_analysis' ,dateType:this.data.value1}),

      csmAnalysisHome: Object.assign(this.getBeginDateAndEndDate(this.data.month),{userId: app.globalData.user.userId,cpId: app.globalData.user.ascpId, orgIds: this.data.orgIds, type: 'f_report_s001_csm_analysis_home',dateType:this.data.value1 }),

      csmFromOrder: Object.assign(this.getBeginDateAndEndDate(this.data.month),{userId: app.globalData.user.userId,cpId: app.globalData.user.ascpId, orgIds: this.data.orgIds, type: 'f_report_s001_csm_from_order' ,dateType:this.data.value1}),
      spuAnalysis: Object.assign(this.getBeginDateAndEndDate(this.data.month),{userId: app.globalData.user.userId,cpId: app.globalData.user.ascpId, orgIds: this.data.orgIds, type: 'f_report_s001_spu_analysis' ,dateType:this.data.value1}),
      
      indexOrgOrder: Object.assign(this.getBeginDateAndEndDate(this.data.month),{ userId: app.globalData.user.userId,cpId: app.globalData.user.ascpId, orgIds: this.data.orgIds, type: 'f_report_s001_index_org_order' ,dateType:this.data.value1}),
      indexOrgRepay: Object.assign(this.getBeginDateAndEndDate(this.data.month),{ userId: app.globalData.user.userId,cpId: app.globalData.user.ascpId, orgIds: this.data.orgIds, type: 'f_report_s001_index_org_repay' ,dateType:this.data.value1}),
      indexStaffOrder: Object.assign(this.getBeginDateAndEndDate(this.data.month),{ userId: app.globalData.user.userId,cpId: app.globalData.user.ascpId, orgIds: this.data.orgIds, staffIds:[], type: 'f_report_s001_index_staff_order' ,dateType:this.data.value1}),
      indexStaffRepay: Object.assign(this.getBeginDateAndEndDate(this.data.month),{ userId: app.globalData.user.userId,cpId: app.globalData.user.ascpId, orgIds: this.data.orgIds, staffIds:[], type: 'f_report_s001_index_staff_repay' ,dateType:this.data.value1}),
    }
    api.request(Constants.WX_REPORT + 'select_report_batch', 'POST', params).then(res => {
      if (res.data.code === 200) {

        this.setData({
          orderAnalysis: res.data.data.orderAnalysis,
          repayAnalysis: res.data.data.repayAnalysis,
          csmAnalysisHome:res.data.data.csmAnalysisHome,
          /** 图形 */
          csmFromOrder:Object.assign(res.data.data.csmFromOrder,{items:res.data.data.csmFromOrder.items.slice(0,8)}),
          spuAnalysis:Object.assign(res.data.data.spuAnalysis,{items:res.data.data.spuAnalysis.items.slice(0,8)}),

          indexOrgOrder: Object.assign(res.data.data.indexOrgOrder,{items:res.data.data.indexOrgOrder.items.slice(0,5)}),
          indexOrgRepay: Object.assign(res.data.data.indexOrgRepay,{items:res.data.data.indexOrgRepay.items.slice(0,5)}),
          indexStaffOrder: Object.assign(res.data.data.indexStaffOrder,{items:res.data.data.indexStaffOrder.items.slice(0,5)}),
          indexStaffRepay: Object.assign(res.data.data.indexStaffRepay,{items:res.data.data.indexStaffRepay.items.slice(0,5)}),
        })
        /** 图形重新渲染 */

        setTimeout(()=>{
          this.setEcharts('echartsKhlyfb', { data: res.data.data.csmFromOrder.items, labelKey: 'fromName', valueKey: 'orderAmount', type: 1 })
          this.setEcharts('echartsCpfb', { data: res.data.data.spuAnalysis.items, labelKey: 'specsName', valueKey: 'sumAmount', type: 1 })
  
          this.setEcharts('echartsBmcj', { data: res.data.data.indexOrgOrder.items, labelKey: 'orgName', valueKey: 'orderAmount', type: 3 })
          this.setEcharts('echartsBmsk', { data: res.data.data.indexOrgRepay.items, labelKey: 'orgName', valueKey: 'repayAmount', type: 3 })
          this.setEcharts('echartsYwycj', { data: res.data.data.indexStaffOrder.items, labelKey: 'staffName', valueKey: 'orderAmount', type: 2 })
          this.setEcharts('echartsYwysk', { data: res.data.data.indexStaffRepay.items, labelKey: 'staffName', valueKey: 'repayAmount', type: 2 })
        },1000)  


      } else {
        console.error("获取报表失败", res)
      }
    })
  },
  onLoad() {
 
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

    let that = this
    //调用刷新时将执行的方法
    that.setData({
      loadingShow: true,
    })
    this.getReportData()
    //隐藏导航条加载动画
    wx.hideNavigationBarLoading();
    setTimeout(function () {
      that.setData({
        loadingShow: false,
      })
      //停止下拉刷新
      wx.stopPullDownRefresh();
    }, 800)

  },
})