<?php

namespace app\manystoreapi\controller;

use addons\xilufitness\services\login\LoginService;
use app\common\controller\ManystoreApiBase;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\dyqc\ManystoreShop;
use app\common\model\manystore\UserAuth;
use app\manystore\model\Manystore;
use fast\Random;
use think\Cache;
use think\Config;
use think\Db;
use think\Log;
use think\Validate;
use app\admin\library\Wechat;

/**
 * 机构API后台：机构账户接口
 */
class User extends ManystoreApiBase
{
    protected $noNeedLogin = ["registerLogin",'getOpenid','decodeData','login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    protected $miniConfig;

    public function _initialize()
    {
        $this->miniConfig = (new Wechat)->getMiniConfig();
        parent::_initialize();
//        if (!Config::get('fastadmin.usercenter')) {
//            $this->error(__('User center already closed'));
//        }
    }






    /**
     * 会员中心
     */
    public function index()
    {

        $data =  [
            'welcome' => $this->auth->nickname,
            'user_info'=>$this->auth->getUserinfo()
        ];

        $data['user_info']["avatar"] = $data['user_info']["avatar"]? cdnurl($data['user_info']["avatar"],true):$data['user_info']["avatar"];
        $this->apisuccess('调用成功',$data);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->apierror(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->apisuccess(__('Logged in successful'), $data);
        } else {
            $this->apierror($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $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, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = Manystore::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = null;
//            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->apisuccess(__('Logged in successful'), $data);
        } else {
            $this->apierror($this->auth->getError());
        }
    }



    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->apierror(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->apisuccess(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="update_fields", type="json", required=true, description="本次需要更新的用户字段json格式：更新谁传谁的字段名，比如：只更新头像和昵称 则 json=['avatar','nickname']")
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $update_fields = $this->request->post('update_fields/a',[]);
//        var_dump($update_fields);die;

        if(!$update_fields)$this->error(__('请指定要更新的字段！'));
        $username = $this->request->post('username/s');
        $nickname = $this->request->post('nickname/s');
//        $realname = $this->request->post('realname/s');
//        $gender = $this->request->post('gender/d');
//        $birthday = $this->request->post('birthday/s');
//        $work = $this->request->post('work/s');
//        $bio = $this->request->post('bio/s',null);
        $avatar = $this->request->post('avatar', null, 'trim,strip_tags,htmlspecialchars');


        if ($username && in_array('username', $update_fields)) {
            $exists = Manystore::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->apierror(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname && in_array('nickname', $update_fields)) {
            $exists = Manystore::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->apierror(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
//        if(in_array('bio', $update_fields))$user->bio = $bio;
        if($avatar!==null && in_array('avatar', $update_fields))$user->avatar = $avatar;

//        if(in_array('realname', $update_fields))$user->realname = $realname;
//        if(in_array('gender', $update_fields)){
//            if(!in_array($gender, [1,0]))$this->error(__('请输入正确的性别！'));
//            $user->gender = $gender;
//        }
//        if(in_array('birthday', $update_fields))$user->birthday = $birthday;
//        if(in_array('work', $update_fields))$user->work = $work;
        $user->save();
        //调用事件
        $datas = ['user' => $user];
        \think\Hook::listen('manystore_update_after', $datas);



        $this->apisuccess();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->apierror(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->apierror(__('Email is incorrect'));
        }
        if (Manystore::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->apierror(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->apierror(__('Captcha is incorrect'));
        }
//        $verification = $user->verification;
//        $verification->email = 1;
//        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->apisuccess();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->apierror(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->apierror(__('Mobile is incorrect'));
        }
        if (Manystore::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->apierror(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->apierror(__('Captcha is incorrect'));
        }
//        $verification = $user->verification;
//        $verification->mobile = 1;
//        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->apisuccess();
    }


//    /**
//     * 重置密码
//     *
//     * @ApiMethod (POST)
//     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
//     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
//     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
//     */
//    public function resetpwd()
//    {
//        $type = $this->request->post("type", "mobile");
//        $mobile = $this->request->post("mobile");
//        $email = $this->request->post("email");
//        $newpassword = $this->request->post("newpassword");
//        $captcha = $this->request->post("captcha");
//        if (!$newpassword || !$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
//        //验证Token
//        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
//            $this->error(__('Password must be 6 to 30 characters'));
//        }
//        if ($type == 'mobile') {
//            if (!Validate::regex($mobile, "^1\d{10}$")) {
//                $this->error(__('Mobile is incorrect'));
//            }
//            $user = \app\common\model\User::getByMobile($mobile);
//            if (!$user) {
//                $this->error(__('User not found'));
//            }
//            $ret = Sms::check($mobile, $captcha, 'resetpwd');
//            if (!$ret) {
//                $this->error(__('Captcha is incorrect'));
//            }
//            Sms::flush($mobile, 'resetpwd');
//        } else {
//            if (!Validate::is($email, "email")) {
//                $this->error(__('Email is incorrect'));
//            }
//            $user = \app\common\model\User::getByEmail($email);
//            if (!$user) {
//                $this->error(__('User not found'));
//            }
//            $ret = Ems::check($email, $captcha, 'resetpwd');
//            if (!$ret) {
//                $this->error(__('Captcha is incorrect'));
//            }
//            Ems::flush($email, 'resetpwd');
//        }
//        //模拟一次登录
//        $this->auth->direct($user->id);
//        $ret = $this->auth->changepwd($newpassword, '', true);
//        if ($ret) {
//            $this->success(__('Reset password successful'));
//        } else {
//            $this->error($this->auth->getError());
//        }
//    }





    /**
     * @ApiTitle( 用户列表查看（取决于搜索条件）)
     * @ApiSummary(用户列表查看（取决于搜索条件）)
     * @ApiMethod(GET)
     * @ApiParams(name = "keywords", type = "string",required=false,description = "搜索关键字")
     * @ApiParams(name = "page", type = "string",required=true,description = "页数")
     * @ApiParams(name = "limit", type = "string",required=true,description = "条数")
     * @ApiParams(name = "shop_id", type = "string",required=false,description = "查询的机构店铺id（只查已授权的）")
     * @ApiParams(name = "nickname", type = "string",required=false,description = "昵称")
     * @ApiParams(name = "realname", type = "string",required=false,description = "真实姓名")
     * @ApiParams(name = "mobile", type = "string",required=false,description = "手机号")
     * @ApiParams(name = "has_order_user", type = "string",required=false,description = "是否只查下单用户")
     * @ApiParams(name = "classes_activity_id", type = "string",required=false,description = "查询的课程活动id")
     * @ApiParams(name = "classes_lib_id", type = "string",required=false,description = "查询的课程id")
     * @ApiReturn({
     *
     *})
     */
    public function user_list()
    {
        $user_id = 0;
        $user = $this->auth->getUser();//登录用户
        if($user)$user_id = $user['id'];
        $params=[];
        $page      =  $this->request->get('page/d', 1); //页数
        $limit   =  $this->request->get('limit/d', 10); //条数
        $params['keywords']  =  $this->request->get('keywords/s', ''); //搜索关键字
        $params['status']  =  $this->request->get('status/s', ''); //搜索关键字
        $shop_id  =  $this->request->get('shop_id/d', ''); //搜索关键字
        if(!$shop_id) $shop_id = $user['shop_id'];
        $has_order_user  =  $this->request->get('has_order_user/d', ''); //搜索关键字

        $params['nickname']  =  $this->request->get('nickname/s', '');
        if($params['nickname']) $params['nickname'] = ["LIKE", "%".$params['nickname'] ."%" ];
        $params['realname']  =  $this->request->get('realname/s', '');
        if($params['realname']) $params['realname'] = ["LIKE", "%".$params['realname'] ."%" ];
        $params['mobile']  =  $this->request->get('mobile/s', '');
        if($params['mobile']) $params['mobile'] = ["LIKE", "%".$params['mobile'] ."%" ];

        $params['classes_activity_id']  =  $this->request->get('classes_activity_id/s', ''); //搜索关键字
        $params['classes_lib_id']  =  $this->request->get('classes_lib_id/s', ''); //搜索关键字
//        $type =  $this->request->get('type/s', ''); //筛选学员和教练单

        try{
            //当前申请状态
            $res =  \app\common\model\User::getShopUserList($page, $limit,$params,$shop_id,$has_order_user);
//            if($user_id =='670153'){
//               file_put_contents("ceshi66.txt",(new AppointmentOrder())->getLastSql());
//            }
        }catch (\Exception $e){

            $this->apierror($e->getMessage());
        }
        $this->apisuccess('查询成功', $res);
    }




}
