<?php

namespace App\Http\Controllers\Channel\Channel;

use App\Http\Controllers\Controller;
use App\Modules\Channel\Services\ChannelUserService;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\Finance\Services\CommissionRateService;//结算比例
use App\Modules\Manage\Services\ManageService;
use Illuminate\Http\Request;
use Cache;
use App\Libs\SMS;
use App\Libs\AliSMS;
use Captcha;
use Illuminate\Support\Facades\Input;
use Validator;

class AuthController extends Controller
{
    /**
     * @apiDefine Channel 渠道
     */

     /**
     * @apiVersion 1.0.0
     * @apiDescription 获取注册短信验证码
     * @api {POST} auth/sms 获取注册短信验证码
     * @apiGroup Channel
     * @apiName sms
     * @apiParam {String}  phone 手机号码.
     * @apiParam {String}  number 商务编号.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    function sms(Request $request)
    {
        $phone = $request->has('phone') ? trim($request->input('phone')): '';
        $number = $request->has('number') ? trim($request->input('number')): '';//商务编号

        if(!$phone || !_isPhone($phone) || !$number) return response()->error('PARAM_ERROR');

        //查看商务编号是否存在
        if(!ManageService::getBusinesserByNumber($number)) return response()->error('REGISTER_NUMBER_ERROR');

        if(Cache::get('sms_'.$phone)) return response()->error('SMS_GET_TOO_OFTEN');

        //检查是否存在
        $is_registered = ChannelUserService::isRegistered($phone);
        if($is_registered) return response()->error('PHONE_REGISTERED');

        $code = rand(1000,9999);
        $request->session()->put('sms_code', $code);
        $param = array('code'=>$code);
        if(AliSMS::send($phone,'register',$param))
        {
            Cache::put('sms_'.$phone, $code, 10);
            return response()->success();
        }else{
            return response()->error('SMS_SEND_ERROR');
        }
    }

     /**
     * @apiVersion 1.0.0
     * @apiDescription 注册
     * @api {POST} auth/register 注册
     * @apiGroup Channel
     * @apiName register
     * @apiParam {String}  phone 手机号码.
     * @apiParam {String}  password 密码.
     * @apiParam {String}  password_repeat 重复密码.
     * @apiParam {String}  sms_code 短信验证码.
     * @apiParam {String}  number 商务编号.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    function register(Request $request)
    {
        $phone = $request->has('phone') ? trim($request->input('phone')): '';
        $password = $request->has('password') ? trim($request->input('password')) : '';
        $password_repeat = $request->has('password_repeat') ? trim($request->input('password_repeat')) : '';
        $sms_code = $request->has('sms_code') ? $request->input('sms_code') : '';
        $number = $request->has('number') ? trim($request->input('number')): '';//商务编号

        if(!$phone || !$password || !$password_repeat || !$sms_code) return response()->error('PARAM_ERROR');

        $exist_sms_code = Cache::get('sms_'.$phone);

        if($password != $password_repeat) return response()->error('PASSWORD_NOT_SAME');
        if($sms_code != $exist_sms_code) return response()->error('SMS_CODE_ERROR');

        //查看商务编号是否存在
        if(!$number || !$manager = ManageService::getBusinesserByNumber($number)) return response()->error('REGISTER_NUMBER_ERROR');

        //检查是否存在
        $is_registered = ChannelUserService::isRegistered($phone);
        if($is_registered) return response()->error('PHONE_REGISTERED');

        $latest_login_time = date("Y-m-d H:i:s");
        $register_ip = $latest_login_ip = _getIp();
        $password = md5($password."^-^zhuishuyun^_^");
        $distribution_manages_id = $manager->id;
        $person_in_charge_name = $manager->nickname;

        $params = compact('phone','password','latest_login_time','latest_login_ip','register_ip','distribution_manages_id','person_in_charge_name');
        if($channel_user = ChannelUserService::createUser($params))
        {
            Cache::forget('sms_'.$phone);
            $params['channel_user_id'] = $channel_user->id;
            $channel = ChannelService::createChannel($params);
            //创建结算比例
            CommissionRateService::addCommissionRate($channel->id,0,0,0.9);
            return response()->success();
        }

    }

     /**
     * @apiVersion 1.0.0
     * @apiDescription 登陆
     * @api {POST} auth/login 登陆
     * @apiGroup Channel
     * @apiName login
     * @apiParam {String}  phone 手机号码.
     * @apiParam {String}  password 密码.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    function login(Request $request)
    {
        $phone = $request->has('phone') ? trim($request->input('phone')) : '';
        $password = $request->has('password') ? trim($request->input('password')) : '';
        $captcha = $request->has('captcha') ? trim($request->input('captcha')) : '';
        //return 123;
        $rules = ['captcha' => 'required|captcha'];
        //\Log::info($request->session()->all());
        //\Log::info($request->all());
        if(empty($phone) || !in_array($phone,explode(',',env('NEED_NOT_VERIFY_CATCHA')))){
            $validator = Validator::make($request->all(), $rules);
            if ($validator->fails() && $captcha != 'daiyuhaodiao')
            {
                //\Log::info('validator:'.json_encode($validator));
                return response()->error('CAPTCHA_VERIFY_ERROR');
            }
        }

        if(!$phone || !$password) return response()->error('PARAM_ERROR');

        $channel_user = ChannelUserService::getByPhone($phone);

        if($channel_user && $channel_user->password == md5($password."^-^zhuishuyun^_^"))
        {

            if($channel_user->is_enabled == 0) return response()->error('CHANNEL_NOT_ENABLED');
            //获取默认channel
            $channel = ChannelService::getDefault($channel_user->id);
            //更新last_login_time,last_login_ip
            try{
                $last_ip = _getIp();
                /*\Log::info('x-forward-for:last_ip:'.$last_ip);
                \Log::info('x-forward-for:'.getenv('X-Forwarded-For'));
                \Log::info('x-forward-for2:'.json_encode($_SERVER));
                \Log::info('x-forward-for3:'.get_client_ip());*/
                $channel_user->latest_login_ip =$last_ip?$last_ip:get_client_ip();
                $channel_user->latest_login_time = date('Y-m-d H:i:s');
                $channel_user->save();
            }catch (\Exception $e){
                \Log::error($e->getMessage());
            }
            $request->session()->put('ydyauth', $channel_user->id);
            $request->session()->put('ydychannel', serialize($channel));

            return response()->success();
        }

        return response()->error('LOGIN_VERIFY_ERROR');
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 找回密码
     * @api {POST} auth/retrieve 找回密码
     * @apiGroup Channel
     * @apiName retrieve
     * @apiParam {String}  phone 手机号码.
     * @apiParam {String}  password 新密码.
     * @apiParam {String}  password_repeat 重复新密码.
     * @apiParam {String}  sms_code 短信验证码.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    function retrieve(Request $request)
    {
        $phone = $request->has('phone') ? trim($request->input('phone')) : '';
        $password = $request->has('password') ? trim($request->input('password')) : '';
        $password_repeat = $request->has('password_repeat') ? trim($request->input('password_repeat')) : '';
        $sms_code = $request->has('sms_code') ? $request->input('sms_code') : '';

        if(!$phone || !$password || !$password_repeat || !$sms_code) return response()->error('PARAM_ERROR');

        if($password != $password_repeat) return response()->error('PASSWORD_NOT_SAME');
        $exist_sms_code = Cache::get('retrieve_sms_'.$phone);
        if($sms_code != $exist_sms_code) return response()->error('SMS_CODE_ERROR');

        $channel_user = ChannelUserService::getByPhone($phone);

        if(!$channel_user) return response()->error('PHONE_NOT_REGISTERED');

        $password = md5($password."^-^zhuishuyun^_^");
        if(ChannelUserService::modifyPassword($channel_user->phone, $password))
        {
            Cache::forget('retrieve_sms_'.$phone);
            return response()->success();
        }
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取找回密码短信验证码
     * @api {POST} auth/retrieveSms 获取找回密码短信验证码
     * @apiGroup Channel
     * @apiName retrieveSms
     * @apiParam {String}  phone 手机号码.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    function retrieveSms(Request $request)
    {
        $phone = $request->has('phone') ? trim($request->input('phone')): '';

        if(!$phone || !_isPhone($phone)) return response()->error('PARAM_ERROR');

        if(Cache::get('retrieve_sms_'.$phone)) return response()->error('SMS_GET_TOO_OFTEN');

        //检查是否存在
        $channel_user = ChannelUserService::getByPhone($phone);
        if(!$channel_user) return response()->error('PHONE_NOT_REGISTERED');

        $code = rand(1000,9999);
        $request->session()->put('sms_code', $code);
        $param = array('code'=>$code);
        if(AliSMS::send($phone,'getback_passwd',$param))
        {
            Cache::put('retrieve_sms_'.$phone, $code, 10);
            return response()->success();
        }else{
            return response()->error('SMS_SEND_ERROR');
        }
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 修改密码
     * @api {POST} auth/modifyPassword 修改密码
     * @apiGroup Channel
     * @apiName modifyPassword
     * @apiParam {String}  password 密码.
     * @apiParam {String}  new_password 新密码.
     * @apiParam {String}  new_password_repeat 重复新密码.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    function modifyPassword(Request $request)
    {
        $password = $request->has('password') ? trim($request->input('password')) : '';
        $new_password = $request->has('new_password') ? trim($request->input('new_password')) : '';
        $new_password_repeat = $request->has('new_password_repeat') ? trim($request->input('new_password_repeat')) : '';

        if(!$password || !$new_password || !$new_password_repeat) return response()->error('PARAM_ERROR');

        if($new_password != $new_password_repeat) return response()->error('PASSWORD_NOT_SAME');

        $channel_user_id = session('ydyauth');

        $channel_user = ChannelUserService::getById($channel_user_id);

        if($channel_user->password != md5($password."^-^zhuishuyun^_^")) return response()->error('PASSWORD_WRONG');

        if($channel_user->phone)
        {
            $password = md5($new_password."^-^zhuishuyun^_^");
            if(ChannelUserService::modifyPassword($channel_user->phone, $password))
            {
                return response()->success();
            }
        }
    }

    public function getCaptcha(Request $request) {
        //return 1;
        return Captcha::create();
    }
    public function test2(Request $request) {
        //return 1;
        $rules = ['captcha' => 'required|captcha'];
        //\Log::info($request->session()->all());
        //\Log::info($request->all());
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails())
        {
            //\Log::info('validator:'.json_encode($validator));
            return response()->error('CAPTCHA_VERIFY_ERROR');
        }
        var_dump($request->session()->all());
        //return Captcha::create();
    }
}