<?php
namespace App\Http\Controllers\Api;
use App\Models\Setting;
use App\Models\ShareConfig;
use App\Models\User;
use App\Models\UserShare;
use App\Models\UserVip;
use App\Models\UserWithdraw;
use Carbon\Carbon;
use EasyWeChat\Factory;
use function Symfony\Component\Translation\t;

class UserController extends Controller
{
    public function get()
    {
        $user = auth('api')->user();

        $user = User::with(['parent'])->where('id',$user['id'])->first()->toArray();
        return out($user);
    }


    // 购买记录
    public function memberRecord()
    {
        $user = auth('api')->user();

        $record = UserVip::where('user_id',$user['id'])
            ->where('status',1)
            ->first();
        if(empty($record)){
            return out();
        }
        $record = $record->toArray();

        return out([
            'order_fee' => $record['order_fee'],
            'buy_time' => $record['pay_at'],
        ]);
    }

    // 余额
    public function overage()
    {
        $user = auth('api')->user();
        $shareConfig = ShareConfig::first()->toArray();
        $user = User::where('id',$user['id'])->first()->toArray();

        return out([
            'overage' => $user['overage'],
            'desc' => $shareConfig['share_desc']
        ]);
    }

    // 收益
    public function income()
    {
        $user = auth('api')->user();

        $builder = UserShare::with(['child'])->where('user_id',$user['id']);

        $data = $builder->paginate($req['per_page'] ?? 15);
        $total_num = $builder->sum('id');
        $custom = collect([
            'total_num'   => $total_num,
        ]);
        $data = $custom->merge($data);

        return out($data);
    }

    // 购买会员
    public function buy()
    {
        $user = auth('api')->user();
        $shareConfig = ShareConfig::first()->toArray();

        \DB::beginTransaction();
        $app = Factory::payment(config('wechat.payment.default'));
        $jssdk = $app->jssdk;

        try {

            $order = UserVip::where('user_id', $user['id'])->first();
            if(empty($order) || empty($order->prepay_id)){
                $orderId = get_order_id($user['id']);
                if(empty($order)){
                    $order = UserVip::create([
                        'order_id' => $orderId,
                        'user_id' => $user['id'],
                        'order_fee' => $shareConfig['member_price']
                    ]);
                }else{
                    $order->order_id = $orderId;
                }
                $payment = $app->order->unify([
                    'body' => '三哥桥梁-购买会员',
                    'out_trade_no' => $orderId,
                    'total_fee' => $shareConfig['member_price']*100, // 分
                    'notify_url' => config('wechat.payment.default.notify_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                    'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                    'openid' => $user['openid'],
                ]);

                if($payment['return_code'] != "SUCCESS" || $payment['result_code'] != 'SUCCESS'){
                    throw new \Exception($payment['return_msg']);
                }

                $order->prepay_id = $payment['prepay_id'];
                $order->save();
            }

            if($order->status == 0){
                $data = $jssdk->bridgeConfig($order->prepay_id,false);
            }else{
                return out([],10013,'您已经是会员了！');
            }

            \DB::commit();
        }catch (\Exception $ex){
            \DB::rollBack();
            return out([],10012,$ex->getMessage());
        }

        return out($data);
    }

    // 查询购买订单
    public function query()
    {
        $user = auth('api')->user();
        $order = UserVip::where('user_id', $user['id'])->first();
        if(!$order){
            return out(2);
        }
        $order = $order->toArray();

        return out($order['status']);
    }

    // 推广人数
    public function shares()
    {
        $user = auth('api')->user();
        $builder = User::where('parent_id', $user['id'])->orderBy('become_child_at','desc');
        $data = $builder->paginate($req['per_page'] ?? 15);
        $total_num = $builder->sum('id');
        $custom = collect([
            'total_num'   => $total_num,
        ]);
        $data = $custom->merge($data);
        return out($data);
    }


    public function bind()
    {
        $req = request()->post();
        $this->validate(request(), [
            'scene'      => 'required',
        ]);
        $user = auth('api')->user();
        $user = User::where('id', $user['id'])->first();
        if($user->parent_id){
            return out();
        }
        $parent = User::where('scene_code', $req['scene'])->first();
        if(!$parent){
            return out();
        }
        if($parent->id == $user->id){
            return out();
        }

        $user->parent_id = $parent->id;
        $user->become_child_at = Carbon::now()->toDateTimeString();
        $user->save();

        return out();
    }

    public function bindPhone()
    {
        $req = request()->post();
        $this->validate(request(), [
            'encryptedData' => 'required',
            'iv'            => 'required',
        ]);
        $app = Factory::miniProgram(config('wechat.mini_program.default'));
        $user = auth('api')->user()->makeVisible('remember_token');
        $decryptedData = $app->encryptor->decryptData($user['remember_token'], $req['iv'], $req['encryptedData']);
        $user = User::where('id', $user['id'])->first();
        if($user->phone_num != $decryptedData['phoneNumber']) {
            $user->phone_num = $decryptedData['phoneNumber'];
            $user->save();
        }
        return out($user);
    }


    public function update()
    {
        $req = request()->post();
        $this->validate(request(), [
            'encryptedData' => 'required',
            'iv'            => 'required',
        ]);
        $app = Factory::miniProgram(config('wechat.mini_program.default'));
        $user = auth('api')->user()->makeVisible('remember_token');
        $decryptedData = $app->encryptor->decryptData($user['remember_token'], $req['iv'], $req['encryptedData']);
        $user = User::where('id', $user['id'])->first();
        $user->nickname = $decryptedData['nickName'];
        $user->head_img = $decryptedData['avatarUrl'];
        $user->save();
        return out($user);
    }
}
