/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：活动（用于续费、注册）
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		周兴		       2024-5-15	            1.00		   	   新建 
 *******************************************************************************/
const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const mixins = require('@/mixins/index.js');
const app = getApp()
Page({
    mixins: [mixins],
    /**
     * 页面的初始数据
     */
    data: {
        // 是否加载完毕
        loadFlag: false,
        // 是否显示vip
        showVip: false,
        // 升级标识
        upgradeFlag: false,
        gradeCode: null,
        freeFlag: false,
        // 企业名称
        companyName: null,
        cpManager: null,
        cpPhone: null,
        webMaxNum: null,
        wxMaxNum: null,
        cpEndDate: null,
        activityTable: null,
        vipTable: null,
        readFlag: false,
        staffCount: {
            maxNum: 1,
            webMaxNum: 0,
            wxMaxNum: 0
        },
        curentAdItem: null,
        // 选择的vip报表
        chooseVipFlag: false,
        summaryInfo: {},
        routeObjName: 'company',
        pageFlag: false,
        // 当前用户授权数
        currentUserCount: null,
        //按钮
        buttonSaveList: [
            { code: 'save', title: mixins.$t('save'), width: '120rpx' }
        ],
        noticeInfo: Constants.noticeInfo
    },
    /**
     * @desc : 选择活动明细
     * @author : 周兴
     * @date : 2024/4/1
     */
    chooseAdItem(e) {
        let item = e.currentTarget.dataset.item;
        let summaryInfo = this.data.summaryInfo
        // 计算截止日期
        let months = item.validLong + item.extraLong
        let endDate = app.globalData.company.endDate
        // 升级需要从当天开始算
        if (this.data.upgradeFlag) {
            endDate = new Date()
        }
        endDate = new Date(endDate).addMonths(months).addDays(-1)
        summaryInfo.endDate = endDate.toDateStr();
        this.setData({
            curentAdItem: item,
            summaryInfo: summaryInfo
        })
        // 计算金额
        this.countSummaryAmount(item);
    },
    /**
     * @desc : 选择VIP报表明细
     * @author : 周兴
     * @date : 2024/4/1
     */
    chooseVipItem(e) {
        let item = e.currentTarget.dataset.item;
        // let summaryInfo = this.data.summaryInfo
        // // 计算截止日期
        // let months = item.validLong + item.extraLong
        // let endDate = app.globalData.company.endDate
        // // 升级需要从当天开始算
        // if (this.data.upgradeFlag) {
        //     endDate = new Date()
        // }
        // endDate = new Date(endDate).addMonths(months).addDays(-1)
        // summaryInfo.endDate = endDate.toDateStr();
        this.setData({
            chooseVipFlag: !this.data.chooseVipFlag,
            // summaryInfo: summaryInfo
        })
        // 计算金额
        this.countSummaryAmountSTD();
    },
    /**
     * @desc : 勾选已阅读表示
     * @author : 周兴
     * @date : 2024/5/17
     */
    handleChangeCheckbox(e) {
        console.log('ee', e);
        this.setData({
            readFlag: e.detail
        })
    },
    /**
     * @desc : 计算金额
     * @author : 周兴
     * @date : 2024/4/1
     */
    countSummaryAmount() {
        let item = this.data.curentAdItem;
        if (!item) return;
        let staffCount = this.data.staffCount;
        let summaryInfo = this.data.summaryInfo
        let amount = 0;
        // 先清空
        summaryInfo.amountInfo = '';
        // 共通用户
        if (staffCount.maxNum) {
            summaryInfo.amountInfo = item.stdPrice + '(打包价格)*' + staffCount.maxNum
            amount += item.stdPrice * staffCount.maxNum
        }
        // 手机端用户
        if (staffCount.wxMaxNum) {
            if (summaryInfo.amountInfo) {
                summaryInfo.amountInfo += ' + '
            }
            summaryInfo.amountInfo += item.wxPrice + '(手机端价格)*' + staffCount.wxMaxNum
            amount += item.wxPrice * staffCount.wxMaxNum
        }
        // 电脑端用户
        if (staffCount.webMaxNum) {
            if (summaryInfo.amountInfo) {
                summaryInfo.amountInfo += ' + '
            }
            summaryInfo.amountInfo += item.webPrice + '(电脑端价格)*' + staffCount.webMaxNum
            amount += item.webPrice * staffCount.webMaxNum
        }
        if (summaryInfo.amountInfo) {
            summaryInfo.amountInfo += ' = ' + amount + '(元)'
            summaryInfo.amount = amount;
        }
        this.setData({
            summaryInfo: summaryInfo
        })
        // 统计两端用户数
        this.countStaffInfo();
    },
    /**
     * @desc : 获取标准版的价格显示
     * @author : 周兴
     * @date : 2024/4/1
     */
    countSummaryAmountSTD() {
        let item = this.data.curentAdItem;
        let vipTable = this.data.vipTable
        let summaryInfo = this.data.summaryInfo
        let amount = 0;
        // 先清空
        summaryInfo.amountInfo = '';
        let extendDays = null;
        let nowDate = new Date(new Date().toDateStr());
        if (summaryInfo.reCountFlag) {
            // 手机端用户
            if (summaryInfo.wxMaxNum) {
                summaryInfo.amountInfo += item.wxPrice + '(元) * ' + summaryInfo.wxMaxNum + '(个) '
                amount += item.wxPrice * summaryInfo.wxMaxNum
            }
            // vip报表
            if (this.data.chooseVipFlag && vipTable && vipTable.length > 0) {
                let vipItem = vipTable[0]
                summaryInfo.amountInfo += ' + ' + vipItem.wxPrice + '(元/VIP) ';
                amount += vipItem.wxPrice;
            }
            if (summaryInfo.amountInfo) {
                summaryInfo.amountInfo += ' = ' + amount + '(元)'
                summaryInfo.amount = amount;
            }
            extendDays = new Date(summaryInfo.userEndDate).dayDiff(nowDate) + 1;
        } else {
            extendDays = new Date(summaryInfo.userEndDate).dayDiff(nowDate) + 1;
            if (summaryInfo.wxMaxNum) {
                summaryInfo.amountInfo += item.wxPrice + '(元)  '
                amount += item.wxPrice * summaryInfo.wxMaxNum
            }
            // vip报表
            if (this.data.chooseVipFlag && vipTable && vipTable.length > 0) {
                let vipItem = vipTable[0]
                console.log('vipItem.wxPrice', vipItem.wxPrice);
                summaryInfo.amountInfo += ' + ' + vipItem.wxPrice + '(元/VIP) ';
                summaryInfo.amountInfo = '( ' + summaryInfo.amountInfo + ' ) ';
                amount += vipItem.wxPrice;
            }
            summaryInfo.amountInfo += ' / 365(天) * ' + extendDays + '(天) * ' + summaryInfo.wxMaxNum + '(个)'
            if (summaryInfo.amountInfo) {
                amount = (amount / 365 * extendDays).toFixed(2);
                summaryInfo.amountInfo += ' = ' + amount + '(元)'
                summaryInfo.amount = amount;
            }
        }

        // 计算一授权一天的单价
        if (summaryInfo.userEndDate) {
            let price = (summaryInfo.amount / summaryInfo.wxMaxNum / extendDays).toFixed(2);
            summaryInfo.priceInfo = price
            summaryInfo.extendDays = extendDays
        }

        this.setData({
            summaryInfo: summaryInfo
        })
    },
    /**
     * @desc : 统计电脑端和手机端的用户数
     * @author : 周兴
     * @date : 2024/4/1
     */
    countStaffInfo() {
        let summaryInfo = this.data.summaryInfo;
        let staffCount = this.data.staffCount;
        if (!staffCount) {
            return;
        }
        let webNum = staffCount.webMaxNum + staffCount.maxNum
        let wxNum = staffCount.wxMaxNum + staffCount.maxNum
        summaryInfo.staffInfo = '可配置手机端授权' + wxNum + '个；电脑端授权' + webNum + '个（包含当前用户）'
        summaryInfo.webMaxNum = webNum
        summaryInfo.wxMaxNum = wxNum
        // 升级从当天算
        if (this.data.upgradeFlag) {
            summaryInfo.buyBeginDate = new Date().addDays(1).toDateStr();
            summaryInfo.extendDays = new Date(summaryInfo.endDate).dayDiff(new Date().addDays(1));
        } else {
            summaryInfo.buyBeginDate = new Date(this.data.cpEndDate).addDays(1).toDateStr();
            summaryInfo.extendDays = new Date(summaryInfo.endDate).dayDiff(new Date(this.data.cpEndDate).addDays(1));
        }
        // 计算一授权一天的单价
        let price = (summaryInfo.amount / (webNum + wxNum) / summaryInfo.extendDays).toFixed(2);
        summaryInfo.priceInfo = price

        this.setData({
            summaryInfo: summaryInfo
        })
    },
    /**
     * @desc : 修改用户数
     * @author : 周兴
     * @date : 2024/4/1
     */
    changeStaffCount(e) {
        let staffCount = this.data.staffCount
        let ds = e.currentTarget.dataset
        if (ds.type == 'wx') {
            staffCount.wxMaxNum = e.detail
        } else if (ds.type == 'web') {
            staffCount.webMaxNum = e.detail
        } else {
            staffCount.maxNum = e.detail
        }
        this.setData({
            staffCount: staffCount
        })
        // 计算金额
        this.countSummaryAmount();
    },
    /**
     * @desc : 保存
     * @author : 周兴
     * @date : 2024/4/1
     */
    handleSave() {
        let summaryInfo = this.data.summaryInfo;
        let currentUserCount = this.data.currentUserCount
        if (!currentUserCount) {
            return;
        }
        if (this.data.gradeCode == Constants.gradeCode.STD) {
            // 必须要选择一个授权 
            if (Number(summaryInfo.amount) <= 0) {
                util.showToast('请选择一个授权');
                return false
            }
            // 判断数量是否超出续约授权
            if (currentUserCount.wxNum > summaryInfo.wxMaxNum && summaryInfo.reCountFlag) {
                let staffInfo = [{ wxMaxNum: this.data.wxMaxNum, title: '当前授权', wxTitle: '手机授权', code: 'current', userTitle: '当前用户' }, { wxMaxNum: summaryInfo.wxMaxNum, title: '续费授权', wxTitle: '手机授权', code: 'renew' }]
                this.save({ saveFlag: false, url: '/package-basic-data/pages/activity/detail/detail?staffInfo=' + JSON.stringify(staffInfo) });
            } else {
                this.save({});
            }
        } else {
            // 判断数量是否超出续约授权
            if (currentUserCount.wxNum > summaryInfo.wxMaxNum || currentUserCount.webNum > summaryInfo.webMaxNum) {
                let staffInfo = [{ wxMaxNum: this.data.wxMaxNum, webMaxNum: this.data.webMaxNum, title: '当前授权', wxTitle: '手机授权', webTitle: '电脑授权', code: 'current' }, { wxMaxNum: summaryInfo.wxMaxNum, webMaxNum: summaryInfo.webMaxNum, title: '续费授权', wxTitle: '手机授权', webTitle: '电脑授权', code: 'renew' }]
                this.save({ saveFlag: false, url: '/package-basic-data/pages/activity/detail/detail?staffInfo=' + JSON.stringify(staffInfo) });
            } else {
                this.save({});
            }
        }
    },
    /**
     * @desc : 改变用户授权数
     * @author : 周兴
     * @date : 2024/4/1
     */
    changeUserSTD(e) {
        let summaryInfo = this.data.summaryInfo
        summaryInfo.wxMaxNum = e.detail
        this.setData({
            summaryInfo: summaryInfo
        })
        // 计算金额
        this.countSummaryAmountSTD();
    },
    /**
     * @desc : 校验
     * @author : 周兴
     * @date : 2024/4/1
     */
    validData() {
        // 专业版校验
        if (this.data.gradeCode == Constants.gradeCode.PRO) {
            if (!this.data.readFlag) {
                util.showToast('请勾选阅读须知');
                return false;
            }
            let curentAdItem = this.data.curentAdItem;
            if (!curentAdItem) {
                util.showToast('请选择活动');
                return false
            }
            // 必须要选择一个授权
            let staffCount = this.data.staffCount
            if (!staffCount.maxNum && !staffCount.webMaxNum && !staffCount.wxMaxNum) {
                util.showToast('请选择一个授权');
                return false
            }
        } else {
            let curentAdItem = this.data.curentAdItem;
            if (!curentAdItem) {
                util.showToast('请选择活动');
                return false
            }
        }

        return true;
    },
    /**
     * @desc : 设置保存参数
     * @author : 周兴
     * @date : 2024/4/1
     */
    setParams(params) {
        let summaryInfo = this.data.summaryInfo
        let curentAdItem = this.data.curentAdItem
        let cpEndDate = this.data.cpEndDate
        console.log('summaryInfo', summaryInfo);
        if (!summaryInfo || !cpEndDate) return;
        params.endDate = summaryInfo.endDate
        params.userEndDate = summaryInfo.userEndDate
        params.gradeCode = this.data.gradeCode
        params.cpId = app.globalData.company.cpId
        params.tradeNo = this.generateRandomNo();
        params.wxUserId = app.globalData.user.userId
        params.tradeAmount = summaryInfo.amount
        params.buyBeginDate = summaryInfo.buyBeginDate;
        params.buyEndDate = summaryInfo.endDate
        params.extendDays = summaryInfo.extendDays;
        if (this.data.gradeCode == Constants.gradeCode.STD) {
            params.buyEndDate = summaryInfo.userEndDate
            params.endDate = app.globalData.company.endDate
            params.wxMaxNum = summaryInfo.wxMaxNum

            if (this.data.showVip && this.data.chooseVipFlag) {
                params.vip = true;
            } else if (!this.data.showVip && app.globalData.company.vip) {
                params.vip = true;
            }
            if (this.data.chooseVipFlag) {
                params.vip = true;
            }
            if (!summaryInfo.reCountFlag && summaryInfo.wxMaxNumSocial) {
                params.wxMaxNum = summaryInfo.wxMaxNum + summaryInfo.wxMaxNumSocial
            }
        } else {
            params.webMaxNum = summaryInfo.webMaxNum
            params.wxMaxNum = summaryInfo.wxMaxNum
        }
        params.buyLong = curentAdItem.activityItemName
        return params;
    },
    /**
     * @desc : 保存数据
     * @author : 周兴
     * @date : 2024/5/17
     */
    saveData(params) {
        return this.excute(this.data.service, this.data.service.reNewCompany, this.data.params).then(res => {
            if (res.data.code == Constants.SUCESS_CODE) {
                // 成功后跳转支付
                this.toPay(res.data.data);
            }
        })
    },
    /**
     * @desc : 查询当前用户授权数
     * @author : 周兴
     * @date : 2024/4/1
     */
    getStaffCount() {
        let service = app.globalData['commonService']
        this.excute(service, service.selectUserCount, {}).then(res => {
            if (res.data.code == Constants.SUCESS_CODE) {
                if (res.data && res.data.data) {
                    let currentUserCount = res.data.data;
                    console.log('currentUserCount', currentUserCount);
                    this.setData({
                        currentUserCount: currentUserCount,
                        //服务器的时间 
                        currentDate: new Date(currentUserCount.currentDate)
                    })
                }
            }
            // 获取活动
            this.getActivity()
            this.setData({
                loadFlag: true
            })
        });
    },
    /**
     * @desc : 查询活动
     * @author : 周兴
     * @date : 2024/4/1
     */
    getActivity() {
        let params = {
            appCode: Constants.APP_CODE,
            activityStatus: Constants.kindCode.activityStatus,
            cpId: app.globalData.company.cpId,
            gradeCode: this.data.gradeCode
        }
        // 标准版
        if (this.data.gradeCode == Constants.gradeCode.STD) {
            params.activityTypeList = [Constants.kindCode.activityGrade, Constants.kindCode.activityVip];
        } else {
            params.activityTypeList = [Constants.kindCode.activityGrade];
        }
        let service = app.globalData['activityService']
        this.excute(service, service.selectActivityItems, params).then(res => {
            if (res.data.code == Constants.SUCESS_CODE) {
                if (res.data && res.data.data) {
                    let activityTable = res.data.data;

                    // 如果是标准版，需要进行截止日期的处理
                    if (this.data.gradeCode == Constants.gradeCode.STD) {
                        this.setData({
                            activityTable: activityTable.filter(it => it.activityType == Constants.kindCode.activityGrade),
                            vipTable: activityTable.filter(it => it.activityType == Constants.kindCode.activityVip),
                        })
                        this.handleDataStd(activityTable);
                    } else {
                        this.setData({
                            activityTable: activityTable
                        })
                    }
                }
            }
        });
    },
    /**
     * @desc : 标准版处理数据
     * @author : 周兴
     * @date : 2024/4/1
     */
    handleDataStd(activityTable) {
        if (activityTable && activityTable.length > 0) {
            let item = activityTable[0]
            this.setData({
                curentAdItem: item
            })
            let summaryInfo = this.data.summaryInfo
            let months = item.validLong + item.extraLong
            //服务器的时间  
            let endDate = this.data.currentDate.addMonths(months).addDays(-1)
            let dayDiffs = null;
            if (summaryInfo.userEndDate) {
                dayDiffs = new Date(summaryInfo.userEndDate).dayDiff(new Date(new Date().toDateStr()))
            }
            // 如果截止日期是空，就取活动中的截止日期
            if (!summaryInfo.userEndDate || !dayDiffs || dayDiffs < 0) {
                summaryInfo.userEndDate = endDate.toDateStr();
                // 重新统计，到期续费或者第一次购买用户
                summaryInfo.reCountFlag = true;
                summaryInfo.wxMaxNum = summaryInfo.wxMaxNumSocial
                this.setData({
                    showVip: true
                })
            } else {
                // 如果没有购买，需要显示
                if (!app.globalData.company.vip) {
                    this.setData({
                        showVip: true
                    })
                }
            }
            summaryInfo.buyBeginDate = this.data.currentDate.toDateStr();
            console.log('summaryInfo', summaryInfo.userEndDate, endDate, months);

            this.setData({
                summaryInfo: summaryInfo
            })
            // 计算金额
            this.countSummaryAmountSTD();
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('options', options, app.globalData);
        // 升级
        if (options && options.upgrade) {
            wx.setNavigationBarTitle({
                title: mixins.$t('updateSpecialized'),
            })
            this.setData({
                gradeCode: Constants.gradeCode.PRO,
                upgradeFlag: true
            })
        } else {
            wx.setNavigationBarTitle({
                title: mixins.$t('reNew'),
            })
            this.setData({
                gradeCode: app.globalData.company.gradeCode
            })
        }

        this.setData({
            companyName: app.globalData.company.cpName,
            cpManager: app.globalData.company.cpManager,
            cpPhone: app.globalData.company.cpPhone,
            cpEndDate: app.globalData.company.endDate,
            webMaxNum: app.globalData.company.webMaxNum,
            wxMaxNum: app.globalData.company.wxMaxNum,
        })
        // 如果是标准版，需要获取用户授权数（手机）
        let summaryInfo = {}
        summaryInfo.wxMaxNum = 1
        summaryInfo.wxMaxNumSocial = this.data.wxMaxNum
        // 续费用户到期日期
        summaryInfo.userEndDate = app.globalData.company.userEndDate
        this.setData({
            summaryInfo: summaryInfo
        })
        // 获取活动
        // this.getActivity();
        // 获取当前用户授权数
        this.getStaffCount();
    },
})