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


namespace app\adminapi\logic;

use app\adminapi\logic\distribution\DistributionDataLogic;
use app\common\enum\AfterSaleEnum;
use app\common\enum\DistributionOrderGoodsEnum;
use app\common\enum\OrderEnum;
use app\common\enum\UserTerminalEnum;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\AfterSale;
use app\common\model\Article;
use app\common\model\DistributionOrderGoods;
use app\common\model\Goods;
use app\common\model\GoodsComment;
use app\common\model\HomeVisitor;
use app\common\model\IndexVisit;
use app\common\model\Order;
use app\common\model\OrderGoods;
use app\common\model\User;
use app\common\service\ConfigService;
use app\common\service\FileService;

/**
 * 工作台
 * Class WorkbenchLogic
 * @package app\adminapi\logic
 */
class WorkbenchLogic extends BaseLogic
{
    /**
     * @notes 工作台
     * @return int[]
     */
    public static function index($adminInfo)
    {
        // 基本信息
        $sysInfo = self::sysInfo($adminInfo);
        // 今日数据
        $today = self::today();
        // 待办事项
        if(isActivePluginByPluginName('shop')){
            $pending = self::pending();
        }
        // 近15日营业额
        $business15 = self::business15();
        // 近15日访客数
        $visitor15 = self::visitor15();

        return [
            'shop_info' => $sysInfo,
            'today' => $today,
            'pending' => $pending??[],
            'business15' => $business15,
            'visitor15' => $visitor15,
        ];
    }


    public static function earningsData()
    {

    }

    /**
     * @notes 平台信息
     * @param $adminInfo
     * @return array
     */
    public static function sysInfo($adminInfo)
    {
        // 平台名称
        $name = ConfigService::get('shop', 'name');
        // 平台logo
        $logo = ConfigService::get('shop', 'logo');
        $logo = FileService::getFileUrl($logo);
        // 管理员名称
        $adminName = $adminInfo['name'];

        return [
            'name' => $name,
            'logo' => $logo,
            'admin_name' => $adminName,
        ];
    }

    /**
     * @notes 今日数据
     * @return array
     */
    public static function today()
    {
        // 话题数
        $topicCountIdsArray = Article::whereDay('create_time')->column('topic_ids');
        $todayTopicCount = count(array_unique(array_merge(...array_map(fn($item) => explode(',', $item), $topicCountIdsArray))));
        // 贴子数
        $todayArticles = Article::whereDay('create_time')->count();
        // 营业额
         $todayOrderAmount = Order::where('pay_status', YesNoEnum::YES)
             ->whereDay('create_time')
             ->sum('order_amount');
         // 成交订单数
        $todayOrderNum = Order::where('pay_status', YesNoEnum::YES)
            ->whereDay('create_time')
            ->count();
        // 访客数
        $visitor = IndexVisit::whereDay('create_time')->column('ip');
        $todayVisitor = count(array_unique($visitor));
        // 新增用户
        $todayNewUser = User::whereDay('create_time')->count();

        return [
            'today_topics' => $todayTopicCount,
            'today_articles' => $todayArticles,
            'today_visitor' => $todayVisitor,
            'today_new_user' => $todayNewUser,
            'today_order_num' => $todayOrderNum,
        ];
    }

    /**
     * @notes 待办事项
     * @return array
     */
    public static function pending()
    {
        // 待发货订单数
        $waitShipped = Order::where('order_status', OrderEnum::STATUS_WAIT_DELIVERY)->count();
        // 待审核售后申请
        $waitAudit = AfterSale::where('sub_status', AfterSaleEnum::SUB_STATUS_WAIT_SELLER_AGREE)->count();

        // 售罄商品
        $noStockGoods = Goods::where('total_stock', 0)->count();

        return [
            'wait_shipped' => $waitShipped,
            'wait_audit' => $waitAudit,
            'no_stock_goods' => $noStockGoods
        ];
    }

