<?php

namespace App\Services\Api\MobileWeb;

use App\Services\CommonService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use BlueCity\Core\Inc\ErrorInc;
use App\Models\{Admin, AdminInfor, Company, InstallPerson};
use Illuminate\Support\Facades\Crypt;

class LoginService
{
    // 登录
    public static function login($request)
    {
        if ($request['user_type'] == 1) { //技师登录
            // 查询登录账号数据
            $find_person = DB::table('install_person as install')
                ->leftJoin('admin as adm', 'install.admin_id', '=', 'adm.id')
                ->where('delet_y', 1)
                ->where('check_code', $request['account'])
                ->where('install_password', md5($request['password']))
                ->select('install.id', 'check_code', 'install_name', 'install_phone', 'install_is_type', 'admin_id','adm.company_id','admin_groupnew')
                ->first();
        } elseif($request['user_type'] == 2) { //服务商登录
            //判定是否有公司名称字段
            if(!isset($request['company_name']) || $request['company_name']==''){
                return ['ErrorCode' => 201, 'ErrorMessage' => '请填写公司名称！', 'data' => ''];
            }
            //查询公司名称是否存在
            $company_id = Company::where("com_name",$request['company_name'])->value('com_id');
            // 查询登录账号数据
            $find_person = DB::table('admin as adm')
                ->leftJoin('admin_infor as adin', 'adin.admin_id', '=', 'adm.id')
                ->where('admin_acc', $request['account'])
                ->where('company_id', $company_id)
                ->whereIn('admin_groupnew', [2,3])
                ->where('admin_password', md5($request['password']))
                ->select('adm.id', 'admin_acc as check_code', 'admin_name as install_name', 'phone as install_phone', 'enable as install_is_type', 'adm.id as admin_id','admin_groupnew','company_id')
                ->first();
            $find_person = CommonService::dataToArray($find_person);
        }
        if (empty($find_person)) {
            return ['ErrorCode' => 202, 'ErrorMessage' => '账号密码错误！', 'data' => ''];
        }
        if ($find_person['install_is_type'] != 1) {
            return ['ErrorCode' => 203, 'ErrorMessage' => '当前账号已停用！', 'data' => ''];
        }
        if($request['user_type'] == 2 && $find_person['admin_groupnew']==3){
            $request['user_type'] = 3;
        }
        if ($request['openid']) {
            // 微信授权绑定用户信息
            $bingding_res = self::accreditBinding($request, $find_person);
        }

        $expiration_time = 12 * 60 * 60; //登录过期时间
        // 生成token
        $unique_string = md5(uniqid(md5(microtime(true)) . rand(100000, 999999), true)); //生成唯一字符串
        $api_token = sha1($unique_string); //加密
        $find_login = DB::table('login_web')
            ->where('install_id', '=', $find_person['id'])
            ->where('user_type', '=', $request['user_type'])
            ->select('lowe_id', 'install_id', 'lowe_last_login')
            ->first();
        if (empty($find_login)) {
            // 如果用户第一次登陆,将用户的登录状态保存到临时表
            $lote_data['install_id'] = $find_person['id']; //账号id
            $lote_data['lowe_last_login'] = time() + $expiration_time; //最后登陆时间
            $lote_data['api_token'] = $api_token; //api_token
            $lote_data['account'] = $find_person['check_code']; //登录账号
            $lote_data['install_name'] = $find_person['install_name']??""; //账号姓名
            $lote_data['install_phone'] = $find_person['install_phone']; //手机号
            $lote_data['admin_id'] = $find_person['admin_id']; //所属服务中心id
            $lote_data['user_type'] = $request['user_type']; //登录类型：1技师2服务商3经销商
            $lote_data['company_id'] = $find_person['company_id']; //所属公司id
            $lote_data['role_auth'] = '';
            $lote_data['auth_routes'] = '';
            $lote_res = DB::table('login_web')->insert($lote_data);
            if (empty($lote_res)) {
                return ["ErrorCode" => 204, 'ErrorMessage' => '登录失败！1', 'data' => ''];
            }

            // 返回数据
            $return_data = [
                'api_token' => Crypt::encrypt($api_token), //生成前台token
                'account' => $find_person['check_code'],
                'install_name' => $find_person['install_name'],
                'install_phone' => $find_person['install_phone'],
                'install_id' => $find_person['id'],
                'admin_id' => $find_person['admin_id'],
                'company_id' => $find_person['company_id'],
            ];
            return ['ErrorCode' => 1, 'ErrorMessage' => '登录成功', 'data' => $return_data];
        }

        $now_time = time();

        // 当前时间大于最后登陆时间，登录时间已过期，重新登录
        // login_type 值为1 强制登录
        if ($now_time > $find_login['lowe_last_login'] || $request['login_type'] == 1) {
            //修改登陆状态
            $lote_data['install_id'] = $find_person['id']; //账号id
            $lote_data['lowe_last_login'] = time() + $expiration_time; //最后登陆时间
            $lote_data['api_token'] = $api_token; //api_token
            $lote_data['account'] = $find_person['check_code']; //登录账号
            $lote_data['install_name'] = $find_person['install_name']; //账号姓名
            $lote_data['install_phone'] = $find_person['install_phone']; //手机号
            $lote_data['admin_id'] = $find_person['admin_id']; //所属服务中心id
            $lote_data['user_type'] = $request['user_type']; //登录类型：1技师2服务商3经销商
            $lote_data['company_id'] = $find_person['company_id']; //所属公司id
            $lote_res = DB::table('login_web')
                ->where('lowe_id', $find_login['lowe_id'])
                ->update($lote_data);
            if (empty($lote_res)) {
                return ["ErrorCode" => 500, 'ErrorMessage' => '登录失败！2', 'data' => ''];
            }

            if($request['user_type']>1) {
                $button = [
                    ["pagePath"=>"/pages/index/index","text"=>"接单","iconPath"=>"tab_icon_01.png","selectedIconPath"=>"tab_icon_01_on.png",'type'=>'OrderTaking'],
                    ["pagePath"=>"/pages/order/installOrderList","text"=>"安装","iconPath"=>"tab_icon_02.png","selectedIconPath"=>"tab_icon_02_on.png",'type'=>'InstallOrder'],
                    ["pagePath"=>"/pages/order/billManagement","text"=>"账单","iconPath"=>"tab_icon_03.png","selectedIconPath"=>"tab_icon_03_on.png",'type'=>'orderBill'],
                    ["pagePath"=>"","text"=>"更多","iconPath"=>"tab_icon_04.png","selectedIconPath"=>"tab_icon_04_on.png",'type'=>'moreButton']
                ];
                $button_more = [
                    ["pagePath"=>"/pages/order/afterOrderList","text"=>"售后","iconPath"=>"","selectedIconPath"=>"",'type'=>'afterOrderList'],
                    ["pagePath"=>"/pages/login/forgotPassword","text"=>"修改密码","iconPath"=>"","selectedIconPath"=>"",'type'=>'forgotPassword'],
                    ["pagePath"=>"/pages/technician/technicianList","text"=>"技师","iconPath"=>"","selectedIconPath"=>"",'type'=>'technicianList'],
                    ["pagePath"=>"","text"=>"退出","iconPath"=>"","selectedIconPath"=>"",'type'=>'quit']
                ];
            }else{
                $button = [
                    ["pagePath"=>"/pages/order/installOrderList","text"=>"安装","iconPath"=>"tab_icon_02.png","selectedIconPath"=>"tab_icon_02_on.png",'type'=>'InstallOrder'],
                    ["pagePath"=>"","text"=>"更多","iconPath"=>"tab_icon_04.png","selectedIconPath"=>"tab_icon_04_on.png",'type'=>'moreButton']
                ];
                $button_more = [
                    ["pagePath"=>"/pages/order/afterOrderList","text"=>"售后","iconPath"=>"","selectedIconPath"=>"",'type'=>'afterOrderList'],
                    ["pagePath"=>"/pages/login/forgotPassword","text"=>"修改密码","iconPath"=>"","selectedIconPath"=>"",'type'=>'forgotPassword'],
                    ["pagePath"=>"","text"=>"退出","iconPath"=>"","selectedIconPath"=>"",'type'=>'quit']
                ];
            }
            // 返回数据
            $return_data = [
                'api_token' => Crypt::encrypt($api_token), //生成前台token
                'account' => $find_person['check_code'],
                'install_name' => $find_person['install_name'],
                'install_phone' => $find_person['install_phone'],
                'install_id' => $find_person['id'],
                'admin_id' => $find_person['admin_id'],
                'company_id' => $find_person['company_id'],
                'button' => $button,
                'user_type' => $request['user_type'],
                'button_more' => $button_more,
            ];
            return ['ErrorCode' => 1, 'ErrorMessage' => '登录成功', 'data' => $return_data];
        } else {
            return ["ErrorCode" => 400, 'ErrorMessage' => '该用户已经登录', 'data' => ''];
        }
    }

