<?php

namespace app\mobile\controller;

use app\common\model\FeedbackModel;
use app\common\model\NoticeModel;
use app\common\model\UserModel;
use app\mobile\MobileBaseController;
use app\mobile\validate\UserValidate;
use think\App;
use think\exception\ValidateException;
use think\facade\View;

class My extends MobileBaseController
{
    private $_user = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->_user = get_user();
        View::assign('user', $this->_user);
    }

    public function index()
    {
        return view();
    }

    public function info()
    {
        return view();
    }

    public function infoPost()
    {
        $data = input('post.');
        $edit = ['avatar', 'nickname', 'gender', 'birthday'];
        try {
            validate(UserValidate::class)->check($data);
        } catch (ValidateException $e) {
            ajax_return(1, $e->getError());
        }

        //账号验证
        if (empty($this->_user['account'])) {
            empty($data['account']) && ajax_return(1, '请填写账号');
            $check = UserModel::where('account', $data['account'])->find();
            if (!empty($check)) {
                ajax_return(1, '该账号已存在');
            }
            $edit[] = 'account';
        }

        foreach ($edit as $v) {
            $this->_user->$v = $data[$v];
        }
        $this->_user->save();

        ajax_return();
    }

    public function password()
    {
        return view();
    }

    public function passwordPost()
    {
        $new_password   = input('post.new_password');
        $renew_password = input('post.renew_password');

        if ($new_password != $renew_password) {
            ajax_return(1, '两次密码不一致');
        }

        if (preg_match("/^(?![^a-zA-Z]+$)(?!\D+$).{6,}$/", $new_password) === false) {
            ajax_return(1, '密码必须大于6位，且包括字母和数字');
        }

        if (!empty($this->_user['password'])) {
            $old_password = input('post.old_password');
            if (md5(md5($this->_user->salt) . $new_password) != $old_password) {
                ajax_return(1, '旧密码错误');
            }
        }

        $this->_user->salt     = rand_str();
        $this->_user->password = md5(md5($this->_user->salt) . $new_password);
        $this->_user->save();
        ajax_return();
    }

    public function mobile()
    {
        return view();
    }

    public function mobilePost()
    {
        $param = input('post.');
        empty($param['mobile']) && ajax_return(1, '请输入手机号');
        empty($param['verify']) && ajax_return(1, '请输入验证码');

        //验证码校验
        if (config('mobile.sms_verify_expire') > 0) {
            $verify_expire = session('mobile.login.verify_expire');
            if ($verify_expire + config('mobile.sms_verify_expire') < time()) {
                session('mobile.login.verify', null);
                session('mobile.login.verify_expire', null);
                ajax_return(1, '验证码已过期');
            }
        }
        $verify = session('mobile.login.verify');
        if ($verify != $param['verify']) {
            ajax_return(1, '验证码不正确');
        }

        $check = UserModel::where('mobile', $param['mobile'])->find();
        if (!empty($check)) {
            ajax_return(1, '该手机号已绑定');
        }

        $this->_user->mobile = $param['mobile'];
        $this->_user->save();

        ajax_return();
    }

    public function auth()
    {
        return view();
    }

    public function authPost()
    {
        if (!in_array($this->_user['is_auth'], [UserModel::AUTH_UN, UserModel::AUTH_REJECT])) {
            ajax_return(1, '当前状态无法提交');
        }

        $data = [];
        foreach (UserModel::MOBILE_EDIT_ALLOW as $v) {
            $data[$v] = input("post.{$v}");
        }

        try {
            validate([
                'realname'         => 'require',
                'idcard'           => 'require|idCard',
                'idcard_front_pic' => 'require',
                'idcard_back_pic'  => 'require',
            ], [
                'realname'         => '请填写真实姓名',
                'idcard'           => '身份证格式错误',
                'idcard_front_pic' => '请上传身份证（头像页）',
                'idcard_back_pic'  => '请上传身份证（国徽页）',
            ])->check($data);
        } catch (ValidateException $e) {
            ajax_return(1, $e->getError());
        }

        $data['is_auth'] = UserModel::AUTH_WAIT;
        UserModel::update($data, ['id' => $this->_user['id']], UserModel::MOBILE_EDIT_ALLOW);

        ajax_return();
    }

    public function about()
    {
        return view();
    }

    public function notice()
    {
        return view();
    }

    public function listNotice()
    {
        $list = NoticeModel::where('status', NoticeModel::STATUS_PUBLISH)
            ->order(['priority' => 'desc', 'update_time' => 'desc'])
            ->limit(input('limit', 10))
            ->page(input('page', 1))
            ->select();

        ajax_success($list);
    }

    public function noticeDetail()
    {
        $id = input('id/d', 0);
        empty($id) && jump('该消息不存在');

        $info = NoticeModel::where('status', NoticeModel::STATUS_PUBLISH)->find($id);
        empty($info) && jump('该消息不存在');

        return view('', [
            'info' => $info,
        ]);
    }

    public function feedback()
    {
        return view();
    }

    public function feedbackPost()
    {
        $param            = input('param.');
        $param['user_id'] = $this->_user['id'];
        FeedbackModel::create($param);
        ajax_return();
    }
}
