<?php

/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2023/6/27
 * Time: 10:02
 */

namespace app\api\controller;

use app\admin\model\Admin;
use app\api\model\UsersDetailMoneyModel;
use app\api\model\UsersModel;
use \app\common\controller\Api;
use app\common\library\Redis\RedisMaster;
use app\common\library\wechat\WxUser;
use app\common\model\Config;
use EasyWeChat\Factory;
use fast\Random;
use \addons\fastim\library\Common as ImCommon;
use think\Db;
use think\Exception;
use think\Session;

class Users extends Api
{

    protected $noNeedLogin = ['wxlogin'];
    protected $noNeedRight = ['*'];
    protected $userinfo = null;
    protected $keeptime = 86400 * 180;


    /*
     * 微信小程序授权登录
     *
     */
    public function wxLogin()
    {
        $data = $this->request->param();
        $login_config = [
            'app_id' => $this->testConfig['appid'],
            'secret' => $this->testConfig['appSecret'],
        ];
        if (!$data['code'] && !$data['session_key']) {
            $this->error('授权失败');
        }
        Db::startTrans();
        try {
            if ($data['code'] && !$data['session_key']) {
                $session = $this->getOpenid($data['code']);
                $this->miniProgram = Factory::miniProgram($login_config);
                if (!$session['session_key'] || !$session['openid'] || !$data['encryptedData'] || !$data['iv']) {
                    $this->error('必要参数缺失');
                }
                //            $res = UsersModel::where(['unionid' => $session['unionid']])->find();
                $res = UsersModel::where(['wx_openid' => $session['openid']])->find();
                $token = Random::uuid(); //用户token
                $redis = RedisMaster::gi();
                $redis->select(7);
                if ($res) {
                    $prefix = 'user_token:' . $res['token'];
                    $uid = $redis->get($prefix);
                    if ($uid) {
                        $redis->delete($prefix);
                        $redis->setEx('user_token:' . $token, $this->keeptime, $uid);
                        Session::pull($prefix);
                        Session::set('user_token:' . $token, $uid, $this->keeptime);
                    } else {
                        $redis->setEx('user_token:' . $token, $this->keeptime, $res['id']);
                        Session::set('user_token:' . $token, $res['id'], $this->keeptime);
                    }
                    UsersModel::where(['id' => $res['id']])->update(['user_type' => 'wechat', 'session_key' => $session['session_key'], 'wx_openid' => $session['openid'], 'token' => $token, 'logintime' => time(), 'loginip' => $this->request->ip()]);
                    $userInfos = UsersModel::where(['id' => $res['id']])->find();
                    //                $flag = true;
                } else {
                    //解密获取用户信息
                    $userInfo = $this->miniProgram->encryptor->decryptData($session['session_key'], $data['iv'], $data['encryptedData']);
                    $session_key = $session['session_key'];
                    $salt = Random::alnum();
                    $users_arr = [
                        'nickname' => $userInfo['nickName'],
                        'sex' => $userInfo['gender'],
                        'city' => $userInfo['city'],
                        'province' => $userInfo['province'],
                        'avatar' => $userInfo['avatarUrl'],
                        'wx_openid' => $session['openid'],
                        'session_key' => $session_key,
                        'token' => $token,
                        //                    'unionid' => $session['unionid'],
                        'logintime' => time(),
                        'jointime' => time(),
                        'loginip' => $this->request->ip(),
                        'salt' => $salt,
                    ];
                    $users = UsersModel::create($users_arr);

                    $redis->setEx('user_token:' . $token, $this->keeptime, $users->id);
                    Session::set('user_token:' . $token, $users->id, $this->keeptime);
                    $userInfos = $users;
                    //                $flag = true;
                }
            } else { //直接登录
                $userInfos = UsersModel::where(['session_key' => $data['session_key']])->find();
                /*if ($userInfos) {
                    $flag = true;
                }*/
            }
            $Imuserinfo = $this->createImuser($userInfos->id); //创建IM用户并初始化
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('登录失败！' . $e->getMessage());
        }
        $this->success('登录成功', [
            'userInfo' => $userInfos,
            'Imuserinfo' => $Imuserinfo,
        ]);
        /*if ($userInfos) {
            $Imuserinfo = $this->createImuser($userInfos->id);//创建IM用户并初始化
            $this->success('登录成功', [
                'userInfo' => $userInfos,
                'Imuserinfo' => $Imuserinfo,
            ]);
        } else {
            $this->error('登录失败');
        }*/
    }

    /**
     * 获取用户信息
     */
    public function getUserinfo()
    {
        $userinfo = $this->auth->getUserinfo();
        $userinfo['certification_fee'] = \think\Config::get('site.certification_fee');
        $this->success('获取成功', ['userinfo' => $userinfo]);
    }


