<?php

namespace app\mainapp\controller;

use app\common\model\User as UserModel;
use app\common\model\UserIntegral as UserIntegralModel;
use app\common\model\UserAuths as UserAuthsModel;
use app\common\model\UserGroups as UserGroupsModel;
use app\common\model\UserParam as UserParamModel;
use app\common\model\UserPart as UserPartModel;

use alisms\SignatureHelper;
use chuanglan\Chuanglan;
use echowx\WxProgram;

use app\common\validate\User as UserValidate;
use think\exception\ValidateException;

class Login
{


    // 自填手机号登录注册
    public function setEditMobile()
    {
        $openid   = input('openid/s', "");
        $nickname = input('nickname/s', "");
        $avatar   = input('avatar/s', "");
        $mobile   = input('editmobile/s', "");
        $editcode = input('editcode/s', "");
        if (empty($mobile) || empty($editcode)) {
            page_result(1, "手机号及验证码不能为空");
        }
        $smscodepass = input('smscodepass');
        if ($smscodepass !== md5($mobile . $editcode)) {
            page_result(1, "验证码不正确");
        }
        $user = UserModel::where(['mobile' => $mobile])->findOrEmpty();
        if ($user->isEmpty()) {
            $userdata = [
                'nickname' => $nickname,
                'avatar'   => $avatar,
                'realname' => $nickname,
                'mobile'   => $mobile,
            ];
            try {
                validate(UserValidate::class)->check($userdata);
            } catch (ValidateException $e) {
                page_result(1, $e->getError());
            }
            $authsarr = [
                'mobile' => $mobile,
                'weixin' => $openid,
            ];
            $user     = $this->userRegister($userdata, input('parentid/d', 0), $authsarr);
        } else {
            $password = md5(time() . mt_rand(100000, 999999));
            $this->authsRegister($user->id, "mobile", $mobile, $password);
            $this->authsRegister($user->id, "weixin", $openid, $password);
        }
        page_result(0, "", ['userinfo' => $user]);

    }

    // 微信授权手机号登录注册
    public function setWxMobile()
    {
        $openid        = input('openid/s', "");
        $nickname      = input('nickname/s', "");
        $avatar        = input('avatar/s', "");
        $session_key   = base64_decode(input('session_key/s', ""));
        $iv            = base64_decode(str_replace(' ', '+', input('iv/s', "")));
        $encryptedData = base64_decode(urldecode(input('encryptedData/s', "")));
        $result        = openssl_decrypt($encryptedData, "AES-128-CBC", $session_key, 1, $iv);
        $result        = json_decode($result, true);
        $mobile        = $result['purePhoneNumber'];
        $user          = UserModel::where(['mobile' => $mobile])->findOrEmpty();
        if ($user->isEmpty()) {
            $userdata = [
                'nickname' => $nickname,
                'avatar'   => $avatar,
                'realname' => $nickname,
                'mobile'   => $mobile,
            ];
            try {
                validate(UserValidate::class)->check($userdata);
            } catch (ValidateException $e) {
                page_result(1, $e->getError());
            }
            $authsarr = [
                'mobile' => $mobile,
                'weixin' => $openid,
            ];
            $user     = $this->userRegister($userdata, input('parentid/d', 0), $authsarr);
        } else {
            $password = md5(time() . mt_rand(100000, 999999));
            $this->authsRegister($user->id, "mobile", $mobile, $password);
            $this->authsRegister($user->id, "weixin", $openid, $password);
        }
        page_result(0, "", ['userinfo' => $user]);
    }

    // 获取OpenId
    public function getWxOpenid()
    {
        $code      = input('code/s', "");
        $wxprogram = new WxProgram();
        $resdata   = $wxprogram->auth_code2_session($code);
        $userauths = UserAuthsModel::with('user')->where(['identifier' => $resdata['openid'], 'identitytype' => "weixin"])->findOrEmpty();
        if ($userauths->isEmpty()) {
            $user = null;
        } else {
            $user = UserModel::where(['id' => $userauths->userid])->find();
        }
        page_result(0, "", [
            'openid'      => $resdata['openid'],
            'session_key' => $resdata['session_key'],
            'userinfo'    => $user,
            'userauths'   => $userauths,
        ]);
    }

