<?php
/**
 * Created by PhpStorm.
 * User: zilongs
 * Date: 20-9-23
 * Time: 上午11:26
 */

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Area;
use App\Models\HelpInfo;
use App\Models\User;
use EasyWeChat\Factory;
use Cache;

class CommonController extends Controller
{
    public function wxLogin()
    {
        $req = request()->post();
        $this->validate(request(), [
            'wechat_code' => 'required',
            'phone|手机号' => 'max:20',
            'verify_code|验证码' => 'integer',
            'nickname|昵称' => 'max:50',
            'avatar|头像' => 'url',
            'latitude|纬度' => 'numeric',
            'longitude|纬度' => 'numeric',
        ]);

        if (!empty($req['phone'])) {
            if (empty($req['verify_code'])) {
                return out(null, 10003, '验证码不能为空');
            }
            $verify_code = Cache::get($req['phone'].'-1');
            if($verify_code != $req['verify_code']){
                if (env('APP_ENV') == 'online' || $req['verify_code'] != '111111') {
                    return out(null, 10004, '验证码错误');
                }
            }
            Cache::delete($req['phone'].'-1');
        }

        $app = Factory::miniProgram(config('config.wechat_small_program'));
        $data = $app->auth->session($req['wechat_code']);
        if (empty($data['openid'])){
            return out(null, 10001, '微信登录code错误');
        }

        $session_key = !empty($data['session_key']) ? $data['session_key'] : '';
        $user = User::select(['id', 'status', 'phone', 'nickname', 'avatar'])->where('openid', $data['openid'])->first();
        if (empty($user)){
            $add = [
                'openid' => $data['openid'],
                'latitude' => $req['latitude'] ?? 0,
                'longitude' => $req['longitude'] ?? 0,
                'phone' => $req['phone'] ?? '',
                'session_key' => $session_key,
                'last_login_time' => time(),
            ];
            $add['nickname'] = $req['nickname'] ?? '';
            $add['avatar'] = $req['avatar'] ?? request()->getScheme().'://'.request()->getHost().'/img/default-head.png';
            $user = User::create($add);
            if (empty($add['nickname'])) {
                $nickname = '用户'.base_convert($user['id'], 10, 16);
                User::where('id', $user['id'])->update(['nickname' => $nickname]);
            }
        }
        else {
            if ($user['status'] == 0) {
                return out(null, 10002, '该账号已被冻结');
            }

            $update = [
                'nickname' => $req['nickname'] ?? '',
                'avatar' => $req['avatar'] ?? '',
                'latitude' => $req['latitude'] ?? 0,
                'longitude' => $req['longitude'] ?? 0,
                'phone' => $req['phone'] ?? '',
                'session_key' => $session_key,
                'last_login_time' => time(),
            ];
            $update = array_filter($update);

            if (empty($req['nickname']) && empty($user['nickname'])) {
                $update['nickname'] = $req['nickname'] = '用户'.base_convert($user['id'], 10, 16);;
            }
            if (empty($req['avatar']) && empty($user['avatar'])) {
                $update['avatar'] = $req['avatar'] = request()->getScheme().'://'.request()->getHost().'/img/default-head.png';
            }

            User::where('id', $user['id'])->update($update);
        }

        $token = aes_encrypt(['id' => $user['id'], 'time' => time()]);

        $req['token'] = $token;
        $req['id'] = $user['id'];
        $req['flag'] = 'member_'.$user['id'];
        return out($req);
    }

    public function getPhoneNumber()
    {
        $req = request()->post();
        $this->validate(request(), [
            'wechat_code' => 'required',
            'iv' => 'required',
            'encryptData' => 'required',
        ]);

        try {
            $app = Factory::miniProgram(config('config.wechat_small_program'));
            $data = $app->auth->session($req['wechat_code']);
            if (empty($data['openid']) || empty($data['session_key'])){
                return out(null, 10001, '微信code错误');
            }

            $decryptedData = $app->encryptor->decryptData($data['session_key'], $req['iv'], $req['encryptData']);
            if (empty($decryptedData['phoneNumber'])) {
                return out(null, 10002, '授权手机号错误');
            }

            if (!User::where('openid', $data['openid'])->exists()){
                $user = User::create([
                    'openid' => $data['openid'],
                    'phone' => $decryptedData['phoneNumber'],
                    'session_key' => $data['session_key'],
                    'avatar' => request()->getScheme().'://'.request()->getHost().'/img/default-head.png',
                    'last_login_time' => time(),
                ]);
                $nickname = '用户'.base_convert($user['id'], 10, 16);
                User::where('id', $user['id'])->update(['nickname' => $nickname]);
            }

        } catch (\Exception $e) {
            return out(null, 10003, '获取手机号失败', $e->getMessage());
        }

        return out($decryptedData);
    }

    public function getUserByCode()
    {
        $req = request()->post();
        $this->validate(request(), [
            'wechat_code' => 'required',
        ]);

        $app = Factory::miniProgram(config('config.wechat_small_program'));
        $data = $app->auth->session($req['wechat_code']);
        if (empty($data['openid'])){
            return out(null, 10001, '微信code错误');
        }

        $user = User::select(['id', 'status', 'phone', 'nickname', 'avatar'])->where('openid', $data['openid'])->first();
        if (!empty($user) && $user['status'] == 0) {
            return out(null, 10002, '该账号已被冻结');
        }

        return out($user);
    }

