<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020/6/24
 *
 * 
 */

namespace app\controller\merchant;


use app\common\repositories\merchant\MerchantRepository;
use crmeb\basic\BaseController;
use app\common\repositories\store\order\StoreOrderProductRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\merchant\order\OrderMerchantRepository;
use app\common\repositories\store\product\ProductRepository;
use app\common\repositories\user\UserRelationRepository;
use app\common\repositories\user\UserVisitRepository;
use think\facade\Db;
use think\App;

/**
 * Class Common
 * @package app\controller\merchant
 * @author xaboy
 * @day 2020/6/25
 */
class Common extends BaseController
{
    /**
     * @var int|null
     */
    protected $merId;

    /**
     * Common constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->merId = $this->request->merId() ?: null;


    }


    /**今日昨日统计+总贡献值记录=总金豆记录
     * @param null $merId
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function zuorijinri()
    {
        $merId = $this->merId;

        // $list['gongxian'] = Db::name('user_sign_gongxian')->where('mer_id', $merId)->sum('number');
        $list['jingdou'] = Db::name('user_sign_jingdou')->where('mer_id', $merId)->where('status',1)->sum('number');
        $list['fenrunzhi'] = Db::name('order_merchant')->where('mer_id', $merId)->where('paid', 1)->sum('available');
    
        $list['xianxia'] = Db::name('order_merchant')->where('mer_id', $merId)->where('paid', 1)->count();
        $list['xianshang'] = Db::name('store_order')->where('mer_id', $merId)->where('paid', 1)->count();


        return app('json')->success(compact('merId', 'list'));
    }



     /**收银台最新记录接口
     * @param null $merId
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function zuixinjilu()
    {
        $merId = $this->merId;
        // $merId = 476;
        $pageNum = $this->request->param('pageNum') ?: 1;
        $pageSize = $this->request->param('pageSize') ?: 10;
     
        $query = Db::name('order_merchant');
        $count = $query->where('mer_id', $merId)->count();
        $list = $query->page($pageNum, $pageSize)->order('id desc')->where('mer_id', $merId)->where('paid', 1)->select();
        $list = $list->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['pv'] = Db::name('user_sign_gongxian')->where('order_id', $v['id'])->value('pv') ?? 0;
            // $list[$k]['gongxian'] = Db::name('user_sign_gongxian')->where('mer_id', $v['mer_id'])->where('order_id', $v['id'])->value('number') ?? 0;
            $list[$k]['fenrunzhi'] = $v['available'];
            $list[$k]['jingdou'] = Db::name('user_sign_jingdou')->where('mer_id', $v['mer_id'])->where('order_id', $v['id'])->value('number') ?? 0;
        }
     
        return app('json')->success(compact('merId', 'list', 'count'));
    }



    /**
     * @param null $merId
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function main($merId = null)
    {
        $all = $this->mainGroup('', $merId ?? $this->merId);
        $today = $this->mainGroup('today', $merId ?? $this->merId);
        $yesterday = $this->mainGroup('yesterday', $merId ?? $this->merId);
        $lastWeek = $this->mainGroup(date('Y-m-d', strtotime('- 7day')), $merId ?? $this->merId);
        $lastWeekRate = [];
        foreach ($lastWeek as $k => $item) {
            if ($item == $today[$k])
                $lastWeekRate[$k] = 0;
            else if ($item == 0)
                $lastWeekRate[$k] = $today[$k];
            else if ($today[$k] == 0)
                $lastWeekRate[$k] = -$item;
            else
                $lastWeekRate[$k] = bcdiv(bcsub($today[$k], $item, 2), $item, 2);
        }
        $day = date('Y-m-d');
        return $merId ? compact('all', 'today', 'yesterday', 'lastWeekRate', 'day') : app('json')->success(compact( 'all', 'today', 'yesterday', 'lastWeekRate', 'day'));
    }

    /**
     * 商户后台顶部统计
     * @param $date
     * @param $merId
     * @return array
     * @author xaboy
     * @day 2020/6/25
     */
    public function mainGroup($date, $merId)
    {
        $userVisitRepository = app()->make(UserVisitRepository::class);
        /** @var StoreOrderRepository $repository */
        $repository = app()->make(StoreOrderRepository::class);
        $orderMerchantRepository = app()->make(OrderMerchantRepository::class);
        $relationRepository = app()->make(UserRelationRepository::class);
        $merchRepository = app()->make(MerchantRepository::class);

        $orderNum = $repository->dayOrderNum($date, $merId);

        $payPrice = $repository->dayOrderPrice($date, $merId);

        $payMoney = $repository->dayOrderMoney($date, $merId);
        $payJingDou = $repository->dayOrderJingDou($date, $merId);
        $payVR = $repository->dayOrderVR($date, $merId);
        $payJiFen = $repository->dayOrderJiFen($date, $merId);

        $payUser = $repository->dayOrderUserNum($date, $merId);

        $orderNumNew = $orderMerchantRepository->dayOrderNum($date, $merId);
        $payPriceNew = $orderMerchantRepository->dayOrderPrice($date, $merId);
        $payUserNew = $orderMerchantRepository->dayOrderUserNum($date, $merId);
        $fenrunNum = $orderMerchantRepository->dayOrderAvailable($date, $merId);

        $jingdouNum = Db::name('user_sign_jingdou')->when($merId, function ($query, $merId) {
            $query->where('mer_id', $merId);
        })->when($date, function ($query, $day) {
            getModelTime($query, $day, 'addtime');
        })->sum('number');

        $visitNum = $userVisitRepository->dateVisitUserNum($date, $merId);
        $likeStore = $relationRepository->dayLikeStore($date, $merId);
        $lockUserNum = $merchRepository->get_lock_num($date, $merId);

        return compact(
            'orderNum',
            'payPrice',
            'payUser',
            'orderNumNew',
            'payPriceNew',
            'payUserNew',
            'fenrunNum',
            'jingdouNum',
            'visitNum',
            'likeStore',
            'lockUserNum',
            'payMoney',
            'payJingDou',
            'payVR',
            'payJiFen'
        );
    }

