<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016～2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\merchant\controller;

use app\merchant\model\merchant\MerchantAdmin as AdminMer;
use basic\SystemBasic;
use service\JsonService;
use service\SystemConfigService;
use app\wap\model\user\SmsCode;
use service\AliMessageService;
use service\sms\storage\Sms;
use basic\AuthBasic;
use think\Request;
use think\Url;
use think\Session;

/**
 * 登录验证控制器
 * Class Login
 * @package app\admin\controller
 */
class Login extends AuthBasic
{
    public function index()
    {
        $this->assign([
            'login_logo' => SystemConfigService::get('login_logo'),
            'Auth_site_name' => SystemConfigService::get('site_name'),
        ]);
        return $this->fetch();
    }

    /**
     * 发送短信验证码
     * @param string $phone
     */
    public function code($phone = '')
    {
        $name = "is_phone_code" . $phone;
        if ($phone == '') return JsonService::fail('请输入手机号码!');
        $time = Session::get($name, 'merchant');
        if ($time < time() + 60) Session::delete($name, 'merchant');
        if (Session::has($name, 'merchant') && $time < time()) return JsonService::fail('您发送验证码的频率过高,请稍后再试!');
        $code = AliMessageService::getVerificationCode();
        SmsCode::set(['tel' => $phone, 'code' => md5('is_phone_code' . $code), 'last_time' => time() + 300, 'uid' => 0]);
        Session::set($name, time() + 60, 'merchant');
        $smsHandle = new Sms();
        $sms_platform_selection = SystemConfigService::get('sms_platform_selection');
        $smsSignName = SystemConfigService::get('smsSignName');//短信签名
        $smsTemplateCode = SystemConfigService::get('smsTemplateCode');//短信模板ID
        if ($sms_platform_selection == 1) {
            if (!$smsSignName || !$smsTemplateCode) return JsonService::fail('系统后台短信没有配置，请稍后在试!');
            $res = AliMessageService::sendmsg($phone, $smsTemplateCode, ['code' => $code]);
        } else {
            if (!(int)$smsTemplateCode) return JsonService::fail('请正确的填写系统后台短信配置!');
            $res = $smsHandle->send($phone, $smsTemplateCode, ['code' => $code]);
        }
        if ($res['Code'] == 'OK') {
            return JsonService::successful('发送成功', $res);
        } else {
            return JsonService::fail($res['Message']);
        }
    }

    /**
     * 登录验证 + 验证码验证
     */
    public function verify(Request $request)
    {
        if (!$request->isPost()) return ['code' => 4];
        $array = $request->Post();
        $account = $array['account'];
        $pwd = $array['pwd'];
        $verify = $array['verify'];
        //检验验证码
        if (!captcha_check($verify)) return ['code' => 2];
        $error = Session::get('mer_login_error', 'merchant') ?: ['num' => 0, 'time' => time()];
        if ($error['num'] >= 5 && $error['time'] < strtotime('+ 5 minutes')) {
            return ['code' => 3];
        }
        //检验帐号密码
        $res = AdminMer::login($account, $pwd);
        if ($res) {
            Session::set('mer_login_error', null, 'merchant');
            return ['code' => 1];
        } else {
            $error['num'] += 1;
            $error['time'] = time();
            Session::set('mer_login_error', $error, 'merchant');
            return ['code' => 0, 'msg' => AdminMer::getErrorInfo()];
        }
    }

    /**
     * 短信登陆
     * @param Request $request
     */
    public function phone_check(Request $request)
    {
        if (!$request->isPost()) return JsonService::fail('提交方式有误');
        $array = $request->Post();
        $phone = $array['phone'];
        $code = $array['code'];
        if (!$phone || !$code) return JsonService::fail('请输入登录账号');
        if (!$code) return JsonService::fail('请输入验证码');
        $code = md5('is_phone_code' . $code);
        if (!SmsCode::CheckCode($phone, $code)) return JsonService::fail('验证码验证失败');
        SmsCode::setCodeInvalid($phone, $code);
        if (($info = AdminMer::adminMerLogin($phone)) !== false)
            return JsonService::successful('登录成功', $info);
        else
            return JsonService::fail(AdminMer::getErrorInfo('登录失败'));
    }

    public function captcha()
    {
        ob_clean();
        $captcha = new \think\captcha\Captcha([
            'codeSet' => '0123456789',
            'length' => 4,
            'fontSize' => 30
        ]);
        return $captcha->entry();
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        AdminMer::clearLoginInfo();
        $this->redirect('Login/index');
    }
}