    public function uploadFile()
    {
        $file = request()->file('file');
        if (empty($file)) {
            return out(null, 10001, '文件不能为空');
        }

        $path = $file->store('uploads/'.date('Ymd'));
        $url = request()->getScheme().'://'.request()->getHost().'/'.$path;

        return out(['url' => $url]);
    }

    public function areaList()
    {
        $areas = Area::get();
        $data1 = $data2 = $data3 = [];
        foreach ($areas as $k => $v) {
            if ($v['level'] == 1) {
                $data1[$k]['id'] = $v['id'];
                $data1[$k]['name'] = $v['name'];
                $data1[$k]['sub'] = [];
            }
            if ($v['level'] == 2) {
                $arr = [];
                $arr['id'] = $v['id'];
                $arr['name'] = $v['name'];
                //$arr['sub'] = [];
                $data2[$v['parent_id']][] = $arr;
            }
            /*if ($v['level'] == 3) {
                $arr = [];
                $arr['id'] = $v['id'];
                $arr['name'] = $v['name'];
                $data3[$v['parent_id']][] = $arr;
            }*/
        }

        /*foreach ($data2 as $k => $v) {
            foreach ($v as $k1 => $v1) {
                $data2[$k][$k1]['sub'] = $data3[$v1['id']]??[];
            }
        }*/

        foreach ($data1 as $k => $v) {
            $data1[$k]['sub'] = $data2[$v['id']]??[];
        }

        return out($data1);
    }

    public function sendVerifyCode()
    {
        //防止恶意刷验证码接口，一分钟最多10次
        check_repeat_request(60, 10);
        $req = request()->post();
        $this->validate(request(), [
            'type' => 'required|integer',
            'phone|手机号' => 'required',
        ]);

        if($req['type'] == 3 || $req['type'] == 4){
            $user = User::getUserByToken();
            if ($user['phone'] != $req['phone']){
                return out(null, 30007, '该手机号不是注册时的手机号');
            }
        }
        if ($req['type'] == 5) {
            if (User::where('phone', $req['phone'])->exists()) {
                return out(null, 30008, '此手机号已经被占用');
            }
        }

        $verify_code = generate_code();
        $result = send_sms($req['phone'], 'verify_template_code', ['code' => $verify_code]);
        if (empty($result['Code']) || $result['Code'] != 'OK'){
            return out(null, 30010, '验证码发送失败，请稍后重试');
        }

        Cache::set($req['phone'].'-'.$req['type'], $verify_code, config('config.aly_sms.sms_verify_code_expire'));

        return out();
    }

    public function doc()
    {
        $database = env('DB_DATABASE');
        $prefix = env('DB_PREFIX');
        $exclude_tables = "'bm_password_resets','bm_admin_menu','bm_admin_users','bm_failed_jobs','bm_migrations'";

        $sql = "select TABLE_NAME name,TABLE_COMMENT comment from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='".$database."' and TABLE_NAME not in (".$exclude_tables.")";
        $tables = \DB::select($sql);
        $map1 = $map2 = [];
        $i = round(count($tables)/2);
        foreach ($tables as $k => $v) {
            $name = str_replace($prefix, '', $v->name);
            if ($k >= $i) {
                $map1[$v->name] = $name.'('.$v->comment.')';
            }
            else {
                $map2[$v->name] = $name.'('.$v->comment.')';
            }
        }

        $data1 = [];
        foreach ($map1 as $k => $v){
            $sql = "select COLUMN_NAME name, DATA_TYPE type, COLUMN_COMMENT comment from INFORMATION_SCHEMA.COLUMNS where table_schema = '".$database."' AND table_name = '".$k."'";
            $comment = \DB::select($sql);
            $data1[$v] = $comment;
        }

        $data2 = [];
        foreach ($map2 as $k => $v){
            $sql = "select COLUMN_NAME name, DATA_TYPE type, COLUMN_COMMENT comment from INFORMATION_SCHEMA.COLUMNS where table_schema = '".$database."' AND table_name = '".$k."'";
            $comment = \DB::select($sql);
            $data2[$v] = $comment;
        }

        return view('doc', ['data1' => $data1, 'data2' => $data2]);
    }

    public function getHelpList()
    {
        $data = HelpInfo::where('status', 1)->orderBy('id', 'desc')->paginate();
        return out($data);
    }

    public function configList()
    {
        $data = [
            'banners' => [
                'https://t5.9026.com/img/banner1.png',
                'https://t5.9026.com/img/banner2.png',
                'https://t5.9026.com/img/banner3.png',
            ],
            'notices' => [
                '宝妈小程序正式公测上线啦！',
            ],
        ];

        return out($data);
    }

    public function getCity()
    {
        $req = request()->post();
        $this->validate(request(), [
            'name' => 'required'
        ]);

        $area = Area::where('name', 'like', $req['name'].'%')->first();
        if (!empty($area) && $area['level'] == 3) {
            $area = Area::where('id', $area['parent_id'])->first();
        }

        return out($area);
    }

    public function buildToken()
    {
        $req = request()->post();
        $this->validate(request(), [
            'user_id' => 'integer',
            'docter_id' => 'integer',
        ]);

        $token = '';
        if (!empty($req['user_id'])) {
            $token = aes_encrypt(['id' => $req['user_id'], 'time' => time()]);
        }
        elseif (!empty($req['docter_id'])) {
            $token = aes_encrypt(['docter_id' => $req['docter_id'], 'time' => time()]);
        }

        return out(['token' => $token]);
    }
}