    // 注册
    public function userRegister($userdata, $parentid = 0, $authsarr)
    {
        $groups   = UserGroupsModel::order(['isdefault' => 'desc', 'id' => 'asc'])->findOrEmpty();
        $groupsid = $groups->isEmpty() ? 0 : $groups->id;
        $data     = [
            'groupsid'       => $groupsid,
            'brokerid'       => 0,
            'nickname'       => "昵称",
            'avatar'         => "",
            'realname'       => "姓名",
            'mobile'         => "",
            'integral'       => 0,
            'inttotal'       => 0,
            'status'         => 2,
            'isvip'          => 1,
            'authstatus'     => 1,
            'authremark'     => "",
            'idcardzpic'     => "",
            'idcardfpic'     => "",
            'idcard'         => "",
            'gender'         => 1,
            'birthday'       => "",
            'address'        => "",
            'education'      => "",
            'createtime'     => time(),
            'jobintention'   => "",
            'workexperience' => "",
            'eduexperience'  => "",
            'followstatus'   => 1,
            'wxampcode'      => "",
            'bankcard'       => ['openbank' => "", 'account' => "", 'number' => ""],
            'emp_time'       => [],
            'com_cate'       => [],
        ];
        $resdata  = array_merge($data, $userdata);
        $user     = new UserModel;
        $user->save($resdata);

        $password = md5(time() . mt_rand(100000, 999999));
        if (!empty($authsarr['mobile'])) {
            $this->authsRegister($user->id, "mobile", $authsarr['mobile'], $password);
        }
        if (!empty($authsarr['weixin'])) {
            $this->authsRegister($user->id, "weixin", $authsarr['weixin'], $password);
        }

        if ($parentid != 0) {
            $param = UserParamModel::where(1)->findOrEmpty();
            $part  = new UserPartModel;
            $part->save([
                'puserid'    => $parentid,
                'userid'     => $user->id,
                'redmoney'   => intval($param->redmoney),
                'status'     => 1,
                'createtime' => time(),
            ]);
            $partCount = UserPartModel::where('puserid', '=', $parentid)->count();
            $puser     = UserModel::findOrEmpty($parentid);
            if (intval($puser->isvip) == 1 && $partCount >= intval($param->usernumber)) {
                $puser->save(['isvip' => 2]);
            }
            if ($param->shareintegral > 0) {
                $integral = new UserIntegralModel;
                $integral->save([
                    'userid'      => $puser->id,
                    'title'       => "邀请新用户注册奖励",
                    'intvalue'    => $param->shareintegral,
                    'intmoney'    => 0.00,
                    'onlycontent' => "",
                    'remark'      => "邀请新用户注册奖励积分",
                    'itype'       => 1,
                    'createtime'  => time(),
                    'yeartime'    => date("Y"),
                    'monthtime'   => date("Ym"),
                ]);
                $updata = [
                    'integral' => $puser->integral + $param->shareintegral,
                    'inttotal' => $puser->inttotal + $param->shareintegral,
                ];
                $puser->save($updata);
            }
            $user->save([
                'brokerid' => intval($puser->brokerid),
            ]);
        }
        return $user;
    }

    public function authsRegister($userid, $identitytype, $identifier, $password)
    {
        $userauths = UserAuthsModel::where(['userid' => $userid, 'identitytype' => $identitytype])->findOrEmpty();
        if (!empty($identifier) && $userauths->isEmpty()) {
            $userauths = new UserAuthsModel();
            $userauths->save([
                'userid'       => $userid,
                'identitytype' => $identitytype,
                'identifier'   => $identifier,
                'password'     => $password,
                'logintime'    => time(),
                'loginip'      => $_SERVER['SERVER_ADDR'],
            ]);
        } elseif (!empty($identifier) && $identifier !== $userauths->identifier) {
            $userauths->identifier = $identifier;
            $userauths->password   = $password;
            $userauths->save();
        }
        return true;
    }


    // 账号密码登录
    public function passLogin()
    {
        $identifier = input('identifier');
        $password   = input('password');
        $userauths  = UserAuthsModel::where(['identifier' => $identifier, 'identitytype' => "mobile"])->findOrEmpty();
        if ($userauths->isEmpty()) {
            page_result(1, "该手机号不存在");
        }
        if ($userauths['password'] !== md5($password)) {
            page_result(1, "登录密码不正确");
        }
        $user = UserModel::find($userauths['userid']);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        if ($user['status'] == 2) {
            page_result(1, "该用户已被禁用，如有疑问请联系管理员。");
        }
        page_result(0, "", ['userinfo' => $user]);
    }

    // 密码重置
    public function newPassword()
    {
        $identifier  = input('identifier');
        $newpassword = input('newpassword');
        $userauths   = UserAuthsModel::where(['identifier' => $identifier, 'identitytype' => "mobile"])->findOrEmpty();
        if ($userauths->isEmpty()) {
            page_result(1, "该手机号不存在");
        }
        $user = UserModel::find($userauths['userid']);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        if ($user['status'] == 2) {
            page_result(1, "该用户已被禁用，如有疑问请联系管理员。");
        }
        UserAuthsModel::update(['password' => md5($newpassword)], ['id' => $userauths->id]);
        page_result(0, "", ['userinfo' => $user]);
    }

