<?php
namespace App\JsonRpc;
use App\Model\Role;
use App\Model\RoleLog;
use App\Model\User;
use App\Model\UserInfo;
use App\Model\UserLogin;
use App\Model\Wechat;
use App\Tools\Result;
use Hyperf\DbConnection\Db;
use Hyperf\RpcServer\Annotation\RpcService;

#[RpcService(name: "UserService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
class UserService implements UserServiceInterface
{
    /**
     * @param string $name
     * @param int $gender
     * @return string
     */
    public function createUser(array $data): array
    {
        Db::beginTransaction();
        try{

            $dataUserReq = [
                'user_name'=>$data['user_name'],
                'password'=>md5(md5($data['password']).$data['salt']),
                'avatar'=>$data['avatar']??'',
                'mobile'=>$data['mobile']??'',
                'status'=>$data['status']??1,
                'role_id'=>$data['role_id']??0,
                'email'=>$data['email']??'',
                'salt'=>$data['salt'],
                'rong_token'=>$data['rong_token']??'',
                'level_id'=>$data['level_id']??0, //会员等级
                'nickname'=>$data['nickname']??'',
                'last_login_ip'=>$data['last_login_ip']??'',
            ];
            var_dump("user:",$dataUserReq);
            $userid = User::query()->insertGetId($dataUserReq);
            $dataUserInfoReq = [
                'user_id'=>$userid,
                'id_card'=>$data['id_card']??'',
                'gender'=>$data['gender']??0,
                'real_name'=>$data['real_name']??'',
                'job'=>$data['job']??'',
                'city_id'=>isset($data['city_id']) && $data['city_id']?json_encode($data['city_id']):'',
                'birthday'=>$data['birthday']??'',
                'number'=>$data['number']??'',
            ];


            $userInfoId = UserInfo::query()->insertGetId($dataUserInfoReq);
            var_dump("userInfo:",$userInfoId);
            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            var_dump($ex->getMessage());
            return Result::error("创建失败",0);
        }
        return $userInfoId ? Result::success(["id"=>$userid]) : Result::error("创建失败",0);
    }

    /**
     * @return array
     */
    public function getUserList(array $data): array
    {

        $where = [
            ['user.user_name','like','%'.$data['keyword'].'%']
        ];
        if(isset($data['pageSize'])){
            $result = User::where($where)
                ->leftJoin('user_info', 'user.id', '=', 'user_info.user_id')
                ->leftJoin('user_level', 'user.level_id', '=', 'user_level.id')
                ->select('user.*', 'user_info.id as user_info_id',
                    'user_info.id_card',
                    'user_info.birthday',
                    'user_info.gender',
                    'user_info.real_name',
                    'user_info.business_name',
                    'user_info.job',
                    'user_info.city_id',
                    'user_level.name as level_name'
                )
                ->limit($data['pageSize'])->offset(($data['page']-1)*$data['pageSize'])->orderBy("user.id","desc")->get();
        }else{
            $result = User::where($where)
                ->select('user.*', 'user_info.id as user_info_id',
                    'user_info.id_card',
                    'user_info.birthday',
                    'user_info.gender',
                    'user_info.real_name',
                    'user_info.business_name',
                    'user_info.job',
                    'user_info.city_id',

                )
                ->leftJoin('user_info', 'user.id', '=', 'user_info.user_id')
                ->get();
        }
        var_dump("用户列表",$result->toArray());
        $count = User::where($where)->count();
        if (empty($result)) {
            return Result::error("没有数据",0);
        }
        $rep = $result->toArray();
        $type = ['1'=>"个人会员",'2'=>"政务会员",'3'=>"企业会员"];
        $gender = ['0'=>"未知",'1'=>"男",'2'=>"女"];
        $status = ['1'=>"正常",'2'=>"冻结"];
        if($rep){
            foreach ($rep as $k=>$v){
                $rep[$k]['type_name'] = $type[$v['type_id']];
                $rep[$k]['gender_name'] = $gender[$v['gender']];
                $rep[$k]['status_name'] = $status[$v['status']];
                $rep[$k]['city_id'] = $v['city_id']?json_decode($v['city_id']):[];
            }
        }
        $data = [
            'rows'=>$rep,
            'count'=>$count
        ];
        return Result::success($data);
    }
    /**
     * @param int $id
     * @return array
     */
    public function getUserInfo(int $id): array
    {
        $userInfo =  Db::table('user')
            ->leftJoin('user_info', 'user.id', '=', 'user_info.user_id')
            ->select('user.*', 'user_info.id as user_info_id','user_info.id_card','user_info.birthday','user_info.gender','user_info.real_name')
            ->where('user.id','=',$id)->first();
        if (empty($userInfo)) {
           return Result::error("找不到用户",0,[]);
        }

        return Result::success($userInfo);
    }

    /**
     * @param array $data
     * @return array
     */
    public function verifyUserInfo(array $data): array
    {
        if(isset($data['id'])){
            $data[] = ['id',"!=",$data['id']];
             unset($data['id']);
        }
        $userInfo = User::query()->where($data)->first();
        if (empty($userInfo)) {
            return Result::error("找不到用户",0);
        }
        return Result::success($userInfo->toArray());
    }

