<?php

namespace app\statistics\controller;

use app\admin\logic\statistic\TradeStatisticLogic;
use app\common\controller\BaseLikeController;
use app\common\model\store_branch_product\StoreBranchProduct;
use app\common\model\store_order\StoreOrder;
use app\common\model\store_order_cart_info\StoreOrderCartInfo;
use app\common\model\store_product\StoreProduct;
use app\common\model\system_store\SystemStore;
use app\common\model\user\User;
use app\common\model\user_recharge\UserRecharge;
use app\statistics\logic\OrderLogic;
use app\statistics\logic\ProductLogic;
use app\statistics\logic\UserLogic;
use DateTime;
use think\facade\Db;

class IndexController extends BaseLikeController
{

    // public $store_id = 0;

    public function index()
    {
        $time = $this->request->get('date', date('Y-m-d'));
        $store_id = $this->request->get('store_id', 0);
        if ($store_id) {
            $where['store_id'] = $store_id;
        }
        $where['paid'] = 1;
        $res = OrderLogic::dayPayPrice($where, $time);
        if (OrderLogic::hasError()) {
            return $this->fail(OrderLogic::getError()); //获取错误信息并返回错误信息
        }
        if ($store_id) {
            $name = SystemStore::where('id', $store_id)->value('name');
            $title = $name . '农(特)产品交易大数据';
        } else {
            $title = '泸县农(特)产品交易大数据';
        }
        return $this->success('ok', ['dayPayPrice' => $res, 'title' => $title]);
    }


    /**
     * 地方商品数量统计
     */
    public function product_count_sotre_count()
    {
        $time = $this->request->get('date', date('Y-m-d'));
        $data = [
            ['street_name' => '喻寺镇', 'product_count' => StoreBranchProduct::where('store_id', 1)->where('create_time', '<=', strtotime($time))->count()],
            ['street_name' => '立石镇', 'product_count' => StoreBranchProduct::where('store_id', 2)->where('create_time', '<=', strtotime($time))->count()],
            ['street_name' => '百和镇', 'product_count' => StoreBranchProduct::where('store_id', 3)->where('create_time', '<=', strtotime($time))->count()],
            ['street_name' => '得胜镇', 'product_count' => StoreBranchProduct::where('store_id', 5)->where('create_time', '<=', strtotime($time))->count()],
            ['street_name' => '玄滩镇', 'product_count' => StoreBranchProduct::where('store_id', 6)->where('create_time', '<=', strtotime($time))->count()],
            ['street_name' => '云锦镇', 'product_count' => StoreBranchProduct::where('store_id', 7)->where('create_time', '<=', strtotime($time))->count()],
        ];
        $townProductCount = StoreProduct::where('create_time', '<=', strtotime($time))->count();
        $product_count = StoreBranchProduct::where('create_time', '<=', strtotime($time))->group('product_id')->order('total_sales desc')->limit(20)->field('image,product_id,store_name,sum(sales) as total_sales')->select();
        $productRankingTotal = 0;
        foreach ($product_count as $item) {
            $productRankingTotal += $item['total_sales'];
        }
        return $this->success('ok', ['townProductCountList' => $data, 'productRankingList' => $product_count, 'townProductCount' => $townProductCount, 'productRankingTotal' => $productRankingTotal]);
    }
    public function user()
    {
        $time = $this->request->get('date', date('Y-m-d'));
        $store_id = $this->request->get('store_id', 0);
        $today = strtotime($time);
        $dates = [];
        $dates_two = [];
        // 循环输出前5天的日期
        for ($i = 0; $i <= 4; $i++) {
            // 计算前第$i天的日期时间戳
            $timestamp = $today - ($i * 86400); // 86400秒等于1天

            // 将时间戳格式化为日期
            $date = date('Y-m-d', $timestamp);
            $dates_two[] = date('n.j', $timestamp);
            $dates[] = $date;
        }
        $where = [];
        if ($store_id) {
            $where['store_id'] = $store_id;
        }
        $res = UserLogic::userCount($where, $dates);
        if (UserLogic::hasError()) {
            return $this->fail(UserLogic::getError()); //获取错误信息并返回错误信息
        }
        $res['date'] = $dates_two;
        $money = Db::name('demo_order_money')->where($where)->sum('money');
        $where['paid'] = 1;
        // $pay_price=Db::connect('demo')->name('store_order')->where($where)->whereDay('create_time')->sum('pay_price');
        $price = Db::connect('demo')->name('user_recharge')->where($where)->sum('price');
        $res['dayPayPrice'] = bcadd($money, $price, 2);
        return $this->success('ok', $res);
    }

