<?php
namespace App\JsonRpc;
use App\Model\Role;
use App\Model\RoleLog;
use App\Model\RoleUser;
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']??'',
                'type_id'=>$data['type_id']??'20000',
                'mobile'=>$data['mobile']??'', //手机号
                'status'=>$data['status']??1,
                'email'=>$data['email']??'',
                'salt'=>$data['salt'],
                'admin_id'=>isset($data['admin_id']) && $data['admin_id']!=''?$data['admin_id']:0,
//                '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']??'',
                'business_name'=>$data['business_name']??'',
                'job'=>$data['job']??'',
                'city_id'=>$data['city_id']??0,
                'birthday'=>$data['birthday']??'',
                'number'=>$data['number']??'',
                'city_arr_id'=>$data['city_arr_id']??'',
                'from_time'=>$data['from_time']??null,
                'to_time'=>$data['to_time']??null,
                'long_time'=>$data['long_time']??0,
                'native_place_id'=>$data['native_place_id']??0,
                'native_place_arr_id'=>$data['native_place_arr_id']??'',
                'qq'=>$data['qq']??'',
                'zip_code'=>$data['zip_code']??'',
                'address_arr_id'=>$data['address_arr_id']??'',
                'address_id'=>$data['address_id']??0,
                'address'=>$data['address']??'',
                'other'=>$data['other']??'',
                'remark'=>$data['remark']??'',
                'fax'=>$data['fax']??'',
                'position'=>$data['position']??'',
                'legal_person_real_name'=>$data['legal_person_real_name']??'',
                'legal_person_mobile'=>$data['legal_person_mobile']??'',
                'legal_person_id_card'=>$data['legal_person_id_card']??'',
                'administrative_unit_arr_id'=>$data['administrative_unit_arr_id']??'',
                'administrative_unit_id'=>$data['administrative_unit_id']??0,
            ];
            var_dump("UserINfo:::",$dataUserInfoReq);

            $userInfoId = UserInfo::query()->insertGetId($dataUserInfoReq);
            $roleUserData = [
                'role_id'=>isset($data['role_id']) && $data['role_id']!=''?$data['role_id']:0,
                'user_id'=>$userid,
                'admin_user_id'=>isset($data['admin_id']) && $data['admin_id']!=''?$data['admin_id']:0,
            ];
            RoleUser::insert($roleUserData);
            var_dump("userInfo:",$userInfoId);
            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            var_dump($ex->getMessage());
            $message = $ex->getMessage();
            return Result::error($message,0);
        }
        return $userInfoId ? Result::success(["id"=>$userid]) : Result::error("创建失败",0);
    }

    /**
     * @return array
     */
    public function getUserList(array $data): array
    {
        $where = [];
        if(isset($data['keyword']) && $data['keyword']){
            array_push($where, ['user.user_name','like','%'.$data['keyword'].'%']);
        }
        if(isset($data['type_id']) && $data['type_id']){
            array_push($where, ['user.type_id','=',$data['type_id']]);
        }
        if(isset($data['status']) && $data['status']!='' && intval($data['status'])>=0 ){
            array_push($where, ['user.status','=',$data['status']]);
        }

        $result = User::where($where)
                ->leftJoin('user_info', 'user.id', '=', 'user_info.user_id')
                ->leftJoin("user as userA",'user.admin_id',"userA.id")
                ->orderBy("user.id","desc")->paginate(intval($data['pageSize']),
                [
                    'user.id',
                    'user.user_name',
                    'user_info.real_name',
                    'user.mobile',
                    'user.type_id',
                    'user.created_at',
                    'user.status',
                    'userA.nickname as admin_nickname'
                ],
                'page', intval($data['page']));

        $count = $result->total();
        if (empty($result)) {
            return Result::error("没有数据",0);
        }
        $rep = $result->items();
        //1:个人会员 2：政务会员 3：企业会员 4:调研员 10000：管理员 20000：游客
        $type = ['1'=>"个人会员",'2'=>"政务会员",'3'=>"企业会员",'4'=>'调研员','10000'=>'管理员','20000'=>'游客'];

        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')
            ->leftJoin('role_user', 'role_user.user_id', '=', 'user.id')
            ->select('user.*',
                'user_info.id as user_info_id',
                'user_info.real_name',
                'user_info.id_card',
                'user_info.birthday',
                'user_info.gender',
                'user_info.city_id',
                'user_info.business_name',
                'user_info.job',
                'user_info.number',
                'user_info.city_arr_id',
                'user_info.from_time',
                'user_info.to_time',
                'user_info.long_time',
                'user_info.native_place_id',
                'user_info.native_place_arr_id',
                'user_info.qq',
                'user_info.zip_code',
                'user_info.address_arr_id',
                'user_info.address_id',
                'user_info.address',
                'user_info.other',
                'user_info.remark',
                'user_info.fax',
                'user_info.position',
                'user_info.legal_person_real_name',
                'user_info.legal_person_mobile',
                'user_info.legal_person_id_card',
                'user_info.administrative_unit_arr_id',
                'user_info.administrative_unit_id',
                'role_user.role_id',

            )
            ->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']??'',
                'type_id'=>$data['type_id']??'20000',
                'mobile'=>$data['mobile']??'', //手机号
                'status'=>$data['status']??1,
                'email'=>$data['email']??'',
                'admin_id'=>$data['admin_id'],
                'nickname'=>$data['nickname']??'',
                'last_login_ip'=>$data['last_login_ip']??'',
            ];

            $userRep =  User::where(['id'=>$data['id']])->update($dataUserReq);
            var_dump("修改user:",$userRep);
            $dataUserInfoReq = [
                'id_card'=>$data['id_card']??'',
                'gender'=>$data['gender']??0,
                'real_name'=>$data['real_name']??'',
                'job'=>$data['job']??'',
                'city_id'=>$data['city_id']??0,
                'birthday'=>$data['birthday']??'',
                'number'=>$data['number']??'',
                'city_arr_id'=>$data['city_arr_id']??'',
                'from_time'=>$data['from_time']??null,
                'business_name'=>$data['business_name']??'',
                'to_time'=>$data['to_time']??null,
                'long_time'=>$data['long_time']??0,
                'native_place_id'=>$data['native_place_id']??0,
                'native_place_arr_id'=>$data['native_place_arr_id']??'',
                'qq'=>$data['qq']??'',
                'zip_code'=>$data['zip_code']??'',
                'address_arr_id'=>$data['address_arr_id']??'',
                'address_id'=>$data['address_id']??0,
                'address'=>$data['address']??'',
                'other'=>$data['other']??'',
                'remark'=>$data['remark']??'',
                'fax'=>$data['fax']??'',
                'position'=>$data['position']??'',
                'legal_person_real_name'=>$data['legal_person_real_name']??'',
                'legal_person_mobile'=>$data['legal_person_mobile']??'',
                'legal_person_id_card'=>$data['legal_person_id_card']??'',
                'administrative_unit_arr_id'=>$data['administrative_unit_arr_id']??'',
                'administrative_unit_id'=>$data['administrative_unit_id']??0,
            ];

            $userInfoRep =  UserInfo::where(['user_id'=>$data['id']])->update($dataUserInfoReq);
            var_dump("修改userInfo:",$userInfoRep);
            $roleUserData = [
                'role_id'=>$data['role_id'],
                'admin_user_id'=>$data['admin_id']
            ];
            $resultRoleUserRep = RoleUser::where(['user_id'=>$data['id']])->update($roleUserData);
            var_dump("修改用户角色权限：",$resultRoleUserRep);
            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);
            RoleUser::where(['role_id'=>$data['id']])->delete();
            $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
    {
        Db::beginTransaction();
        try{
            $result = Role::where(['id'=>$data['id']])->update($data);
            $logData = [
                'user_id'=>$data['user_id'],
                'data'=>json_encode($data),
                'type'=>3
            ];
            RoleLog::insertGetId($logData);
            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            return  Result::error("更新失败");
        }
        return Result::success($result);
    }
    /**
     * @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 = [];
        if(isset($data['keyword']) && $data['keyword']){
            array_push($where,  ['role.role_name','like','%'.$data['keyword'].'%']);
        }
        $result = Role::withCount('users')->where($where)->limit($data['pageSize'])->offset(($data['page']-1)*$data['pageSize'])->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('添加失败');
        }
    }


     /**
     * 修改密码
     * @param array $data
     * @return array
     */
    public function changePassword(array $data) :array
    {
        Db::beginTransaction();
        $userInfo = User::where(['id' => $data['user_id']])->first();
        // return Result::success($userInfo); 
        try {
            $dataUserReq = [
                'password' => md5(md5($data['new_password1']) . $userInfo['salt']),
            ];
            if ($userInfo['password'] != md5(md5($data['password']) . $userInfo['salt'])) {
                return Result::error('您输入的密码错误');
            }
            $userRep = User::where(['id' => $data['user_id']])->update($dataUserReq);
            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 upUserStatus(array $data) :array
    {
        $where = [
            'id'=>$data['id']
        ];
        $result = User::where($where)->update($data);
        if($result){
            return Result::success($result);
        }else{
            return Result::error('修改失败');
        }
    }
}