<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Leave;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobile_login', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }
    /**
     * 用户信息
     * @ApiMethod (POST)
     * @ApiReturnParams (name=code,type="integer",description=错误码:0=失败1=成功401=未登录403=没有权限)
     * @ApiReturnParams (name=msg,type="string",description=提示信息)
     * @ApiReturnParams (name=data,type="array",description=要返回的数据)
     * @ApiReturnParams (name=data.id,type="integer",description=用户ID)
     * @ApiReturnParams (name=data.username,type="string",description=用户姓名)
     * @ApiReturnParams (name=data.email,type="string",description=邮箱)
     * @ApiReturnParams (name=data.mobile,type="integer",description=手机号)
     * @ApiReturnParams (name=data.avatar,type="string",description=头像地址)
     * @ApiReturnParams (name=data.gender,type="string",description=性别)
     * @ApiReturnParams (name=data.birthday,type="string",description=出生年月)
     * @ApiReturnParams (name=data.rights,type="integer",description=是否有权益:0=没有1=有)
     */
    public function get_user_info()
    {
        $user = $this->auth->getUserinfo();
        $this->success('用户信息', $user);
    }
    /**
     * 手机验证码登录
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     * @ApiReturnParams (name=code,type="integer",description=错误码:0=失败1=成功401=未登录403=没有权限)
     * @ApiReturnParams (name=msg,type="string",description=提示信息)
     * @ApiReturnParams (name=data,type="array",description=要返回的数据)
     * @ApiReturnParams (name=data.token,type="string",description=token值)
     */
    public function mobile_login()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'register')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register('植提桥用户'.substr($mobile,-4), Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'register');
            $data = ['token' => $this->auth->getUserinfo()['token']];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 修改用户信息
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=false, description="头像地址")
     * @ApiParams (name="username", type="string", required=false, description="姓名")
     * @ApiParams (name="gender", type="string", required=false, description="性别")
     * @ApiParams (name="birthday", type="string", required=false, description="出生年月")
     * @ApiParams (name="email", type="string", required=false, description="邮箱地址")
     */
    public function edit_user_info()
    {
        $user = $this->auth->getUser();
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $username = $this->request->post('username');
        $gender = $this->request->post('gender');
        $birthday = $this->request->post('birthday');
        $email = $this->request->post('email');
        if(empty($avatar) && empty($username) && empty($gender) && empty($birthday) && empty($email)){
            $this->error('参数错误');
        }
        if($avatar){
            $user->avatar = $avatar;
        }
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if($gender){
            $user->gender = $gender;
        }
        if($birthday){
            $user->birthday = $birthday;
        }
        if($email){
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $exists = \app\common\model\User::where('username', $email)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error('邮箱已存在');
            }
            $user->email = $email;
        }
        $user->save();
        $this->success('编辑成功');
    }

    /**
     * 第三方登录
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform",'Wechat');
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $openid = $result['openid'];
            $user = \app\common\model\User::getByOpenid($openid);
            if($user){
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            }
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 留言内容
     *
     */
    public function leavelist(){
        $this->success('请求成功',Leave::where('uid',$this->auth->id)->field('id,type,content,createtime')->selectOrFail());
    }

    /**
     * 留言
     * @ApiMethod (POST)
     * @param string $content 留言内容
     */
    public function leave(){
        $input = $this->_validate(['content|留言内容'=>'require']);
        $data = [
            'uid' => $this->auth->id,
            'content' => $input['content'],
            'type' => 1
        ];
        $inc = Leave::insert($data);
        if($inc){
            $this->success('留言成功',$inc);
        }else{
            $this->error('留言失败');
        }
    }
    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }
}