    /**
     * 中间商品统计
     */
    public function product_count()
    {
        $time = $this->request->get('date', date('Y-m-d'));
        $store_id = $this->request->get('store_id', 0);
        $where = [];
        if ($store_id) {
            $where['store_id'] = $store_id;
        }
        $res = ProductLogic::Count($where, $time);
        if (ProductLogic::hasError()) {
            return $this->fail(ProductLogic::getError()); //获取错误信息并返回错误信息
        }
        return $this->success('ok', $res);
    }
    /**
     * 订单统计
     */
    public function order_user_num_count()
    {
        $time = $this->request->get('date', date('Y-m-d'));
        $store_id = $this->request->get('store_id', 0);
        $where = [];
        if ($store_id) {
            $where['store_id'] = $store_id;
        }
        $where['recharge_type'] = 'INDUSTRYMEMBERS';
        $where['status'] = 1;
        $where['paid'] = 1;
        $where[] = ['price', '>', 1];
        // $res = OrderLogic::Count($where,$time);
        // if (ProductLogic::hasError()) {
        //     return $this->fail(ProductLogic::getError()); //获取错误信息并返回错误信息
        // }

        $res = Db::connect('demo')->name('user_recharge')->where($where)->limit(20)->order('id desc')->select()->each(function ($item) {
            if ($item['uid']) {
                $find = Db::connect('demo')->name('user')->where('id', $item['uid'])->field('real_name,nickname')->find();
                $item['nickname'] = $find['real_name'] ?? '';
                if ($item['nickname'] == '') {
                    $item['nickname'] = $find['nickname'] ?? '';
                } else {
                    $nickname = $item['nickname'];
                    $item['nickname'] = $this->hideMiddleName($nickname);
                }
            } else {
                $item['nickname'] = '';
            }
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            return $item;
        });
        return $this->success('ok', $res?->toArray());
    }
    /**
     * 商品销量排行榜统计
     */
    public function sales_ranking()
    {
        $time = $this->request->get('date');
        $store_id = $this->request->get('store_id', 0);
        $where['paid'] = 1;
        if ($store_id) {
            $where['store_id'] = $store_id;
        }
        // $res = OrderLogic::sales($where, $time);
        // if (ProductLogic::hasError()) {
        //     return $this->fail(ProductLogic::getError()); //获取错误信息并返回错误信息
        // }
        $select = Db::connect('demo')->name('store_order')->where($where)->limit(20)->order('id desc')
            ->field('id,order_id,pay_price,create_time')->select()->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            })->toArray();
        return $this->success('ok', $select);
    }
    /**
     * 成交用户数据
     */
    public function user_trade_count()
    {
        $store_id = $this->request->get('store_id', 0);
        $date = $this->request->get('date', '');

        if ($date != '') {
            $where = ['create_time' => ['start_time' => $date, 'end_time' => $date . ' 23:59:59']];
            $where2 = ['create_time' => ['start_time' => $date, 'end_time' => $date . ' 23:59:59']];
        } else {
            $where = ['create_time' => 'today'];
            $where2 = ['create_time' => 'yestoday'];
        }

        if ($store_id) {
            $where['store_id'] = $store_id;
            $where2['store_id'] = $store_id;
        }
        $logic = (new TradeStatisticLogic());
        $leftToday = $logic->getTopLeftTrade($where);

        $leftyestoday = $logic->getTopLeftTrade($where2);
        $totalleft = [$leftToday, $leftyestoday];
        foreach ($totalleft as $k => $v) {
            $left['name'] = "当日订单金额";
            $left['x'] = $v['curve']['x'];
            $left['series'][$k]['money'] = round($v['total_money'], 2);
            $left['series'][$k]['value'] = array_values($v['curve']['y']);
        }

        return $this->data($left);
    }
    /**
     * 当日订单金额
     */
    public function street_currday_order_count()
    {
        $time = $this->request->get('date', date('Y-m-d'));
        $store_id = $this->request->get('store_id', 0);
        $where = [];
        if ($store_id) {
            $where['store_id'] = $store_id;
        }
        $res = OrderLogic::Currday($where, $time);
        if (ProductLogic::hasError()) {
            return $this->fail(ProductLogic::getError()); //获取错误信息并返回错误信息
        }
        return $this->success('ok', $res);
    }

    public function store_order_day()
    {
        $time = $this->request->get('date', date('Y-m'));
        $arr = SystemStore::where('is_show', 1)->field('id,name street_name')->select()
            ->each(function ($item) use ($time) {
                $res = StoreOrder::where('paid', 1)->where('refund_status', 0)->where('store_id', $item['id'])->whereDay('create_time', $time)->field('count(id) count,sum(pay_price) price')->find();
                $month = StoreOrder::where('paid', 1)->where('refund_status', 0)->where('store_id', $item['id'])->whereMonth('create_time', $time)->field('count(id) count,sum(pay_price) price')->find();
                $item['dayOrderAmount'] = $res['price'] ?? 0;
                $item['dayOrderCount'] = $res['count'] ?? 0;
                $item['monthOrderAmount'] = $month['price'] ?? 0;
                $item['monthOrderCount'] = $month['count'] ?? 0;
                return $item;
            });
        return $this->success('ok', $arr?->toArray());
    }
    public function store_order_day_two()
    {
        $arr = SystemStore::where('is_show', 1)->field('id,name street_name')->select()
            ->each(function ($item) {
                $today_order_amount = StoreOrder::where('paid', 1)->where('refund_status', 0)->where('store_id', $item['id'])->whereDay('create_time')->sum('pay_price');
                $yesterday_order_amount = StoreOrder::where('paid', 1)->where('refund_status', 0)->where('store_id', $item['id'])->whereMonth('create_time', 'yesterday')->sum('pay_price');
                $item['today_order_amount'] = $today_order_amount;
                $item['yesterday_order_amount'] = $yesterday_order_amount;
                return $item;
            });
        return $this->success('ok', $arr?->toArray());
    }

    /**
     * 格式化时间
     * @param $time
     * @return string
     */
    public function getDay($time)
    {
        if (strstr($time, '-') !== false) {
            [$startTime, $endTime] = explode('-', $time);
            if (!$startTime && !$endTime) {
                return date("Y/m/d", strtotime("-30 days", time())) . '-' . date("Y/m/d", time());
            } else {
                if ($startTime == $endTime) {
                    return $startTime . '-' . $endTime . ' 23:59:59';
                } else {
                    return $startTime . '-' . $endTime;
                }
            }
        } else {
            return date("Y/m/d", strtotime("-30 days", time())) . '-' . date("Y/m/d", time());
        }
    }

    function hideMiddleName($name)
    {
        $strlen = mb_strlen($name); // 获取字符串长度
        $firstStr = mb_substr($name, 0, 1); // 获取名字的第一个字符
        $lastStr = mb_substr($name, -1, 1); // 获取名字的最后一个字符
        $replaceStr = ''; // 初始化替换字符串
        if ($strlen == 2) {
            return $firstStr . '*';
        } else {
            for ($i = 0; $i < $strlen - 2; $i++) {
                $replaceStr .= '*'; // 根据需要替换的字符数量,生成相应数量的星号
            }
        }


        return $firstStr . $replaceStr . $lastStr; // 返回替换后的名字
    }
}