<?php

namespace app\api\controller\mine;

use app\api\controller\PayController;
use app\api\middleware\Auth;
use app\api\service\UserService;
use app\api\service\UtilService;
use app\api\validate\CourseValidate;
use app\api\validate\UserValidate;
use app\BaseController;
use app\model\Course as CourseModel;
use app\model\project\Mail;
use app\model\project\UserAccount;
use app\model\project\UserMoneyLog;
use app\model\project\UserSmrz;
use app\model\project\UserWithdrawal;
use app\Request;
use app\model\project\User as UserModel;

class User extends BaseController
{

    protected $middleware = [
        Auth::class,
    ];

    public function getUserInfo(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['token']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->header();

        $user = UserService::getUserInfo($data['token']);
        if (!$user)
        {
            return $this->returnMsg('token无效',0);
        }

        return $this->returnMsg('操作成功',1,$user);
    }

    public function updateUserInfo(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['updateField','updateValue']);
        if ($vo !== true) {
            return $vo;
        }

        $data = $request->param();

        $res = UserService::updateUserInfo($data['updateField'],$data['updateValue']);

        return $this->returnMsg('操作成功',1,$res);
    }

    public function bindZfb(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['zfb']);
        if ($vo !== true) {
            return $vo;
        }

        if (UserAccount::where(['user_id'=>$request->userId,'is_del'=>0])->count())
        {
            return $this->returnMsg('请勿重复提交');
        }

        $data = $request->param();

        $data['type'] = 0;
        $data['account'] = $data['zfb'];
        $data['user_id'] = $request->userId;
        unset($data['zfb']);

        $res = UserAccount::create($data);

        return $this->returnMsg('操作成功',1,$res);

    }

    public function editMobile(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['mobile','code']);
        if ($vo !== true) {
            return $vo;
        }

        $data = $request->param();

        //check sms

        $res = UserService::updateUserInfo('mobile',$data['mobile']);

        return $this->returnMsg('操作成功',1,$res);

    }

    public function realUser(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['realname','idcard','idcard_q','idcard_h']);
        if ($vo !== true) {
            return $vo;
        }
        if (UserSmrz::where(['user_id'=>$request->userId,'is_del'=>0])->count())
        {
            return $this->returnMsg('请勿重复提交');
        }

        $data = $request->param();

        $data['user_id'] = $request->userId;

        $res = UserSmrz::create($data);

        return $this->returnMsg('操作成功',1,$res);

    }

    public function withdrawal(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['amount','txType']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();

        $userId = $request->userId;

        $userInfo = UserModel::where(['id'=>$userId,'is_del'=>0])->find();
        if ($userInfo['money']< $data['amount'])
        {
            return $this->returnMsg('余额不足');
        }


        $count = UserMoneyLog::where(['user_id'=>$userId,'type'=>1])
            ->whereBetween('createtime', [strtotime('today'), strtotime('tomorrow') - 1])
            ->count();
        if ($count)
        {
            return $this->returnMsg('每天只能提现一次');
        }

        $UserWithdrawalModel = new UserWithdrawal();

        $sum = $UserWithdrawalModel->where(['user_id'=>$userId,'type'=>1])
            ->whereBetween('createtime', [strtotime('today'), strtotime('tomorrow') - 1])
            ->sum('money');

        if ($sum > 10000)
        {
            return $this->returnMsg('超出每日限额');
        }
        $userAccount = UserAccount::where(['user_id'=>$userId,'is_del'=>0,'type'=>$data['txType']])->find();

        $commission = vconfig('commission') ? : 0;
//        halt($commission);

        $res = $UserWithdrawalModel->applyWithdrawal($userId,$data['amount'],$data['txType'],$userAccount['account'],$userInfo['realname'],$commission,$userInfo['money']);

        if (!$res['status'])
        {
            return $this->returnMsg($res['msg']);
        }

        return $this->returnMsg('success',1);

    }

    //站内信
    public function getUserMailList(Request $request)
    {
        $page = $request->param('page/d', 1);
        $pageSize = $request->param('pageSize/d', 10);

        $list = Mail::order('createtime','desc')
            ->paginate([
            'page' => $page,
            'list_rows' => $pageSize
        ]);

        return $this->returnMsg('success',1,$list);
    }

    public function buyCourse(\think\Request $request)
    {

        $vo = (new CourseValidate())->goCheck(['course_id']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();
        $userId = $request->userId;


        $course = CourseModel::where([
            'id' => $data['course_id'],
            'status' => 3,
            'is_sell' => 1,
            'is_del' => 0
        ])->find();

        if (!$course) {
            return $this->returnMsg('课程不存在');
        }
        if ($course['price']<=0)
        {
            return $this->returnMsg('免费课程无需购买');
        }

        // 验证购买状态（1表示视频类型）
        if (UtilService::checkPurchase($userId, $data['course_id'], 1)) {
            return $this->returnMsg('请勿重复购买');
        }
        $params = [
            'order_id'=>$data['course_id'],
            'order_type'=>1,
            'pay_method'=>$data['pay_method'],
            'amount'=>$course['price'],
            'user_id'=>$userId,
        ];

        $payController = new PayController();

        return $payController->create($params);

    }


}