/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：主页首页
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		admin		   2024-02-20	   1.00		   	  首页
 *******************************************************************************/

const app = getApp()
const api = require('@/utils/api.js');
const config = require('@/config/config.js');
const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 语言包
    $t: app.globalData.lang,
    swiperList: [
      {
        title: '本月数据',
        // 成交额
        transactionAmount: 0,
        // 收款额
        collectionAmount: 0,
        // 背景
        background: 'linear-gradient(105.85deg, #F0F5FF -56.04%, #0E23E1 96.41%)'
      },
      {
        title: '本周数据',
        // 成交额
        transactionAmount: 0,
        // 收款额
        collectionAmount: 0,
        // 背景
        // background:'linear-gradient(105.85deg, #C1D1ED -56.04%, #507BCC 96.41%)'
        background: 'linear-gradient(105.85deg, #C1D1ED -56.04%, #2b63cc 96.41%)'
      }
    ],
    statusHeight: 0, // 状态栏高度
    dateType: 'week',// week本周， month本月
    swiperIndex: 0,
    imageUrl: config.image_url + '/static/img/',
    advertisementList: [], // 广告数据
    // 分页flg
    pageFlag: false,
    comMenuList: [],// 常用功能
    companyName: null,
    // 成交额
    transactionAmount: 0,
    // 收款额
    collectionAmount: 0,
    //功能分类-大功能模块-页面
    functionItems: [
    ],
    //  模块名称
    functionRegionItems: [
      {
        diamondflg: false,
        titlesrc: 'home-add-order.png',
        cardname: '采购管理',
        background: 'linear-gradient(200.98deg, #FFFFFF -13.39%, #A1CDFF 100%)',
        arrowBackground: '#A9CCFF',
        color: '#3785E5',
        image: 'pur-icon',
        items: [
          { code: 'pur-order', url: '/package-purchase/pages/purchase-order/purchase-order', title: '采购订单', color: '#7AADDF' },
          { code: 'pur-enter', url: '/package-purchase/pages/purchase-receipt/purchase-receipt', title: '采购入库', color: '#7AADDF' }
        ],
      },
      {
        diamondflg: true,
        titlesrc: 'home-customer-data.png',
        cardname: '销售管理',
        background: 'linear-gradient(224.58deg, #FFFFFF -11.05%, #FFC9C2 100%)',
        arrowBackground: '#FDD4C7',
        color: '#CC5E64',
        image: 'sale-icon',
        items: [
          { code: 'order', url: '/package-sales/pages/order-billing/order-billing', title: '订单开单', color: '#E6725F' },
          { code: 'order-out', url: '/package-sales/pages/sales-outbound/sales-outbound', title: '销售出库', color: '#E6725F' }
        ],
      },
      {
        diamondflg: false,
        titlesrc: 'home-receive-customer.png',
        background: 'linear-gradient(225.36deg, #FFFFFF -10.7%, #F2D1AC 100%)',
        arrowBackground: '#EABB92',
        color: '#D27E52',
        cardname: '存货管理',
        image: 'ivt-icon',
        items: [
          { code: 'entry-handle', url: '/package-inventory/pages/warehousing-processing/warehousing-processing', title: '入库办理', color: '#EEA05B' },
          { code: 'out-handle', url: '/package-inventory/pages/outbound-processing/outbound-processing', title: '出库办理', color: '#EEA05B' }
        ],
      },
      {
        diamondflg: false,
        titlesrc: 'home-customer-payment.png',
        cardname: '客户管理',
        background: 'linear-gradient(200.98deg, #FFFFFF -13.39%, #D7DFFF 100%)',
        arrowBackground: '#C3D0FF',
        color: '#606EB2',
        image: 'customer-icon',
        items: [
          { code: 'customer', url: '/package-basic-data/pages/customer-list/customer-list', title: '客户档案', color: '#606EB2' },
          { code: 'cus-follow', url: '/package-basic-data/pages/customer-reception/customer-reception', title: '客户跟进', color: '#606EB2' }
        ],
      },
      {
        diamondflg: true,
        titlesrc: 'home-customer-payment.png',
        cardname: '资金管理',
        background: 'linear-gradient(223.67deg, #FFFFFF -15.06%, #FFF5E2 100%)',
        arrowBackground: '#ECD1A7',
        color: '#A5814A',
        image: 'fin-icon',
        items: [
          { code: 'receipt', url: '/package-accounts-manage/pages/receipt/receipt', title: '收款单', color: '#A5814A' },
          { code: 'payment', url: '/package-accounts-manage/pages/payment-order/payment-order', title: '付款单', color: '#A5814A' }
        ],
      },
      {
        diamondflg: false,
        titlesrc: 'home-customer-payment.png',
        cardname: '系统管理',
        background: 'linear-gradient(225.36deg, #FFFFFF -10.7%, #C2DFFF 100%)',
        arrowBackground: '#B7D6FF',
        color: '#89B9FF',
        image: 'analysis-icon',
        items: [
          { code: 'goods-attr', url: '/package-basic-data/pages/product-attribute/product-attribute', title: '商品属性', color: '#89B9FF' },
          { code: 'goods', url: '/package-basic-data/pages/product-file/product-file', title: '商品档案', color: '#89B9FF' }
        ],
      },
    ],
    // 功能模块组件高度和宽度
    funcViewHeight: 0,
    funcViewWidth: 0,
    freeVersionFlag: true,
  },
  /**
  * @desc : 切换公司
  * @author : 周兴
  * @date : 2024/4/1
  */
  changeCp() {
    wx.navigateTo({
      url: '/pages/company/company',
    })
  },
  /**
  * @desc : 点击跳转到对应的链接
  * @author : 周兴
  * @date : 2024/4/1
  */
  handClickImage(e) {
    let url = e.currentTarget.dataset.item.activityUrl
    let toUrl = null;
    if (url) {
      // 看下是否包括http,http就跳转到product页面
      if (url.indexOf('http') >= 0) {
        toUrl = '/pages/product/product'
      } else {
        // 说明是跳本产品
        toUrl = url;
      }
      wx.navigateTo({
        url: toUrl,
        success: function (res) {
          res.eventChannel.emit('url', url);
        }
      })
    }
  },
  /**
  * @desc : 查询应收和收款
  * @author : 周兴
  * @date : 2024/4/3
  */
  getReceivableAccountSum(dateType) {
    let now = new Date();
    let params = {
      staffId: app.globalData.user.staffId,
    }
    // 本周
    if (dateType == 'week') {
      params['accDateStart'] = now.getWeekFirstDay()
      params['accDateEnd'] = now.getWeekLastDay()
    } else if (dateType == 'month') {
      params['accDateStart'] = now.getFirstDateStr()
      params['accDateEnd'] = now.getLastDateStr()
    }
    let service = app.globalData['accountService']
    api.request(service.prefix + service.getReceivableAccountSum, 'POST', params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        console.log('eee', res.data);
        let swiperList = this.data.swiperList
        if (res.data && res.data.data && swiperList) {
          let data = res.data.data
          if (dateType == 'week') {
            swiperList[1]['transactionAmount'] = data.receivable ? data.receivable : 0;
            swiperList[1]['collectionAmount'] = data.receipt ? data.receipt : 0;
          } else if (dateType == 'month') {
            swiperList[0]['transactionAmount'] = data.receivable ? data.receivable : 0;
            swiperList[0]['collectionAmount'] = data.receipt ? data.receipt : 0;
          }
          this.setData({
            swiperList: swiperList
          })
        }
        // if (res.data && res.data.data) {
        //   let advertisementList = res.data.data
        //   advertisementList.forEach(it => {
        //     it.adPath = config.image_url + it.adPath
        //   })
        //   this.setData({
        //     advertisementList: advertisementList
        //   })
        // }
      }
    });
  },
  /**
  * @desc : 查询广告
  * @author : 周兴
  * @date : 2024/4/1
  */
  getAdvertisement() {
    let params = {
      appCode: Constants.APP_CODE,
      flgBanner: true,
      gradeCode: app.globalData.company.gradeCode
    }
    let service = app.globalData['activityService']
    api.request(service.prefix + service.selectByCond, 'POST', params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        if (res.data && res.data.data) {
          let advertisementList = res.data.data
          advertisementList.forEach(it => {
            if (it.annexPaths && it.annexPaths.length > 0) {
              it.adPath = config.image_url + it.annexPaths[0].url
            }
          })
          this.setData({
            advertisementList: advertisementList,
          })
        }
      }
    });
  },
  /**
  * @desc : 查询常用功能以及频率高的功能
  * @author : 周兴
  * @date : 2024/3/30
  */
  getComMenu() {
    let staffId = app.globalData.user.staffId;
    if (!staffId) {
      return;
    }
    let params = {
      staffId: staffId,
      appCode: Constants.APP_CODE,
      gradeCode: app.globalData.company.gradeCode
    }
    let service = app.globalData['comMenuService']
    api.request(service.prefix + service.selectMenu, 'POST', params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        /**
         * 过滤Vip标识
         */
        let comMenuList = res.data.data
        const menus = app.globalData.menus
        comMenuList.forEach(res => {
          const comMenus = menus.filter(menu => menu.menuUuid === res.menuUuid)
          res.isVip = comMenus[comMenus.length - 1].isVip
        })
        // 如果标准版把销售出库 修改为订单开单
        // if (app.globalData.company.gradeCode == Constants.gradeCode.STD) {
        //   let filters = comMenuList.filter(it => it.objectCode == 'order-out');
        //   if (filters && filters.length > 0) {
        //     filters[0].menuName = '订单开单'
        //     filters[0].name = '订单开单'
        //   }
        //   // 出库明细表修改为销售明细表
        //   filters = comMenuList.filter(it => it.objectCode == 'out-detail-report');
        //   if (filters && filters.length > 0) {
        //     filters[0].menuName = '销售明细表'
        //     filters[0].name = '销售明细表'
        //   }
        // }
        // 增加全部列表
        let allMenu = {
          menuUuid: '-1',
          menuName: '全部应用',
          objectIcon: 'all_app.png'
        }
        comMenuList.push(allMenu);
        this.setData({
          comMenuList: comMenuList,
        })
      }
    });
  },
  /**
   * @desc : 跳转到功能页面
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  toApp(e) {
    let item = e.currentTarget.dataset.item
    console.log('item', item);
    // 如果点击全部应用跳转到应用页面
    if (item.menuUuid == '-1') {
      wx.reLaunch({
        url: '/pages/index/index',
      })
      return
    }

    let hasRightFlag = false;
    let menuUuid = null;
    let guideUrl = null;
    let menuList = app.globalData.menus
    if (menuList && menuList.length > 0) {
      // 查看该功能是否有权限
      let filters = menuList.filter(it => it.objectCode == (item.objectCode || item.code));
      if (filters && filters.length > 0) {
        menuUuid = filters[0].menuUuid
        guideUrl = filters[0].guideUrl
        hasRightFlag = true;
      }
    }
    if (!hasRightFlag) {
      util.showToast('没有该功能权限');
      return;
    }
    let companyVip = app.globalData.company.vip
    if (e.currentTarget.dataset.item.isVip) {
      if (!companyVip) {
        util.showToast('此功能为Vip功能!')
        return;
      }
    }
    // 打开页面
    if (item.objectPath || item.url) {
      wx.navigateTo({
        url: item.objectPath ? item.objectPath : item.url,
        success: function (res) {
          res.eventChannel.emit('params', { formMode: 'index', menuUuid: menuUuid, guideUrl: guideUrl })
        }
      })
    }
  },
  // 初始化tauchSwiper
  tauchSwiper(name) {
    let list = this.data[name];
    for (let i = 0; i < list.length; i++) {
      // Math.abs(x) 函数返回指定数字 “x“ 的绝对值
      list[i].zIndex = parseInt(list.length / 2) + 1 - Math.abs(i - parseInt(list.length / 2))
      list[i].mLeft = parseInt(list.length / 2) - i
    }
    this.setData({
      swiperList: list
    })
  },
  // tauchSwiper触摸开始
  tauchStart(e) {
    this.setData({
      tauchStart: e.touches[0].pageX
    })
  },
  // tauchSwiper计算方向
  tauchMove(e) {
    this.setData({
      direction: e.touches[0].pageX - this.data.tauchStart > 0 ? 'right' : 'left'
    })
  },
  // tauchSwiper计算滚动
  tauchEnd(e) {
    let direction = this.data.direction;
    let list = this.data.swiperList;
    if (direction == 'right') {
      let mLeft = list[0].mLeft;
      let zIndex = list[0].zIndex;
      for (let i = 1; i < list.length; i++) {
        list[i - 1].mLeft = list[i].mLeft
        list[i - 1].zIndex = list[i].zIndex
      }
      list[list.length - 1].mLeft = mLeft;
      list[list.length - 1].zIndex = zIndex;
      this.setData({
        swiperList: list
      })
    } else {
      let mLeft = list[list.length - 1].mLeft;
      let zIndex = list[list.length - 1].zIndex;
      for (let i = list.length - 1; i > 0; i--) {
        list[i].mLeft = list[i - 1].mLeft
        list[i].zIndex = list[i - 1].zIndex
      }
      list[0].mLeft = mLeft;
      list[0].zIndex = zIndex;

      this.setData({
        swiperList: list
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function name(params) {
    // 获取常用菜单
    this.getComMenu();
    // 查询应收和收款额(本周) 本周数据点击首页就能刷新
    this.getReceivableAccountSum('week');
    // 查询应收和收款额(本月)
    this.getReceivableAccountSum('month');
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const gradeCode = app.globalData.company.gradeCode;
    console.log('gradeCode', gradeCode);
    this.setData({
      freeVersionFlag: gradeCode === 'STD'
    })
    // 如果企业还有15天到期给出提示信息
    let company = app.globalData.company;
    if (company && company.endDate) {
      let endD = new Date(company.endDate);
      // 服务器的日期为准
      let nowD = new Date(app.globalData.nowDate).addDays(Constants.CP_ALERT_TIME);
      if (endD < nowD) {
        util.showToast('企业即将到期，到期日期为【' + company.endDate + '】', 5000);
      }
    }
    // // 判断当前用户是否到期 标准版
    if (app.globalData.company.gradeCode == Constants.gradeCode.STD
      && !app.globalData.user.flgInit
      && company
      && company.userEndDate) {
      let endD = new Date(company.userEndDate);
      // 服务器的日期为准
      let nowD = new Date(app.globalData.nowDate).addDays(Constants.CP_ALERT_TIME);
      if (endD < nowD) {
        util.showToast('企业即将到期，到期日期为【' + company.userEndDate + '】', 5000);
      }
    }
    let res = wx.getSystemInfoSync();
    let statusHeight = res.statusBarHeight
    this.setData({
      statusHeight: statusHeight * 2 + 20
    })
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      }
    })
    this.setData({
      companyName: app.globalData.company.cpName
    })
    // 本周本月数据
    this.tauchSwiper('swiperList');
    // 查询广告数据
    this.getAdvertisement();
    // options 中的 scene  todo.. 先不要删除日志
    console.log("homepage---", options.scene);
    if (options.scene) {
      // var scene = options.scene
      var openid = decodeURIComponent(options.scene)
      console.log("homepage---", openid);
      // let openid = scene.s
      // console.log("homepage---", openid);
      // 邀请员工的确认
      wx.navigateTo({
        url: '/package-basic-data/pages/staff/detail/detail',
        events: {
          // 回调后，在这里给页面赋值
          bandData: function (e) {
          }
        },
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
          res.eventChannel.emit('params', { formType: openid, formMode: Constants.formMode.index })
        }
      })
    } else if (options.buy) {
      wx.navigateTo({
        url: '/package-basic-data/pages/staff/staff',
        success: function (res) {
          res.eventChannel.emit('params', { formMode: Constants.formMode.index })
        }
      })
    }

    // 获取功能卡片模块高度 以便设置水印蒙版高度
    const that = this;
    let query = wx.createSelectorQuery();
    query.select('.func').boundingClientRect(rect => {
      let height = rect.height;
      let width = rect.width;
      that.setData({
        funcViewWidth: width,
        funcViewHeight: height
      })
      that.drawWatermark('watermarkCanvas', '专业版功能', width * 2, height * 2)
    }).exec();

    //小程序推送消息传过来的值 pages/login/login?loginType=1&otherParam=值
    // loginType 
    // 1 客户跟进通知-进入客户跟进详情  2 客户任务通知  3 客户流失提醒  4 审批任务通知  5 工具栏跳转客户跟进
    // 6 工具栏跳转订单开单  7 工具栏跳客户详细 8 客户跟进通知-进入接待详情 9 销售退货通知跳转 10上样检查跳转

  },

  /** 
   * 水印配置
   * @author 刘尧
   * @date 2024.5.30
   * */
  drawWatermark(canvasName, watermarkText, width, height) {
    const ctx = wx.createCanvasContext(canvasName); // 创建 canvas 上下文  
    // 水印配置  
    const watermarkConfiguration = {
      watermarkText: watermarkText, // 水印文本  
      watermarkFontSize: 14, // 水印字体大小  
      watermarkColor: '#aaa', // 水印字体颜色  
      watermarkAngle: -25, // 水印倾斜度数  
      watermarkOpacity: 0.5, // 水印透明度  
      watermarkInterval: 50, // 水印之间的间隔  
    };
    const canvasWidth = width; // canvas 宽度  
    const canvasHeight = height; // canvas 高度  
    // 设置 canvas 样式和全局属性  
    ctx.setGlobalAlpha(watermarkConfiguration.watermarkOpacity);
    ctx.setFontSize(watermarkConfiguration.watermarkFontSize);
    ctx.setFillStyle(watermarkConfiguration.watermarkColor);
    // 计算单个水印文本的宽度和高度  
    const textWidth = ctx.measureText(watermarkConfiguration.watermarkText).width;
    const textHeight = watermarkConfiguration.watermarkFontSize;
    // 计算可以放置水印的行数和列数  
    const numColumns = Math.floor(canvasWidth / (textWidth + watermarkConfiguration.watermarkInterval));
    const numRows = Math.floor(canvasHeight / (textHeight + watermarkConfiguration.watermarkInterval));
    // 绘制水印  
    for (let i = 0; i < numRows; i++) {
      for (let j = 0; j < numColumns; j++) {
        // 计算水印位置  
        const x = j * (textWidth + watermarkConfiguration.watermarkInterval);
        const y = i * (textHeight + watermarkConfiguration.watermarkInterval);
        // 保存当前状态  
        ctx.save();
        // 旋转坐标系以绘制倾斜的水印  
        ctx.translate(x + textWidth / 2, y + textHeight / 2);
        ctx.rotate(watermarkConfiguration.watermarkAngle * Math.PI / 180);
        ctx.fillText(watermarkConfiguration.watermarkText, -textWidth / 2, -textHeight / 2);
        // 恢复之前保存的状态  
        ctx.restore();
      }
    }

    // 绘制到 canvas 上  
    ctx.draw();
  },
  /**
   * 水印点击事件
   * @author 刘尧
   * @date 2024.5.30
   */
  masksClick() {
    wx.navigateTo({
      url: '/package-basic-data/pages/register/product-detail/product-detail',
    })
  },
})

