import { AppService, TySqlApiClient } from "../refs/nslib"
import { logger } from "mslib";
import{Helper} from "./Helper"
const dayjs= require('dayjs')


/**
 *
 * @date 2022-08-16 10:16:41
 * @author 侯洪莉
 */
class ChargingBusDeal {

    /**
    * 获取使用规则配置信息
    * @param {*} parkId 
    * @param {string} pileId 充电桩appID
    * @param {*} opsConfig 统一平台配置
    */
    async getPileRule(parkId, pileId) {

        let sql = `
            select  
                id,
                name  as pileName,      -- 充电桩名称
                pileId,                 -- 充电桩ID
                isEnable,               -- 是否启用 0-禁用 1-启用
                discountSource,         -- 抵扣来源
                discountType,           -- 抵扣类型
                discountMethod,         -- 抵扣方法
                discountNumber,         -- 抵扣数量
                chargeTime,             -- 使用抵扣的最小充电时间要求
                onceMaxNum,             -- 单次停车抵扣次数上限
                dayMaxNum,              -- 单日停车抵扣次数上限
                onceMaxTime,            -- 单次停车抵扣时长上限
                onceMaxMoney,           -- 单次停车抵扣金额上限
                dayMaxTime,             -- 每日抵扣时长上限
                dayMaxMoney,            -- 每日抵扣金额上限
                isSpecialFeeRule,       -- 是否使用特殊规则
                carStyle                   -- 充电车辆类型
            from 
                t_${parkId}_ns_pile 
            where 
                isDelete  = 0 and isEnable = 1 and pileId='${pileId}'
            limit 1
        `;
        const res = await new TySqlApiClient().selectOne(sql);
        const info = res || null
        return info;
    }



    /**
     * 获取全局配置信息
     * 
     * @param {string}
     * @param {*} opsConfig 统一平台配置
     */
    async getPileConfig(parkId) {
        const session = '1103860'; //此值固定
        const sql = `
            select
            name, 
            value 
            from t_${parkId}_ns_pile_config where session='${session}';
        `
        const result = await new TySqlApiClient().list(sql);


        const info = result||[]
        let configInfo = {}
        if (info && info.length > 0) {
            for (let item of info) {
                Object.assign(configInfo,
                    {
                        [item.name]: item['value']
                    }
                )
            }
        }
        return configInfo;
    }




