<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\adminapi\logic\recharge;

use app\common\enum\PayEnum;
use app\common\logic\BaseLogic;
use app\common\model\RechargeOrder;
use app\common\model\RechargeTemplate;
use app\common\service\ConfigService;
use app\common\service\FileService;

/**
 * 充值逻辑层
 * Class RechargeLogic
 * @package app\adminapi\logic\recharge
 */
class RechargeLogic extends BaseLogic
{
    /**
     * @notes 获取充值设置
     * @return array
     */
    public static function getConfig()
    {
        $config = [
            // 充值设置
            'set' => self::getSet(),
            // 充值规则
            'rule' => self::getRule(),
        ];

        return $config;
    }

    /**
     * @notes 充值设置
     * @return array
     */
    public static function getSet()
    {
        $set = [
            'open' => ConfigService::get('recharge', 'open'),
            'min_amount' => ConfigService::get('recharge', 'min_amount')
        ];
        return $set;
    }

    /**
     * @notes 获取规则
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getRule()
    {
        $lists = RechargeTemplate::field('id,money,award')->select()->toArray();
        return $lists;
    }

    /**
     * @notes 充值设置
     * @param $params
     */
    public static function setConfig($params)
    {
        try {
            // 更新设置
            self::updateSet($params);
            // 更新规则
            self::updateRule($params);

            return true;
        } catch(\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 更新设置
     * @param $params
     */
    public static function updateSet($params)
    {
        if(isset($params['open'])) {
            ConfigService::set('recharge', 'open', $params['open']);
        }
        if(isset($params['min_amount'])) {
            ConfigService::set('recharge', 'min_amount', $params['min_amount']);
        }
    }

    /**
     * @notes 更新规则
     * @param $params
     * @throws \think\Exception
     */
    public static function updateRule($params)
    {
        // 清除旧数据
        $deleteIds = RechargeTemplate::column('id');
        RechargeTemplate::destroy($deleteIds);

        // 未设置充值规则,直接返回
        if(!isset($params['rule']) || empty($params['rule'])) {
            return true;
        }

        if (!is_array($params['rule'])) {
            throw new \Exception('充值规则格式不正确');
        }

        $data = [];
        foreach($params['rule'] as $key => $item) {
            $data[] = self::validateData($key, $item);
        }
        (new RechargeTemplate())->saveAll($data);

    }

    /**
     * @notes 校验数据
     * @param $key
     * @param $item
     * @throws \think\Exception
     */
    public static function validateData($key, $item)
    {
        if(!isset($item['money'])) {
            throw new \think\Exception('规则' . ($key + 1) . '请输入充值金额');
        }
        if($item['money'] <= 0) {
            throw new \think\Exception('规则' . ($key + 1) . '充值金额须大于0');
        }
        if(!isset($item['award'])) {
            throw new \think\Exception('规则' . ($key + 1) . '请选择充值奖励');
        }
        if(!is_array($item['award']) || empty($item['award'])) {
            throw new \think\Exception('规则' . ($key + 1) . '充值奖励格式错误或为空');
        }
        foreach($item['award'] as $subItem) {
            if ($subItem['give_money'] < 0) {
                throw new \think\Exception('规则' . ($key + 1) . '充值奖励不能为负数');
            }
        }
        $item['award'] = json_encode($item['award'], JSON_UNESCAPED_UNICODE);
        return $item;
    }

    /**
     * @notes 充值数据中心
     * @return array
     */
    public static function dataCenter()
    {
        return [
            'recharge_data' => self::rechargeData(),
            'top_user' => self::topUser(),
            'top_rule' => self::topRule(),
        ];
    }

    /**
     * @notes 充值数据
     * @return array
     */
    public static function rechargeData()
    {
        $totalAmount = RechargeOrder::where(['pay_status' => PayEnum::ISPAID
        ])->sum('order_amount');
        $totalTimes = RechargeOrder::where(['pay_status' => PayEnum::ISPAID
        ])->count();
        return [
            'total_amount' => $totalAmount,
            'total_times' => $totalTimes
        ];
    }

    /**
     * @notes 用户充值榜
     * @return mixed
     */
    public static function topUser()
    {
        $field = 'u.nickname,u.avatar,sum(ro.order_amount) as total_amount';
        $lists = RechargeOrder::alias('ro')
            ->leftJoin('user u', 'u.id = ro.user_id')
            ->field($field)
            ->where('pay_status', PayEnum::ISPAID)
            ->group('ro.user_id')
            ->order('total_amount', 'desc')
            ->limit(10)
            ->select()
            ->toArray();

        foreach($lists as &$item) {
            if($item['avatar']){
                $item['avatar'] = FileService::getFileUrl($item['avatar']);
            }
        }

        return $lists;
    }

    /**
     * @notes 充值规则榜
     * @return mixed
     */
    public static function topRule()
    {
        $field = 'rt.money, count(ro.id) as total_num';
        $lists =RechargeTemplate::alias('rt')
            ->leftJoin('recharge_order ro', 'ro.template_id = rt.id')
            ->field($field)
            ->where('pay_status', PayEnum::ISPAID)
            ->group('rt.id')
            ->order('total_num', 'desc')
            ->limit(10)
            ->select()
            ->toArray();

        return $lists;
    }
}