    /**
     * @param StoreOrderRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function order(StoreOrderRepository $repository)
    {
        $date = $this->request->param('date') ?: 'lately7';
        $time = getDatesBetweenTwoDays(getStartModelTime($date), date('Y-m-d'));
        $list = $repository->orderGroupNum($date, $this->merId)->toArray();
        $list = array_combine(array_column($list, 'day'), $list);
        $data = [];
        foreach ($time as $item) {
            $data[] = [
                'day' => $item,
                'total' => $list[$item]['total'] ?? 0,
                'user' => $list[$item]['user'] ?? 0,
                'pay_price' => $list[$item]['pay_price'] ?? 0
            ];
        }
        return app('json')->success($data);
    }

    /**
     * @param UserRelationRepository $repository
     * @param StoreOrderRepository $orderRepository
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function user(UserRelationRepository $repository, StoreOrderRepository $orderRepository)
    {
        $date = $this->request->param('date', 'today') ?: 'today';
        $visitUser = $repository->dateVisitStore($date, $this->merId);
        $orderUser = $orderRepository->orderUserNum($date, null, $this->merId);
        $orderPrice = $orderRepository->orderPrice($date, null, $this->merId);
        $payOrderUser = $orderRepository->orderUserNum($date, 1, $this->merId);
        $payOrderPrice = $orderRepository->orderPrice($date, 1, $this->merId);
        $userRate = $payOrderUser ? bcdiv($payOrderPrice, $payOrderUser, 2) : 0;
        $orderRate = $visitUser ? bcdiv($orderUser, $visitUser, 2) : 0;
        $payOrderRate = $orderUser ? bcdiv($payOrderUser, $orderUser, 2) : 0;
        return app('json')->success(compact('visitUser', 'orderUser', 'orderPrice', 'payOrderUser', 'payOrderPrice', 'payOrderRate', 'userRate', 'orderRate'));
    }

    /**
     * @param StoreOrderRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function userRate(StoreOrderRepository $repository)
    {
        $date = $this->request->param('date') ?: 'today';
        $uids = $repository->orderUserGroup($date, 1, $this->merId)->toArray();
        $oldUids = $repository->oldUserIds(array_column($uids, 'uid'), $this->merId);
        $user = count($uids);
        $oldUser = count($oldUids);
        $totalPrice = 0;
        $oldTotalPrice = 0;
        foreach ($uids as $uid) {
            $totalPrice = bcadd($uid['pay_price'], $totalPrice, 2);
            if (in_array($uid['uid'], $oldUids))
                $oldTotalPrice = bcadd($uid['pay_price'], $oldTotalPrice, 2);

        }
        $newTotalPrice = bcsub($totalPrice, $oldTotalPrice);
        $newUser = $user - $oldUser;
        return app('json')->success(compact('newTotalPrice', 'newUser', 'oldTotalPrice', 'oldUser', 'totalPrice', 'user'));
    }

    /**
     * @param StoreOrderProductRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function product(StoreOrderProductRepository $repository)
    {
        $date = $this->request->param('date', 'today') ?: 'today';
        return app('json')->success($repository->orderProductGroup($date, $this->merId));
    }

    public function productVisit(UserVisitRepository $repository)
    {
        $date = $this->request->param('date', 'today') ?: 'today';
        return app('json')->success($repository->dateVisitProductNum($date, $this->merId));
    }

    /**
     * @param ProductRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function productCart(ProductRepository $repository)
    {
        $date = $this->request->param('date', 'today') ?: 'today';
        return app('json')->success($repository->cartProductGroup($date, $this->merId));
    }
}