/*******************************************************************************
 * 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/',
    dueFlag: false,  // 到期标识
    videoSrc: 'https://s.dev01.dkiboss.com:7000/file/operate_guide/all.mp4',
    cpEndDate: null,
    playFlag: false,
    companyName: null,
    staffName: 'null',
    orgName: null,
    waitMenuFlag: true, // 是否显示待办工作区
    statusHeight: 0, // 状态栏高度
    // 路由
    routeObjName: 'setting',
    companyService: app.globalData['companyService'],
    oauthService: app.globalData['oauthService'],
    appCount: 0,
    noticeCount: 0,
    beginnerGuideUrl: '/package-basic-data/pages/beginner-guide/beginner-guide',//新手引导

    /** 6个切换组件的值 */
    storeHelperValue: 'nearly7days',

    /** 6个数据源 */
    shopHelper: {},
    staffHelper: {},

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

    /** 2种切换组件的options */
    tagList: [
      { name: '今日', id: 'today', value: [util.formatDataTime(new Date()).substring(0, 10), util.formatDataTime(new Date()).substring(0, 10)] },
      { name: '近7天', id: 'nearly7days', value: util.timeForMat(7) },
      { name: '近30天', id: 'nearly30days', value: util.timeForMat(30) }],

    active: 'store',
    showStoreFlag: true,

    menuBtnInfo: null,
    // 待办工作
    waitMenu: [
      {
        title: '待收款',
        code: 'cus-receipt',
        path: '/package-sales/pages/customer-collection/customer-collection',
        icon: 'btn-account-receivable.png',
      },
      {
        title: '待发货',
        code: 'order',
        path: '/package-sales/pages/order-billing/order-billing',
        icon: 'btn-shipped.png',
      },
      {
        title: '待入库',
        code: 'entry-handle',
        path: '/package-inventory/pages/warehousing-processing/warehousing-processing',
        icon: 'btn-stored.png',
      },
      {
        title: '待出库',
        code: 'out-handle',
        path: '/package-inventory/pages/outbound-processing/outbound-processing',
        icon: 'btn-shipped-out.png',
      },
    ],
  },

  /**
   * @desc   : 改变选择框内容
   * @author : 周兴
   * @date   : 2024/1/26 11:46
   */
  changeTabs(e) {
    let values = e.detail.value
    this.getHomeOrderRecCost(values[0], values[1])
  },

  /**
  * @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
  */
  getHomeOrderRecCost(dateBegin, dateEnd) {
    let params = {
      dateBegin: dateBegin,
      dateEnd: dateEnd,
    }
    let service = app.globalData['commonService']
    api.request(service.prefix + service.getHomeOrderRecCost, 'POST', params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        let data = res.data.data
        let valueAmounts = []
        valueAmounts.push({
          title: '销售金额(元)',
          value: data.amtShouldSumAmount ? data.amtShouldSumAmount : 0.00
        })
        valueAmounts.push({
          title: '收款金额(元)',
          value: data.amtRecSumAmount ? data.amtRecSumAmount : 0.00
        })
        valueAmounts.push({
          title: '库存成本金额(元)',
          value: data.costAmtSumAmount ? data.costAmtSumAmount : 0.00
        })
        this.setData({
          valueAmounts,
        })
      }
    });
  },

  /**
  * @desc : 跳转到微信聊天界面
  * @author : 周兴
  * @date : 2024/4/9
  */
  handleWxService(e) {
    // console.log('Constants.WX_SERVICE',Constants.WX_SERVICE);
    // let url= Constants.WX_SERVICE
    // wx.navigateTo({
    //   url: '/pages/product/product',
    //   success: function (res) {
    //     res.eventChannel.emit('url', Constants.WX_SERVICE);
    //   }
    // })
    wx.openCustomerServiceChat({
      extInfo: { url: Constants.WX_SERVICE },
      corpId: Constants.WX_CPID,
      success(res) {
        console.log('ddd', res);
      }
    })
  },
  /**
  * @desc : 跳转到续费页面
  * @author : 周兴
  * @date : 2024/4/9
  */
  handleRecharge(e) {
    let url = '/package-basic-data/pages/activity/activity'
    wx.navigateTo({
      url: url,
      events: {
        // 保存成功后刷新页面
        refresh: function (data) {
          // 刷新一览界面
          wx.reLaunch({
            url: '/pages/welcome/welcome',
          })
        }
      },
    })
  },
  /**
  * @desc : 升级
  * @author : 周兴
  * @date : 2024/4/9
  */
  handleUpgrade(e) {
    let url = '/package-basic-data/pages/activity/activity?upgrade=true'
    wx.navigateTo({
      url: url,
      events: {
        // 保存成功后刷新页面
        refresh: function (data) {
          // 刷新一览界面
          wx.reLaunch({
            url: '/pages/welcome/welcome',
          })
        }
      },
    })
  },
  /**
  * @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 : 2024/5/13 13:49
  * @author : 周兴
  */
  toOperateGuide(e) {
    let file = 'all.pdf'
    // 下载操作手册pdf
    let url = config.image_url + '/operate_guide/' + file;
    this.downloadFile(url, type);
  },
  /**
  * @desc : 打开操作手册视频
  * @date : 2024/5/13 13:49
  * @author : 周兴
  */
  toOperateGuideVideo(e) {
    let type = e.currentTarget.dataset.type

    if (type == 'close') {
      this.setData({
        playFlag: false
      })
    } else {
      this.setData({
        playFlag: true
      })
    }
  },

  /**
  * @desc : 设置跳转
  * @date : 2022/5/12 13:49
  * @author : 姜永辉
  */
  toSetting() {
    this.setData({
      loading: true
    })
    console.log(app.globalData, "toSetting");
    let _this = this
    wx.navigateTo({
      url: this.data.route.companySetting.url,
      events: {
        // 回调后，在这里给页面赋值
        bandData: function (e) {
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', { id: app.globalData.company.cpId, formMode: Constants.formMode.edit })
        setTimeout(() => {
          _this.setData({
            loading: false
          })
        }, 2000)
      }
    })
  },
  /**
  * @desc : 新手引导
  * @date : 2022/5/12 13:49
  * @author : 于继渤
  */
  toBeginnerGuide() {
    this.setData({
      loading: true
    })
    let _this = this
    wx.navigateTo({
      url: this.data.beginnerGuideUrl,
      events: {
        // 回调后，在这里给页面赋值
        bandData: function (e) {
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', {})
        setTimeout(() => {
          _this.setData({
            loading: false
          })
        }, 1000)
      }
    })
  },

  /**
  * @desc : 退出登录
  * @date : 2022/5/12 13:49
  * @author : 姜永辉
  */
  logout(e) {
    let _this = this
    //提示
    Dialog.confirm({
      message: '您确定要退出系统？',
    }).then(() => {
      let params = {
        openid: app.globalData.openid,
        userId: app.globalData.user.userId,
      }
      return this.excute(_this.data.oauthService, _this.data.oauthService.logout, 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) {
    console.log(app.globalData.company, " app.globalData.company");
    let res = wx.getSystemInfoSync();
    let statusHeight = res.statusBarHeight
    this.setData({
      statusHeight: statusHeight * 2 + 20
    })
    if (app.globalData && app.globalData.company) {
      let cpEndDate = app.globalData.company.endDate
      this.setData({
        cpEndDate: cpEndDate, // 企业到期日期
      })
      // 判断是否即将到期
      let endD = new Date(cpEndDate);
      // 服务器的日期为准
      let nowD = new Date(app.globalData.nowDate).addDays(Constants.CP_ALERT_TIME);
      if (endD < nowD) {
        this.setData({
          dueFlag: true
        })
      }
    }
    // // 判断当前用户是否到期 标准版
    if (app.globalData.company.gradeCode == Constants.gradeCode.STD
      && !app.globalData.user.flgInit
      && app.globalData.company.userEndDate) {
      let endD = new Date(app.globalData.company.userEndDate);
      // 服务器的日期为准
      let nowD = new Date(app.globalData.nowDate).addDays(Constants.CP_ALERT_TIME);
      if (endD < nowD) {
        let cpEndDate = app.globalData.company.userEndDate
        this.setData({
          cpEndDate: cpEndDate, // 企业到期日期
        })
        this.setData({
          dueFlag: true
        })
      }
    }

    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();
        }
      }
    })
    // 标准版不显示待办
    if (this.data.gradeCode == Constants.gradeCode.STD) {
      waitMenuFlag = false
    }

    this.setData({
      waitMenuFlag: waitMenuFlag,
      companyName: app.globalData.company.cpName,
      staffName: app.globalData.user.staffName,
      orgName: app.globalData.user.orgName,
      waitMenu: waitMenu,
      dateBegin: '',
      dateEnd: '',
      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()
      })
    }
    // 查询门店助手
    let dates = util.timeForMat(7)
    this.getHomeOrderRecCost(dates[0], dates[1])
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  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);

  },

})