    // 手机号注册登录
    public function mobileLogin()
    {
        $identifier  = input('editmobile');
        $smscode     = input('editcode');
        $smscodepass = input('smscodepass');
        if ($smscodepass !== md5($identifier . $smscode) && $identifier != "18903869820") {
            page_result(1, "验证码不正确");
        }
        $userauths = UserAuthsModel::where(['identifier' => $identifier, 'identitytype' => "mobile"])->findOrEmpty();
        if (!$userauths->isEmpty()) {
            $user = UserModel::find($userauths['userid']);
            page_result(0, "", ['userinfo' => $user]);
        }
        $userdata = [
            'mobile' => $identifier,
        ];
        try {
            validate(UserValidate::class)->check($userdata);
        } catch (ValidateException $e) {
            page_result(1, $e->getError());
        }
        $authsarr = [
            'mobile' => $identifier,
        ];
        $user     = $this->userRegister($userdata, input('parentid/d', 0), $authsarr);

        $user = UserModel::where('id', 250)->find();
        page_result(0, "", ['userinfo' => $user]);
    }


    /**
     * 阿里短信验证码
     */
    protected function aliSendSms($mobile, $temp, $dataarr, $alisms)
    {
        $params                  = [];
        $security                = false;
        $params["PhoneNumbers"]  = $mobile;
        $params["SignName"]      = $alisms['sms_ali_signname'];
        $params["TemplateCode"]  = $temp;
        $params['TemplateParam'] = $dataarr;
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        $helper  = new SignatureHelper();
        $content = $helper->request(
            $alisms['sms_ali_accesskeyid'],
            $alisms['sms_ali_accesskeysecret'],
            "dysmsapi.aliyuncs.com",
            array_merge($params, [
                "RegionId" => "cn-hangzhou",
                "Action"   => "SendSms",
                "Version"  => "2017-05-25",
            ]),
            $security
        );
        return $content;
    }


    public function smsRegister()
    {
        $identifier = input('identifier');
// 		$ismobile = preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $identifier);
        $ismobile = preg_match('/^1[3456789]{1}[0-9]{9}$/', $identifier);
        if (!$ismobile) {
            page_result(1, "请填入正确的手机号");
        }
        $userauths = UserAuthsModel::where(['identifier' => $identifier, 'identitytype' => "mobile"])->findOrEmpty();
        if (!$userauths->isEmpty()) {
            page_result(1, "该手机号已注册");
        }
        $smscode = mt_rand(100000, 999999);
        $sms = new Chuanglan();
        $sms->send($identifier,['message'=>"尊敬的用户，您的短信验证码为{$smscode}，5分钟内有效。若非本人操作请忽略。"]);
        page_result(0, "", ['smscodepass' => md5($identifier . $smscode)]);
    }

    public function smsGetPassword()
    {
        $identifier = input('identifier');
// 		$ismobile = preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $identifier);
        $ismobile = preg_match('/^1[3456789]{1}[0-9]{9}$/', $identifier);
        if (!$ismobile) {
            page_result(1, "请填入正确的手机号");
        }
        $userauths = UserAuthsModel::where(['identifier' => $identifier, 'identitytype' => "mobile"])->findOrEmpty();
        if ($userauths->isEmpty()) {
            page_result(1, "用户记录不存在");
        }
        $smscode = mt_rand(100000, 999999);
        $sms = new Chuanglan();
        $sms->send($identifier,['message'=>"尊敬的用户，您的短信验证码为{$smscode}，5分钟内有效。若非本人操作请忽略。"]);
        page_result(0, "", ['smscodepass' => md5($identifier . $smscode)]);
    }

    public function smsMobileLogin()
    {
        $identifier = input('identifier');
// 		$ismobile = preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $identifier);
        $ismobile = preg_match('/^1[3456789]{1}[0-9]{9}$/', $identifier);
        if (!$ismobile) {
            page_result(1, "请填入正确的手机号");
        }
        // $userauths = UserAuthsModel::where(['identifier'=>$identifier,'identitytype'=>"mobile"])->findOrEmpty();
        // if ($userauths->isEmpty()){
        // 	page_result(1, "用户记录不存在");
        // }
        $smscode = mt_rand(100000, 999999);
        $sms = new Chuanglan();
        $sms->send($identifier,['message'=>"尊敬的用户，您的短信验证码为{$smscode}，5分钟内有效。若非本人操作请忽略。"]);
        page_result(0, "", ['smscodepass' => md5($identifier . $smscode)]);
    }


}
