<?php

namespace app\api\logic\user;


use app\common\{logic\BaseLogic,
    model\dict\DictData,
    model\finance\CapitalFlow,
    model\store_finance_flow\StoreFinanceFlow,
    model\store_order\StoreOrder,
    model\system_store\DeliveryService,
    model\system_store\SystemStore,
    model\system_store\SystemStoreStaff,
    model\user\User,
    model\user\UserRecharge,
    model\user\UserShip,
    service\wechat\WeChatMnpService};

/**
 * 会员逻辑层
 * Class UserLogic
 * @package app\shopapi\logic
 */
class UserLogic extends BaseLogic
{

    /**
     * @notes 获取小程序手机号
     * @param array $params
     * @return bool
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     * @author 段誉
     * @date 2023/2/27 11:49
     */
    public static function getMobileByMnp(array $params)
    {
        try {
            $response = (new WeChatMnpService())->getUserPhoneNumber($params['code']);
            $phoneNumber = $response['phone_info']['purePhoneNumber'] ?? '';
            if (empty($phoneNumber)) {
                throw new \Exception('获取手机号码失败');
            }

            $user = User::where([
                ['mobile', '=', $phoneNumber],
                ['id', '<>', $params['user_id']]
            ])->findOrEmpty();

            if (!$user->isEmpty()) {
                throw new \Exception('手机号已被其他账号绑定');
            }

            // 绑定手机号
            User::update([
                'id' => $params['user_id'],
                'mobile' => $phoneNumber
            ]);

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


    public static function info($uid)
    {
        $data =  User::with(['userShip'])->where('id',$uid)
            ->field('id,avatar,real_name,nickname,account,mobile,sex,login_ip,now_money,total_recharge_amount,user_ship
            ,purchase_funds,integral')
            ->find();
        //判断是不是员工
        if($data){
            $data = $data->toArray();
            $all =UserShip::field('id,title,limit')->select()->toArray();
            $new =  self::getNextArrayByID($all,$data['user_ship']);
            $data['next_level'] = '';
            $data['next_limit'] = 0;
            if($new){
                $data['next_level'] = $new['title'];
                $data['next_limit'] = $new['limit'] - $data['total_recharge_amount'];
            }
            $data['is_staff'] = 0;
            $data['store_id'] = 0;
            if(isset($data['mobile']) && $data['mobile']){
                $check = DeliveryService::where('phone',$data['mobile'])->find()??[];
                if ($check){
                    $data['is_staff'] = 1;
                    $data['store_id'] = $check['store_id'];
                }
            }
            $data['return_money'] = StoreFinanceFlow::
                    where(['user_id'=>$uid,'status'=>0,'financial_pm'=>0])
                    ->sum('number');

        }else{
            $data = [];
        }
       return $data;
    }


    public static function  recharge($param)
    {
        $param['order_id']  = getNewOrderId('rc');
        $param['recharge_type']  = 'wechat';
        return UserRecharge::create($param);

    }


    public static function getNextArrayByID($arr, $id) {
        foreach ($arr as $key => $value) {
            if ($value['id'] == $id) {
                if ($key + 1 < count($arr)) {
                    return $arr[$key + 1];
                }
                return null;
            }
        }
        return null;
    }

    public static function capital_list($uid,$params)
    {
        $query = CapitalFlow::where('uid',$uid);
        $count = $query->count();
        $data = $query
            ->page($params['page_no'], $params['page_size'])
            ->select()->toArray();
        foreach ($data as &$value){
            if($value['link_type'] == 'order'){
                $value['order_sn'] = StoreOrder::where('id',$value['link_id'])
                    ->value('order_id');
            }
        }
        return [
            'count'=>$count,
            'data'=>$data,
        ];
    }

    public static function capital_count($uid)
    {
        $query = CapitalFlow::where('uid',$uid);
        $recharge = $query->where('link_type','user_recharge')
            ->sum('amount')??0;
        $query1 = CapitalFlow::where('uid',$uid);
        $orderConsumption = $query1->where('link_type','<>','user_recharge')
            ->sum('amount')??0;
        return [
            'recharge'=>$recharge,
            'order'=>$orderConsumption,
        ];
    }


    public static function rechange_level()
    {
        return DictData::where(['type_value'=>'recharge','status'=>1])
            ->select()->toArray();
    }


}