<?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\{Company, InstallPerson};
use Illuminate\Support\Facades\Crypt;

class LoginService
{
    // 登录
    public static function login($request)
    {
        if ($request['user_type'] == 1) { //技师登录
            // 查询登录账号数据
            $find_person = InstallPerson::where('delet_y', 1)
                ->where('check_code', $request['account'])
                ->where('install_password', md5($request['password']))
                ->select('id', 'check_code', 'install_name', 'install_phone', 'install_is_type', 'admin_id')
                ->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'])
                ->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')
                ->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['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服务商
            $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'],
            ];
            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_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' => '{}'];
            }

            // 返回数据
            $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'],
            ];
            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'])
            ->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)
    {
        try {
            $api_token = Crypt::decrypt($request['api_token']);
        } catch (\Exception $e) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => 'api_token失效', 'data' => ''];
        }

        // 更改最后登录时间
        $lote_data['lowe_last_login'] = 0; //最后登陆时间
        $res = DB::table('login_web')
            ->where('api_token', $api_token)
            ->update($lote_data);
        if ($res) {
            return ['ErrorCode' => 1, 'ErrorMessage' => '退出成功', 'data' => '{}'];
        } else {
            return ["ErrorCode" => 201, 'ErrorMessage' => '退出失败', 'data' => '{}'];
        }
    }
}
