<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-present http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use app\user\service\UserService;
use cmf\lib\Storage;
use think\Validate;
use think\Image;
use cmf\controller\UserBaseController;
use app\user\model\UserModel;

class ProfileController extends UserBaseController
{

    /**
     * 会员中心首页
     */
    public function center()
    {
        $user = cmf_get_current_user();
        $this->assign($user);

        $userId = cmf_get_current_user_id();

        $userModel = new UserModel();
        $user      = $userModel->where('id', $userId)->find();
        $this->assign('user', $user);
        return $this->fetch();
    }

    /**
     * 编辑用户资料
     */
    public function edit()
    {
        $user = cmf_get_current_user();
        $this->assign($user);
        return $this->fetch('edit');
    }

    /**
     * 编辑用户资料提交
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            $validate = new Validate();
            $validate->rule([
                'user_nickname' => 'max:32',
                'sex'           => 'between:0,2',
                'birthday'      => 'dateFormat:Y-m-d|after:-88 year|before:-1 day',
                'user_url'      => 'url|max:64',
                'signature'     => 'max:128',
            ]);
            $validate->message([
                'user_nickname.max'   => lang('NICKNAME_IS_TO0_LONG'),
                'sex.between'         => lang('SEX_IS_INVALID'),
                'birthday.dateFormat' => lang('BIRTHDAY_IS_INVALID'),
                'birthday.after'      => lang('BIRTHDAY_IS_TOO_EARLY'),
                'birthday.before'     => lang('BIRTHDAY_IS_TOO_LATE'),
                'user_url.url'        => lang('URL_FORMAT_IS_WRONG'),
                'user_url.max'        => lang('URL_IS_TO0_LONG'),
                'signature.max'       => lang('SIGNATURE_IS_TO0_LONG'),
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            if (UserService::editData($data, [
                'user_nickname',
                'send_email',
                'sex',
                'birthday',
                'user_url',
                'signature',
                'more'
            ])) {
                $this->success(lang('EDIT_SUCCESS'), "user/profile/center");
            } else {
                $this->error(lang('NO_NEW_INFORMATION'));
            }
        } else {
            $this->error(lang('ERROR'));
        }
    }

    /**
     * 个人中心修改密码
     */
    public function password()
    {
        $user = cmf_get_current_user();
        $this->assign($user);
        return $this->fetch();
    }