     /**
     * 获取全局的限制情况
     * @param {Object} params 
     * @param {Object} configRule 全局规则限制
     * @param {Object} parkInfo 停车信息
     * 
     * @return {Int} canUse  可以使用额度 Infinity：表示不限额度
     */
    async getConfigRuleLimit(params, configRule, parkInfo) {
        const { parkId, plateNo } = params;
        // onceMaxNum: 单次抵扣次数上限 dayMaxNum： 每日抵扣次数上限 onceMaxTime:单次停车抵扣时长上限  dayMaxTime:每日抵扣时长上限 dayMaxMoney:每日抵扣金额上限  onceMaxMoney:单次停车抵扣金额上限
        const { onceMaxNum=0, dayMaxNum=0, onceMaxTime=0, dayMaxTime=0, dayMaxMoney=0, onceMaxMoney=0 } = configRule;
        const { inTime } = parkInfo
        let onceUse = { count: 0, time: 0, money: 0 };
        let dayUse = { count: 0, time: 0, money: 0 };
        // 单次可用额度，当天可用额度
        let onceNumCanUse = 0, dayNumCanUse = 0;
        let onceTimeCanUse = 0, onceMoneyCanUse = 0;
        let dayTimeCanUse = 0, dayMoneyCanUse = 0;
        // 判断单次所有抵扣使用情况
        if (onceMaxTime > 0 || onceMaxMoney > 0 || onceMaxNum > 0) {
            onceUse = await  Helper.getPaymentCount({ parkId, plateNo, inTime });
        }

        // 可用额度
        onceNumCanUse = onceMaxNum > 0 ? onceMaxNum - onceUse.count : Infinity
        onceTimeCanUse = onceMaxTime > 0 ? onceMaxTime - onceUse.time : Infinity;
        onceMoneyCanUse = onceMaxMoney > 0 ? onceMaxMoney - onceUse.money : Infinity;
        if (onceNumCanUse <= 0) {
            logger.info(`【全局限制】单次抵扣次数（${onceMaxNum}次）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };

        }
        if (onceTimeCanUse <= 0) {
            logger.info(`【全局限制】单次抵扣时间额度（${onceMaxTime/60}分钟）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }
        if (onceMoneyCanUse <= 0) {

            logger.info(`【全局限制】单次抵扣金额(${(onceMaxMoney)/100}元）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }

        // 判断当日抵扣使用情况
        if (dayMaxTime > 0 || dayMaxMoney > 0 || dayMaxNum > 0) {
            let startTime = `${dayjs().format('YYYY-MM-DD')} 00:00:00`;
            let endTime = `${dayjs().format('YYYY-MM-DD')} 23:59:59`;
            dayUse = await Helper.getPaymentCount({ parkId, plateNo, startTime, endTime });
        }

        // 可用额度
        dayNumCanUse = dayMaxNum > 0 ? dayMaxNum - dayUse.count : Infinity
        dayTimeCanUse = dayMaxTime > 0 ? dayMaxTime - dayUse.time : Infinity;
        dayMoneyCanUse = dayMaxMoney > 0 ? dayMaxMoney - dayUse.money : Infinity;


        if (dayNumCanUse <= 0) {
            logger.info(`【全局限制】当日抵扣次数（${dayMaxNum}次）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }
        if (dayTimeCanUse <= 0) {
            logger.info(`【全局限制】当日抵扣时间额度（${dayMaxTime/60}分钟）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }
        if (dayMoneyCanUse <= 0) {
            logger.info(`【全局限制】当日抵扣额度（${dayMaxMoney/100}元）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }
        const timeCanUse = onceTimeCanUse - dayTimeCanUse < 0 ? onceTimeCanUse : dayTimeCanUse;
        const moneyCanUse = onceMoneyCanUse - dayMoneyCanUse < 0 ? onceMoneyCanUse : dayMoneyCanUse;
        return { timeCanUse, moneyCanUse }


    }




    /**
     * 获取使用规则的限制情况
     * @param {Object} params 
     * @param {Object} pileRule 使用规则限制
     * @param {Object} parkInfo 停车信息
     * 
     * @return {Int} canUse  可以使用额度 Infinity：表示不限额度
     */
    async getPileRuleLimit(params, pileRule, parkInfo) {
        if(!params.pileId){
            logger.info(`【使用规则限制】未获取到充电桩pileId`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }
        const { parkId, plateNo ,pileId} = params;
        // onceMaxNum: 单次抵扣次数上限 dayMaxNum： 每日抵扣次数上限 onceMaxTime:单次停车抵扣时长上限  dayMaxTime:每日抵扣时长上限 dayMaxMoney:每日抵扣金额上限  onceMaxMoney:单次停车抵扣金额上限
        const { onceMaxNum, dayMaxNum, onceMaxTime, dayMaxTime, dayMaxMoney, onceMaxMoney } = pileRule;
        const { inTime } = parkInfo
        let onceUse = { count: 0, time: 0, money: 0 };
        let dayUse = { count: 0, time: 0, money: 0 };
        // 单次可用额度，当天可用额度
        let onceNumCanUse = 0, dayNumCanUse = 0;
        let onceTimeCanUse = 0, onceMoneyCanUse = 0;
        let dayTimeCanUse = 0, dayMoneyCanUse = 0;
        // 判断单次所有抵扣使用情况
        if (onceMaxTime > 0 || onceMaxMoney > 0 || onceMaxNum > 0) {
            onceUse = await Helper.getPaymentCount({ parkId, plateNo, inTime,pileId });
        }

        // 可用额度
        onceNumCanUse = onceMaxNum > 0 ? onceMaxNum - onceUse.count : Infinity
        onceTimeCanUse = onceMaxTime > 0 ? onceMaxTime - onceUse.time : Infinity;
        onceMoneyCanUse = onceMaxMoney > 0 ? onceMaxMoney - onceUse.money : Infinity;
        if (onceNumCanUse <= 0) {
            logger.info(`【使用规则限制】单次抵扣次数（${onceMaxNum}次）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };

        }
        if (onceTimeCanUse <= 0) {
            logger.info(`【使用规则限制】单次抵扣时间额度（${onceMaxTime/60}分钟）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }
        if (onceMoneyCanUse <= 0) {

            logger.info(`【使用规则限制】单次会员抵扣金额(${(onceMaxMoney)/100}元）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }

        // 判断当日抵扣使用情况
        if (dayMaxTime > 0 || dayMaxMoney > 0 || dayMaxNum > 0) {
            let startTime = `${dayjs().format('YYYY-MM-DD')} 00:00:00`;
            let endTime = `${dayjs().format('YYYY-MM-DD')} 23:59:59`;
            dayUse = await Helper.getPaymentCount({ parkId, plateNo, startTime, endTime,pileId });
        }

        // 可用额度
        dayNumCanUse = dayMaxNum > 0 ? dayMaxNum - dayUse.count : Infinity
        dayTimeCanUse = dayMaxTime > 0 ? dayMaxTime - dayUse.time : Infinity;
        dayMoneyCanUse = dayMaxMoney > 0 ? dayMaxMoney - dayUse.money : Infinity;


        if (dayNumCanUse <= 0) {
            logger.info(`【使用规则限制】当日抵扣次数（${dayMaxNum}次）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }
        if (dayTimeCanUse <= 0) {
            logger.info(`【使用规则限制】当日抵扣时间额度（${dayMaxTime/60}分钟）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }
        if (dayMoneyCanUse <= 0) {
            logger.info(`【使用规则限制】当日抵扣额度（${dayMaxMoney/100}元）已达上限`);
            return { timeCanUse: 0, moneyCanUse: 0 };
        }
        const timeCanUse = onceTimeCanUse - dayTimeCanUse < 0 ? onceTimeCanUse : dayTimeCanUse;
        const moneyCanUse = onceMoneyCanUse - dayMoneyCanUse < 0 ? onceMoneyCanUse : dayMoneyCanUse;
        return { timeCanUse, moneyCanUse }


    }








}

export { ChargingBusDeal }