    /**
     * @param array $data
     * @return array
     */
    public function createUserLogin(array $data): array
    {
       $id =  UserLogin::insertGetId($data);
        if (empty($id)) {
            return Result::error("创建登录日志失败",0);
        }
        return Result::success(["id"=>$id]);
    }

    /**
     * 更新用户信息和userInfo
     * @param array $data
     * @return array
     */
    public function updateUser(array $data): array{
        Db::beginTransaction();
        try{
            $dataUserReq = [
                'user_name'=>$data['user_name'],
                'avatar'=>$data['avatar']??'',
                'mobile'=>$data['mobile']??'',
                'status'=>$data['status']??1,
                'role_id'=>$data['role_id']??0,
                'email'=>$data['email']??'',
                'rong_token'=>$data['rong_token']??'',
                'level_id'=>$data['level_id']??0, //会员等级
                'nickname'=>$data['nickname']??'',
                'last_login_ip'=>$data['last_login_ip']??'',
            ];
            if($data['password']){
                $dataUserReq['password'] = md5(md5($data['password']).$data['salt']);
                $dataUserReq['salt'] =$data['salt'];
            }
            $userRep =  User::where(['id'=>$data['id']])->update($dataUserReq);

            $dataUserInfoReq = [
                'id_card'=>$data['id_card']??'',
                'gender'=>$data['gender']??0,
                'real_name'=>$data['real_name']??'',
                'job'=>$data['job']??'',
                'city_id'=>$data['city_id']?json_encode($data['city_id']):'',
                'birthday'=>$data['birthday']??''
            ];

            $userInfoRep =  UserInfo::where(['user_id'=>$data['id']])->update($dataUserInfoReq);

            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            var_dump($ex->getMessage());
            return Result::error("创建失败",0);
        }
        return Result::success([]);
    }

    /**
     * @param array $data
     * @return array
     */
    public function updateUserInfo(array $data): array{
        return 1;
    }

    /**
     * @param int $id
     * @return array
     */
    public function  delUser(int $id) :array{
        Db::beginTransaction();
        try{
            User::where(['id'=>$id])->delete();
            UserInfo::where(['user_id'=>$id])->delete();
            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            return Result::error("删除失败",0);
        }
        return Result::success([]);

    }

    /**
     * @param array $data
     * @return array
     */
    public function addRole(array $data) :array
    {
        Db::beginTransaction();
        try{
            Role::insertGetId($data);
            $logData = [
                'user_id'=>$data['user_id'],
                'data'=>json_encode($data),
                'type'=>1
            ];
            RoleLog::insertGetId($logData);
            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            return Result::error("新增失败",0);
        }
        return Result::success([]);
    }
    /**
     * @param array $data
     * @return array
     */
    public function delRole(array $data) :array
    {
        Db::beginTransaction();
        try{
            $roleInfo = Role::where(['id'=>$data['id']])->first();
            $logData = [
                'user_id'=>$data['user_id'],
                'data'=>json_encode($roleInfo->toArray()),
                'type'=>2
            ];
            RoleLog::insertGetId($logData);
            $result = Role::where(['id'=>$data['id']])->delete();
            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            return Result::error("删除失败",0);
        }
        return Result::success($result);
    }
    /**
     * @param array $data
     * @return array
     */
    public function updateRole(array $data) :array
    {

        $result = Role::where(['id'=>$data['id']])->update($data);
        if ($result) {
            return Result::success($result);
        }
        return  Result::error("更新失败");
    }
    /**
     * @param array $data
     * @return array
     */
    public function roleInfo(array $data) :array
    {
        $roleInfo = Role::where(['id'=>$data['id']])->first();
        if($roleInfo){
            return Result::success($roleInfo->toArray());
        }else{
            return  Result::error("没有数据");
        }
    }
    /**
     * @param array $data
     * @return array
     */
    public function roleList(array $data) :array
    {
        $where = [
            ['role_name','like','%'.$data['keyword'].'%']
        ];
        if(isset($data['pageSize'])){
            $result = Role::where($where)->limit($data['pageSize'])->offset(($data['page']-1)*$data['pageSize'])->get();
        }else{
            $result = Role::where($where)->get();
        }

        $count = Role::where($where)->count();
        if (empty($result)) {
            return Result::error("没有数据",0);
        }
        $data = [
            'rows'=>$result->toArray(),
            'count'=>$count
        ];
        return Result::success($data);
    }

    /**
     * 获取小程序注册信息
     * @param array $data
     * @return array
     */
    public function getWechatInfo(array $data) :array
    {
        $where = [
            'purePhoneNumber'=>$data['purePhoneNumber'],
            'openid'=>$data['openid']
        ];
        $result = Wechat::where($where)->first();
        var_dump($result);
        if($result){
            return Result::success($result);
        }else{
            return Result::error('没有数据');
        }
    }

    /**
     * 添加小程序 注册信息
     * @param array $data
     * @return array
     */
    public function addWechatInfo(array $data) :array
    {
        $result =  Wechat::insertGetId($data);
        if($result){
            return Result::success($result);
        }else{
            return Result::error('添加失败');
        }
    }
}