/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：我的设置
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		姜永辉		  2024-2-12	    1.00		   	    
 *******************************************************************************/
const api = require('@/utils/api.js');
const config = require('@/config/config.js');
const common = require('@/utils/common.js')
const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const mixins = require('@/mixins/index.js')
import Dialog from '@/dist/dialog/dialog.js';
const app = getApp()

Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    imageUrl: config.image_url + '/static/img/',
    companyName: null,
    staffName: 'null',
    orgName: null,
    waitMenuFlag:true, // 是否显示待办工作区
    // 路由
    routeObjName: 'setting',
    wechatPayService: app.globalData['wechatPayService'],
    companyService: app.globalData['companyService'],
    appCount: 0,
    noticeCount: 0,

    /** 6个切换组件的值 */
    storeHelperValue: 'nearly7days',
    staffHelperValue: 'nearly7days',
    storeOrderRateValue: 'month',
    staffOrderRateValue: 'month',
    storeRepayRateValue: 'month',
    staffRepayRateValue: 'month',

    /** 6个数据源 */
    shopHelper: {},
    staffHelper: {},
    storeOrderRate: {},
    staffOrderRate: {},
    storeRepayRate: {},
    staffRepayRate: {},

    /** 3个加载loading(实际页面上是6个 因为左右切换无法同时显示两个所以3个就够了) */
    filterBlur1: '0',
    filterBlur2: '0',
    filterBlur3: '0',

    /** 2种切换组件的options */
    tagList: [{ name: '今日', id: 'today' }, { name: '近7天', id: 'nearly7days' }, { name: '近30天', id: 'nearly30days' }],
    tagList2: [{ name: '本月', id: 'month' }, { name: '本年', id: 'year' }],

    active: 'store',
    showStoreFlag: true,

    menuBtnInfo: null,
    // 待办工作
    waitMenu: [
      {
        title: '待收款',
        code: 'cus-receipt',
        path: '/package-sales/pages/customer-collection/customer-collection',
        icon: 'order-billing.png',
      },
      {
        title: '待发货',
        code: 'order',
        path: '/package-sales/pages/order-billing/order-billing',
        icon: 'order-billing.png',
      },
      {
        title: '待入库',
        code: 'entry-handle',
        path: '/package-inventory/pages/warehousing-processing/warehousing-processing',
        icon: 'order-billing.png',
      },
      {
        title: '待出库',
        code: 'out-handle',
        path: '/package-inventory/pages/outbound-processing/outbound-processing',
        icon: 'order-billing.png',
      },
    ],
    functionItems_mine: [
      {
        FunctionName: '我的开单',
        FormName: '/package4/pages/order-billing/order-billing',
        ImageUri: '/static/image/order-billing.png',
        PFunctionCode: '01',
        FunctionCode: '0101'
      },
      {
        FunctionName: '我的客户',
        FormName: '/package3/pages/customer/customer',
        ImageUri: '/static/image/customer.png',
        PFunctionCode: '01',
        FunctionCode: '0102'
      },

      {
        FunctionName: '客户收款',
        FormName: '/package4/pages/collection/add/add',
        ImageUri: '/static/image/collection.png',
        PFunctionCode: '01',
        FunctionCode: '0103'
      },
    ]
  },
  /**
  * @desc : 切换公司
  * @author : 周兴
  * @date : 2024/4/1
  */
  changeCp() {
    wx.navigateTo({
      url: '/pages/company/company',
    })
  },
  /**
   * @desc : 跳转到功能页面
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  toApp(e) {
    let item = e.currentTarget.dataset.item
    let hasRightFlag = false;
    let menuUuid = null
    let menuList = app.globalData.menus
    if (menuList && menuList.length > 0) {
      // 查看该功能是否有权限
      let filters = menuList.filter(it => it.objectCode == item.code);
      if (filters && filters.length > 0) {
        menuUuid = filters[0].menuUuid
        hasRightFlag = true;
      }
    }
    if (!hasRightFlag) {
      util.showToast('没有该功能权限');
      return;
    }
    // 打开页面
    if (item.path) {
      wx.navigateTo({
        url: item.path,
        success: function (res) {
          res.eventChannel.emit('params', { formMode: 'index', menuUuid: menuUuid })
        }
      })
    }
  },
  /**
  * @desc : 查询待发货数据
  * @author : 周兴
  * @date : 2024/4/9
  */
  getOrder() {
    let params = {
      appCode: Constants.APP_CODE,
      orderStatusList: ['出库状态-待出库', '出库状态-出库中']
    }
    let service = app.globalData['orderService']
    api.request(service.prefix + service.countOrderByCond, 'POST', params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        let waitMenu = this.data.waitMenu;
        let filters = waitMenu.filter(it => it.code == 'order')
        if (filters && filters.length > 0) {
          filters[0].count = res.data.data;
          this.setData({
            waitMenu: waitMenu
          })
        }
      }
    });
  },
  /**
  * @desc : 查询待收款数据
  * @author : 周兴
  * @date : 2024/4/9
  */
  getWaitReceival() {
    let params = {
      appCode: Constants.APP_CODE,
      amtResidueZeroFlg: true,
      accItemType: '账款类型-应收'
    }
    let service = app.globalData['accountService']
    api.request(service.prefix + service.getReceivableAccountItemCount, 'POST', params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        let waitMenu = this.data.waitMenu;
        let filters = waitMenu.filter(it => it.code == 'cus-receipt')
        if (filters && filters.length > 0) {
          filters[0].count = res.data.data;
          this.setData({
            waitMenu: waitMenu
          })
        }
      }
    });
  },
  /**
  * @desc : 查询待入库数据
  * @author : 周兴
  * @date : 2024/4/9
  */
  getWaitInbound() {
    let params = {
      appCode: Constants.APP_CODE,
    }
    let service = app.globalData['inboundOtherService']
    api.request(service.prefix + service.selectWaitInboundCount, 'POST', params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        let waitMenu = this.data.waitMenu;
        let filters = waitMenu.filter(it => it.code == 'entry-handle')
        if (filters && filters.length > 0) {
          filters[0].count = res.data.data;
          this.setData({
            waitMenu: waitMenu
          })
        }
      }
    });
  },
  /**
  * @desc : 查询待出库数据
  * @author : 周兴
  * @date : 2024/4/9
  */
  getWaitOutbound() {
    let params = {
      appCode: Constants.APP_CODE,
    }
    let service = app.globalData['outboundOtherService']
    api.request(service.prefix + service.selectWaitOutboundCount, 'POST', params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        let waitMenu = this.data.waitMenu;
        let filters = waitMenu.filter(it => it.code == 'out-handle')
        if (filters && filters.length > 0) {
          filters[0].count = res.data.data;
          this.setData({
            waitMenu: waitMenu
          })
        }
      }
    });
  },
  /**
   * @desc : 修改密码跳转
   * @date : 2022/5/12 13:49
   * @author : 姜永辉
   */
  toEditPassword() {
    wx.navigateTo({
      url: './setting/setting',
    })
  },

  /**
  * @desc : 公告跳转
  * @date : 2022/5/12 13:49
  * @author : 姜永辉
  */
  toNotice() {
    wx.navigateTo({
      url: '/package-basic-data/pages/notice/notice',
    })
  },


  /**
  * @desc : 微信支付-随机生成单号
  * @date : 2022/5/12 13:49
  * @author : 姜永辉
  */
  generateOrderNumber() {
    let timestamp = new Date().getTime().toString() // 当前时间戳
    let randomPart = Math.random().toString(36).substring(2, 10) // 随机字符串
    return timestamp + randomPart
  },

  /**
  * @desc : 微信支付
  * @date : 2022/5/12 13:49
  * @author : 姜永辉
  */
  toPay(e) {
    let params = {
      openId: app.globalData.openid,
      paymentSn: this.generateOrderNumber(),
    }
    return this.excute(this.data.wechatPayService, this.data.wechatPayService.unifiedOrder, params).then(res => {
      console.log("toPay", res);
      if (res.data.code === Constants.SUCESS_CODE) {
        var appid = res.data.data.appId
        var timeStamp = res.data.data.timeStamp
        var nonce_str = res.data.data.nonceStr
        var pk = res.data.data.pack
        var paySign = res.data.data.paySign
        //调用微信支付
        wx.requestPayment({
          'appId': appid,
          'timeStamp': timeStamp,
          'nonceStr': nonce_str,
          'package': pk,
          'signType': 'MD5',
          'paySign': paySign,
          'success': function (res) {
            console.log('success', res);

          },
          'fail': function (res) {
            console.log('fail', res);
          },
          'complete': function (res) {
            // console.log(res);
            console.log('complete', res);
          }
        });

      }
    });

  },

  /**
  * @desc : 设置跳转
  * @date : 2022/5/12 13:49
  * @author : 姜永辉
  */
  toSetting() {
    wx.navigateTo({
      url: this.data.route.companySetting.url,
      events: {
        // 回调后，在这里给页面赋值
        bandData: function (e) {
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', { id: 1, formMode: Constants.formMode.edit })
      }
    })
  },

  /**
  * @desc : 退出登录
  * @date : 2022/5/12 13:49
  * @author : 姜永辉
  */
  logout(e) {
    let _this = this
    //提示
    Dialog.confirm({
      message: '您确定要退出系统？',
    }).then(() => {
      let params = {
        openid: app.globalData.openid,
        cpId: null
      }
      return this.excute(_this.data.companyService, _this.data.companyService.updateCurrentCpByWxid, params).then(res => {
        console.log("logout", res);
        if (res.data.code === Constants.SUCESS_CODE) {
          // 调转主页
          wx.reLaunch({
            url: '../../pages/welcome/welcome',
          })
        }
      });

    }).catch(() => {

    });

  },

  /**
  * @desc : 注册商户
  * @date : 2022/5/12 13:49
  * @author : 姜永辉
  */
  register() {
    console.log("this.data.route", this.data.route);
    wx.navigateTo({
      url: this.data.route.companyRegister.url,
      events: {
        // 回调后，在这里给页面赋值
        bandData: function (e) {
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', {})
      }
    })
  },
  /**
    * @desc : 获取用户信息
    * @date : 2022/5/12 13:49
    * @author : 姜永辉
    */
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善用户资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        let user = res.userInfo
        wx.setStorageSync('user', user) //保存用户信息到本地缓存
        this.setData({
          isShowUserName: true,
          userInfo: user,
        })
      },
      fail: res => {

      }
    })
  },
  /**
    * @desc : 小程序测试例子
    * @author : admin
    * @date : 2023年8月21日
    */
  toTestExample(e) {
    wx.navigateTo({
      url: '/package-basic-data/pages/test/test',
    })
  },

  toOtherPage(e) {

    let type = e.currentTarget.dataset.type
    let dateValue = e.currentTarget.dataset.datevalue
    let jumpType = e.currentTarget.dataset.jumptype
    let url = "";
    let param = {};

    let dateObj = {
      today: { text: '本日', value: 1 },
      nearly30days: { text: '近30天', value: 5 },
      nearly7days: { text: '近7天', value: 6 }
    }


    let staffObj = {}

    if (jumpType === 2) {
      staffObj = {
        staffId: app.globalData.user.userId,
        staffNames: app.globalData.user.userName
      }

    }
    let hasrightflg = true
    switch (type) {
      case 1:
        hasrightflg = this.data.orderflg
        url = '/package4/pages/order-billing/order-billing'
        param = { active: 1, date: dateObj[dateValue], receiveStatusParam: [], receiveStatusParamIds: [] }
        break;
      case 2:
        hasrightflg = this.data.customerflg
        url = '/package3/pages/customer/customer'
        param = { active: 0, date: dateObj[dateValue], keyTypeList: [], keyTypeNameList: [] }
        break;
      case 3:
        hasrightflg = this.data.customerflg
        url = '/package3/pages/customer/customer'
        param = { active: 3, date: dateObj[dateValue], keyTypeList: [0, 1], keyTypeNameList: ["客意品类-定制", "客意品类-智能"] }
        break;
      case 4:
        hasrightflg = this.data.orderflg
        url = '/package4/pages/order-billing/order-billing'
        param = { active: 2, date: { text: '自定义', value: -2 }, receiveStatusParam: ['收款状态-未收', '收款状态-部分'], receiveStatusParamIds: [0, 1], type: 2 }
        break;
      case 5:
        hasrightflg = this.data.receivecustomersflg
        url = '/package3/pages/receive-customers/receive-customers'
        param = { active: 1, date: { text: '自定义', value: -2 }, followStatusNameList: [], followStatusList: [], type: 2 }
        break;
      case 6:
        hasrightflg = this.data.orderflg
        url = '/package4/pages/order-billing/order-billing'
        param = { active: 3, date: dateObj[dateValue], receiveStatusParam: [], receiveStatusParamIds: [] }
        break;
      case 7:
        hasrightflg = this.data.receivecustomersflg
        url = '/package3/pages/receive-customers/receive-customers'
        param = { active: 0, date: dateObj[dateValue], followStatusNameList: ['跟进状态-接待', '跟进状态-报备'], followStatusList: [0, 1] }
        break;
      case 8:
        hasrightflg = this.data.receivecustomersflg
        url = '/package3/pages/receive-customers/receive-customers'
        param = { active: 0, date: dateObj[dateValue], followStatusNameList: ['跟进状态-报备'], followStatusList: [0] }
        break;
      case 9:
        hasrightflg = this.data.receivecustomersflg
        url = '/package3/pages/receive-customers/receive-customers'
        param = { active: 0, date: dateObj[dateValue], followStatusNameList: ['跟进状态-接待'], followStatusList: [1] }
        break;
      case 10:
        hasrightflg = this.data.customerflg
        url = '/package3/pages/customer/customer'
        param = { active: 1, date: dateObj.nearly30days }
        break;
    }
    if (hasrightflg) {
      wx.navigateTo({
        url: url + '?frommine=' + JSON.stringify(Object.assign(param, staffObj))
      })
    } else {
      wx.showModal({ title: '提示', content: '没有该功能权限', showCancel: false })
    }
  },
  /**
   * 
   * @param {获取待审条数} options 
   */
  getAppCount() {
    let params = {
      // cpId: app.globalData.user.cpId,
      userId: app.globalData.user.userId,
    }
    api.request(Constants.BPM_WAITING_FOR_APPRAVAL + 'list_count', 'POST', params).then(res => {
      if (res.data.code === 200) {
        this.setData({
          appCount: res.data.data
        })
      }
    })

  },
  /**
 * 
 * @param {获取未读公告条数} options 
   * @param {获取未读公告条数} options 
 * @param {获取未读公告条数} options 
 */
  getNoticeCount() {
    let param = {
      cpId: app.globalData.user.cpId,
      orgId: app.globalData.user.orgId,
      userId: app.globalData.user.userId,
    }
    //操作后台
    api.request(Constants.NOTICE_API + 'search_select_count', 'POST', param).then(res => {

      if (res.data.code == 200) {
        this.setData({
          noticeCount: res.data.data
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let waitMenu = this.data.waitMenu;
    let waitMenuFlag = false;
    waitMenu.forEach(it => {
      let rightFlag = common.hasPageRight(it.code)
      if (rightFlag) {
        it.show = true;
        waitMenuFlag = true;
        // 待收款
        if (it.code == Constants.menuCode.cusReceipt) {
          // 获取条数
          this.getWaitReceival();
        }else if (it.code == Constants.menuCode.order) {
          // 获取条数
          this.getOrder();
        }else if (it.code == Constants.menuCode.entryHandle) {
          // 获取条数
          this.getWaitInbound();
        }else if (it.code == Constants.menuCode.outHandle) {
          // 获取条数
          this.getWaitOutbound();
        }
      }
    })
    this.setData({
      waitMenuFlag:waitMenuFlag,
      companyName: app.globalData.company.cpName,
      staffName: app.globalData.user.staffName,
      orgName: app.globalData.user.orgName,
      waitMenu:waitMenu,
      version: wx.getAccountInfoSync().miniProgram.version,
    })
    /**
     * @desc : 获取用户信息
     * @date : 2022/5/12 13:49
     * @author : 姜永辉
     */
    if (app.globalData.user) {
      this.setData({
        userInfo: app.globalData.user,
      })
    }
    // this.getAppCount()
    /** 获取胶囊信息 */
    this.setData({
      menuBtnInfo: wx.getMenuButtonBoundingClientRect()
    })
  },
  onShow() {
    if (this.data.mineFlag) {
      // this.getAppCount()
      /** 获取胶囊信息 */
      this.setData({
        menuBtnInfo: wx.getMenuButtonBoundingClientRect()
      })
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

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

  },

  /**
   *  检测是否有新版本-手动更新
   */
  checkHasManualUpdate() {
    app.checkHasManualUpdate()
  },
  /**
  *  当前版本号
  */
  getAccountInfoSync() {
    const accountInfo = wx.getAccountInfoSync();
    util.showToast('当前版本号:' + accountInfo.miniProgram.version);

  },

})