    /**
     * 创建IM用户并初始化
     */
    public function createImuser($user_id)
    {
        //        $user_id = $this->request->post('user_id');
        // 检查是否为会员
        $this->userinfo = $this->checkUserByPassword($user_id);
        if (!$this->userinfo) {
            // 检查是否为管理员
            $this->userinfo = $this->checkAdminByPassword($user_id);
        }
        if (!$this->userinfo) {
            $this->error(__('Username is incorrect'));
        }

        // 用户和管理员以及游客token都可通过此处转换为IMuser
        $imUser = ImCommon::checkWxIMUser(false, $this->userinfo);
        if (!$imUser) {
            // 建立
            $imUser = ImCommon::createWxIMUser('uni-app', $this->request->ip(), $this->userinfo['token']);
            if ($imUser) {
                $userInfoToken = $imUser['cache_token'];
            }
        } else {
            $keeptime      = $this->keeptime; // token 10天后过期
            $expiretime    = time() + $keeptime;
            $token         = Db::name('fastim_user')->where('id', $imUser['id'])->value('token');
            $key           = md5(md5($imUser['id']) . md5($keeptime) . md5($expiretime) . $token);
            $userInfoToken = [$imUser['id'], $keeptime, $expiretime, $key];
            $userInfoToken = implode('|', $userInfoToken);
        }

        // 绑定
        $this->userinfo = ImCommon::bindFaUserToIMUser($imUser, $this->userinfo);
        if (!$this->userinfo) {
            $this->error(__('Unrecognized user'), [], 401);
        }

        $this->userinfo['token']      = $userInfoToken;
        $this->userinfo['auth_token'] = ImCommon::createAuthToken($imUser['id']);
        /* $this->success('登录成功', [
            'userInfo' => $this->userinfo,
        ]);*/
        return $this->userinfo;
    }

    private function checkUserByPassword($user_id)
    {
        $user  = UsersModel::get(['id' => $user_id]);
        if ($user->status != 1) {
            return false;
        }
        //记录本次登录的IP和时间
        $user->loginip   = request()->ip();
        $user->logintime = time();
        $user->save();
        $user->identity = 'fauser';
        return $user->toArray();
    }

    private function checkAdminByPassword($user_id)
    {
        $admin  = Admin::get(['user_id' => $user_id]);
        if (!$admin) {
            return false;
        }
        if ($admin['status'] == 'hidden') {
            return false;
        }
        // 不重置管理员token
        $admin->loginfailure = 0;
        $admin->logintime    = time();
        $admin->loginip      = request()->ip();
        $admin->save();
        $admin->identity = 'admin';
        return $admin->toArray();
    }

    /**
     * 微信授权获取openid、unionid
     */
    public function authorWechat()
    {
        $code = $this->request->post('code', ''); //code
        $access_token = $this->request->post('access_token', '');
        $userinfo = $this->request->post('userinfo/a');
        if ($this->login_type == 'app') {
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $userinfo['openId'];
            $info = sendCurl($url);
            $info = json_decode($info, true);
            if (!$info) {
                $this->error('授权失败');
            }
            $data = [
                'app_openid' => $info['openid'],
            ];
        } else {
            $userinfo = $this->auth->getUserinfo();
            $session = $this->getOpenid($code);
            if (!$session['session_key'] || !$session['openid']) {
                $this->error('必要参数缺失');
            }
            if ($userinfo['wx_openid'] == $session['openid']) {
                $this->error('app已授权过');
            }
            if ($userinfo['wx_openid'] == $session['openid']) {
                $this->error('小程序已授权过');
            }
            $data = [
                'wx_openid' => $session['openid'],
                //                'unionid' =>$session['unionid'],
            ];
        }
        \app\common\model\User::update($data, ['id' => $userinfo['id']]);
        $this->success('授权成功');
    }

    /**
     * 获取微信的openid等唯一标识
     */
    protected function getOpenid($code)
    {
        if (!$code) {
            //            return ['code'=>-1,'msg' =>'code不能够为空'];
            $this->error(__('Invalid parameters'));
        }
        // 微信登录 (获取session_key)
        $WxUser = new WxUser($this->testConfig['app_id'], $this->testConfig['appSecret']);
        if (!$session = $WxUser->sessionKey($code))
            $this->error('请再次点击绑定', '', 1002);
        //缓存session_key
        cache($session['openid'] . '_zp', $session['session_key']);
        //根据openid获取用户的信息
        //返回openid给小程序
        //$data = ['openid'=>$session['openid']];
        return $session;
    }

    /**
     * 资金明细记录
     */
    public function deatailMoneyLog()
    {
        //页数
        $page = $this->request->post('page', 1);
        //1=用户余额，2=代理资金，3=佣金
        $type = $this->request->post('type',1); 
        //1正数收入，-1负数支出
        $heatos = $this->request->post('heatos', 1); 
        $where = [];
        $where['user_id'] = $this->auth->id;
        $where['type'] = $type;
        $where['heatos'] = $heatos;
        $userDetailMoney = UsersDetailMoneyModel::where($where)
            ->page($page)
            ->limit($this->pageSize)
            ->order('create_time desc')
            ->select();
        $userInfo = UsersModel::where(['id' => $this->auth->id])->field('money,commission,agent_money')->find();
        if ($userDetailMoney) {
            foreach ($userDetailMoney as $key => $val) {
                switch ($val['heatos']) {
                    case 1:
                        $val['money'] = '+' . $val['money'];
                        break;
                    case -1:
                        $val['money'] = '-' . $val['money'];
                        break;
                }
            }
        }
        $this->success('获取账单明细成功', ['userDetailMoneys' => $userDetailMoney, 'userInfo' => $userInfo]);
    }
}