    /**
     * @notes 近15天营业额
     * @return array
     */
    public static function business15()
    {
        $today = new \DateTime();
        $todayStr = $today->format('Y-m-d') . ' 23:59:59';
        $todayDec15 = $today->add(\DateInterval::createFromDateString('-14day'));
        $todayDec15Str = $todayDec15->format('Y-m-d');

        $field = [
            "FROM_UNIXTIME(create_time,'%Y%m%d') as date",
            "sum(order_amount) as today_amount"
        ];
        $lists = Order::field($field)
            ->whereTime('create_time', 'between', [$todayDec15Str,$todayStr])
            ->where('pay_status', YesNoEnum::YES)
            ->group('date')
            ->select()
            ->toArray();

        $lists = array_column($lists, 'today_amount', 'date');
        $amountData = [];
        $date = [];
        for($i = 0; $i < 15; $i ++) {
            $today = new \DateTime();
            $targetDay = $today->add(\DateInterval::createFromDateString('-'. $i . 'day'));
            $targetDay = $targetDay->format('Ymd');
            $date[] = $targetDay;
            $amountData[] = $lists[$targetDay] ?? 0;
        }
        return [
            'date' => $date,
            'list' => [
                ['name' => '营业额', 'data' => $amountData]
            ]
        ];
    }

    /**
     * @notes 近15天访客数
     * @return mixed
     */
    public static function visitor15()
    {
        $today = new \DateTime();
        $todayStr = $today->format('Y-m-d') . ' 23:59:59';
        $todayDec15 = $today->add(\DateInterval::createFromDateString('-14day'));
        $todayDec15Str = $todayDec15->format('Y-m-d');

        $field = [
            "FROM_UNIXTIME(create_time,'%Y%m%d') as date",
            "ip"
        ];
        $lists = IndexVisit::field($field)
            ->distinct(true)
            ->whereTime('create_time', 'between', [$todayDec15Str,$todayStr])
            ->select()
            ->toArray();

        // 集合一天的IP
        $temp1 =  [];
        foreach ($lists as $item) {
            $temp1[$item['date']][] = $item['ip'];
        }
        // 统计数量
        $temp2 = [];
        foreach ($temp1 as $k => $v) {
            $temp2[$k] = count($v);
        }

        $userData = [];
        $date = [];
        for($i = 0; $i < 15; $i ++) {
            $today = new \DateTime();
            $targetDay = $today->add(\DateInterval::createFromDateString('-'. $i . 'day'));
            $targetDay = $targetDay->format('Ymd');
            $date[] = $targetDay;
            $userData[] = $temp2[$targetDay] ?? 0;
        }
        return [
            'date' => $date,
            'list' => [
                ['name' => '访客数', 'data' => $userData]
            ]
        ];
    }

    /**
     * @notes 帖子排行榜
     * @return mixed
     */
    public static function topArticleTop50($params)
    {

        $lists = Article::alias('a')->with(['user'])
            ->where('a.status', YesNoEnum::YES)
            ->order('visit', 'desc')
            ->limit(50)
            ->page($params['page_no'], $params['page_size'])
            ->select()
            ->toArray();

        $count = Article::alias('a')
            ->where('a.status', YesNoEnum::YES)
            ->order('visit', 'desc')
            ->limit(50)
            ->count();

        return [
            'lists' => $lists,
            'count' => $count,
            'page_no' => $params['page_no'],
            'page_size' => $params['page_size'],
        ];
    }

    /**
     * @notes 商品排行榜 - 按销售额排序
     * @return mixed
     */
    public static function topGoods50($params)
    {
        try{
            $field = [
                'g.id',
                'g.name',
                'g.image',
                'sum(og.goods_num)' => 'total_num',
                'sum(og.total_pay_price)' => 'total_pay_price',
            ];
            $lists = OrderGoods::alias('og')
                ->leftJoin('order o', 'o.id = og.order_id')
                ->leftJoin('goods g', 'g.id = og.goods_id')
                ->field($field)
                ->where('o.pay_status', YesNoEnum::YES)
                ->group('g.id,g.name,g.image')
                ->order('total_pay_price', 'desc')
                ->limit(50)
                ->page($params['page_no'], $params['page_size'])
                ->select()
                ->toArray();
    
            $count = OrderGoods::alias('og')
                ->leftJoin('order o', 'o.id = og.order_id')
                ->leftJoin('goods g', 'g.id = og.goods_id')
                ->field($field)
                ->where('o.pay_status', YesNoEnum::YES)
                ->group('g.id,g.name,g.image')
                ->order('total_pay_price', 'desc')
                ->limit(50)
                ->count();
        }catch(\Exception $e){
            return [];
        }

        return [
            'lists' => $lists,
            'count' => $count,
            'page_no' => $params['page_no'],
            'page_size' => $params['page_size'],
        ];
    }
}