    /**
     * 个人中心修改密码提交
     */
    public function passwordPost()
    {
        if ($this->request->isPost()) {
            $validate = new Validate();
            $validate->rule([
                'old_password' => 'require|min:6|max:32',
                'password'     => 'require|min:6|max:32',
                'repassword'   => 'require|min:6|max:32',
            ]);
            $validate->message([
                'old_password.require' => lang('旧密码不能为空！'),
                'old_password.max'     => lang('旧密码不能超过32个字符！'),
                'old_password.min'     => lang('旧密码不能小于6个字符！'),
                'password.require'     => lang('新密码不能为空！'),
                'password.max'         => lang('新密码不能超过32个字符！'),
                'password.min'         => lang('新密码不能小于6个字符！'),
                'repassword.require'   => lang('重复密码不能为空！'),
                'repassword.max'       => lang('重复密码不能超过32个字符！'),
                'repassword.min'       => lang('重复密码不能小于6个字符！'),
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            $log = UserService::editPassword($data);
            switch ($log) {
                case 0:
                    $this->success(lang('change_success'));
                    break;
                case 1:
                    $this->error(lang('密码输入不一致!'));
                    break;
                case 2:
                    $this->error(lang('原始密码不正确！'));
                    break;
                default :
                    $this->error(lang('ERROR'));
            }
        } else {
            $this->error(lang('ERROR'));
        }

    }

    // 用户头像编辑
    public function avatar()
    {
        $user = cmf_get_current_user();
        $this->assign($user);
        return $this->fetch('avatar');
    }

    // 用户头像上传
    public function avatarUpload()
    {
        $file = $this->request->file('file');

        $validator = validate(['file' => 'fileExt:jpg,jpeg,png']);

        if (!$validator->check(['file' => $file])) {
            if ($this->request->isAjax()) {
                $this->error($validator->getError());
            } else {
                return json_encode([
                    'code' => 0,
                    "msg"  => $validator->getError(),
                    "data" => "",
                    "url"  => ''
                ]);
            }
        }

        $fileMd5 = $file->md5();
        $fileExt = $file->getOriginalExtension();

        $fileName = $fileMd5 . '.' . $fileExt;
        $date     = date('Ymd');

        $avatarDir = WEB_ROOT . 'upload' . DIRECTORY_SEPARATOR . 'avatar' . DIRECTORY_SEPARATOR . $date . DIRECTORY_SEPARATOR;

        $file->move($avatarDir, $fileMd5 . '.' . $fileExt);

        $avatar = 'avatar/' . $date . '/' . $fileName;
        session('avatar', $avatar);

        if ($this->request->isAjax()) {
            $avatarPath = $avatarDir . $fileName;
            $storage    = new Storage();
            $result     = $storage->upload($avatar, $avatarPath, 'image');

            $userId = cmf_get_current_user_id();
            UserModel::where("id", $userId)->update(["avatar" => $avatar]);
            session('user.avatar', $avatar);

            $this->success(lang('Upload successful'), null, ['file' => $avatar]);
        } else {
            return json_encode([
                'code' => 1,
                "msg"  => lang('Upload successful'),
                "data" => ['file' => $avatar],
                "url"  => ''
            ]);
        }
    }

    // 用户头像裁剪
    public function avatarUpdate()
    {
        $avatar = session('avatar');
        if (!empty($avatar)) {
            $w = $this->request->param('w', 0, 'intval');
            $h = $this->request->param('h', 0, 'intval');
            $x = $this->request->param('x', 0, 'intval');
            $y = $this->request->param('y', 0, 'intval');

            $avatarPath = WEB_ROOT . 'upload/' . $avatar;

            $avatarImg = Image::open($avatarPath);

            $avatarImg->crop($w, $h, $x, $y)->save($avatarPath);

            $result = true;
            if ($result === true) {
                $storage = new Storage();
                $result  = $storage->upload($avatar, $avatarPath, 'image');

                $userId = cmf_get_current_user_id();
                UserModel::where('id', $userId)->update(['avatar' => $avatar]);
                session('user.avatar', $avatar);
                $this->success(lang('EDIT_SUCCESS'));
            } else {
                $this->error(lang('EDIT_FAILED'));
            }

        }
    }

    /**
     * 绑定手机号或邮箱
     */
    public function binding()
    {
        $user = cmf_get_current_user();
        $this->assign($user);
        return $this->fetch();
    }

    /**
     * 绑定手机号
     */
    public function bindingMobile()
    {
        if ($this->request->isPost()) {
            $validate = new Validate();
            $validate->rule([
                'username'          => 'require|number|unique:user,mobile',
                'verification_code' => 'require',
            ]);
            $validate->message([
                'username.require'          => lang('手机号不能为空！'),
                'username.number'           => lang('手机号只能为数字！'),
                'username.unique'           => lang('手机号已存在！'),
                'verification_code.require' => lang('数字验证码不能为空！'),
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
            if (!empty($errMsg)) {
                $this->error($errMsg);
            }

            $log = UserService::bindingMobile($data);
            switch ($log) {
                case 0:
                    $this->success(lang('手机号绑定成功！'));
                    break;
                default :
                    $this->error(lang('未受理的请求！'));
            }
        } else {
            $this->error(lang('illegal request'));
        }
    }

    /**
     * 绑定邮箱
     */
    public function bindingEmail()
    {
        if ($this->request->isPost()) {
            $validate = new Validate();
            $validate->rule([
                'username'          => 'require|email|unique:user,user_email',
                'verification_code' => 'require',
            ]);
            $validate->message([
                'username.require'          => lang('邮箱不能为空！'),
                'username.email'            => lang('邮箱格式不正确！'),
                'username.unique'           => lang('邮箱已存在！'),
                'verification_code.require' => lang('数字验证码不能为空！'),
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
            if (!empty($errMsg)) {
                $this->error($errMsg);
            }

            $log = UserService::bindingEmail($data);
            switch ($log) {
                case 0:
                    $this->success(lang('邮箱绑定成功！'));
                    break;
                default :
                    $this->error(lang('未受理的请求！'));
            }
        } else {
            $this->error(lang('illegal request'));
        }
    }

}