    // 微信授权绑定
    public static function accreditBinding($request, $find_person)
    {
        // 查询数据表openID是否存在绑定，存在绑定改为离线
        DB::table('installation_master')
            ->where('wechat_number',$request['openid'])
            ->update(['priority'=>2,'update_time'=>date('Y-m-d H:i:s')]);
        $find_data = DB::table('installation_master')
            ->where('check_code',$find_person['check_code'])
            ->where('type',$request['user_type'])
            ->value('id');
        if($find_data){
            return DB::table('installation_master')
                ->where('id',$find_data)
                ->update(['priority'=>1,'wechat_number'=>$request['openid'],'update_time'=>date('Y-m-d H:i:s')]);
        }else {
            // 新增绑定关系
            $data['wechat_number'] = $request['openid'];
            $data['type'] = $request['user_type'];
            $data['check_code'] = $find_person['check_code'];
            $data['inst_name'] = $find_person['install_name'];
            $data['inst_phone'] = $find_person['install_phone'];
            $data['admin_id'] = $find_person['admin_id'];
            $data['install_id'] = $find_person['id'];
            $data['priority'] = 1;
            return DB::table('installation_master')->insert($data);
        }
    }

    // 退出
    public static function quit($request)
    {

        // 更改最后登录时间
        $lote_data['lowe_last_login'] = 0; //最后登陆时间
        $res = DB::table('login_web')
            ->where('api_token', $request['api_token'])
            ->update($lote_data);
        if ($res) {
            return ['ErrorCode' => 1, 'ErrorMessage' => '退出成功', 'data' => ''];
        } else {
            return ["ErrorCode" => 201, 'ErrorMessage' => '退出失败', 'data' => ''];
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 修改密码
     * @param string password 原密码
     * @param string new_password 新密码
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/13 0:34
     * |---------------------------------------------------------------------------------
    */
    public static function updatePassword( $request, $ip )
    {
        $session = $request['session'];
        if($session['user_type']==1){
            $res = InstallPerson::where('id',$session['install_id'])->where('install_password',md5($request['old_password']))->value('id');
            if($res){
                if($request['new_password']==$request['old_password']){
                    return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'data' => ''];
                }else{
                    $password['install_password']=md5($request['new_password']);
                    $password['install_password1']=$request['new_password'];
                    $result = InstallPerson::where('id',$session['install_id'])->update($password);
                    if ($result) {
                        $lote_data['lowe_last_login'] = 0; //最后登陆时间
                        $res = DB::table('login_web')
                            ->where('api_token', $request['api_token'])
                            ->update($lote_data);
                        return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'data' => ''];
                    } else {
                        return ["ErrorCode" => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'data' => ''];
                    }
                }
            }else{
                return ["ErrorCode" => ErrorInc::ELASTIC_FAILED, 'ErrorMessage' => '密码错误', 'data' => ''];
            }
        }else{
            $res = Admin::where('id',$session['install_id'])
                ->where('admin_password',md5($request['old_password']))->value("id");
            if($res){
                if($request['new_password']==$request['old_password']){
                    return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'data' => ''];
                }
                $password['admin_password']=md5($request['new_password']);
                $result = Admin::where('id',$session['install_id'])->update($password);
                if($result){
                    $data['back_pass']=$_POST['new_password'];
                    AdminInfor::where('admin_id',$session['install_id'])->update($data);
                    $lote_data['lowe_last_login'] = 0; //最后登陆时间
                    $res = DB::table('login_web')
                        ->where('api_token', $request['api_token'])
                        ->update($lote_data);
                    return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'data' => ''];
                }else{
                    return ["ErrorCode" => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'data' => ''];
                }
            }else{
                return ["ErrorCode" => ErrorInc::ELASTIC_FAILED, 'ErrorMessage' => '密码错误', 'data' => ''];
            }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取openid
     * @param string code 微信授权码
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/13 17:07
     * |---------------------------------------------------------------------------------
    */
    public static function getOpenid ( $request ){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxf457f42f874c3545&secret=62c5530f13e8b88204818c8b98d3a5b6&code=".$request['code']."&grant_type=authorization_code";
        $result = CommonService::requestGet($url);
        $jsoninfo = json_decode($result, true);
        if(isset($jsoninfo["openid"])){
            return ["ErrorCode" => 1, 'ErrorMessage' => '操作成功', 'data' => $jsoninfo["openid"]];
        }else{
            return ["ErrorCode" => ErrorInc::SAPI_FAILED, 'ErrorMessage' => '操作失败', 'data' => $jsoninfo];
        }
        $openid = $jsoninfo["openid"];
    }
}
