<?php
namespace Api\Controller;
use Think\Controller;
use User\Api\MemberApi;
/**
 * 用户操作接口
 *
 */

class UserController extends Controller{

    private $allow_ip;

    public function __construct(){

        /* 读取站点配置 */
        $config = api('Config/lists');
        C($config); //添加配置

        $this->allow_ip= C('API_ALLOW_IP'); //ip白名单,多个ip用逗号分隔,留空为允许所有ip

        //验证请求ip是否通过白名单
        $client_ip = get_client_ip();
        if(!empty($this->allow_ip)){
            $allow_ip_arr = explode(',',$this->allow_ip);
            if(!in_array($client_ip,$allow_ip_arr)){
                $data = ['msg'=>'ip白名单未通过','status'=>'-1','data'=>''];
                $this->ajaxReturn($data);
            }
        }

    }


    /**
     * 检查用户名是否存在
     * @param string $account   用户名
     * @return  string
     */
    public function checkUserName(){

        $account = I('account','');

        if(empty($account)){
            $data = ['msg'=>'用户名不能为空','status'=>0,'data'=>''];
            $this->ajaxReturn($data);
        }

        $where['account'] = $account;
        $where['phone'] = $account;
        $where['_logic'] = 'or';
        $map['_complex'] = $where;

        $res = M('user','tab_')->field('id')->where($map)->find();
        if(!empty($res)){
            //用户名已存在,不可用
            $data = ['msg'=>'用户名已存在','status'=>0,'data'=>''];
            $this->ajaxReturn($data);
        }else{
            //用户名不存在,可以注册
            $data = ['msg'=>'用户名可用','status'=>1,'data'=>''];
            $this->ajaxReturn($data);
        }
    }




    /**
     * 修改用户密码接口
     * @param string $account   用户名
     * @param string $oldpsw    旧密码
     * @param string $newpsw    新密码
     * @return  string
     */
    public function editPassword(){

        $account = I('account','');
        $oldpsw = I('oldpsw','');
        $newpsw = I('newpsw','');
        $type = I('type','');

        $member = new MemberApi();
        $user_info = M('user','tab_')->where(['account'=>$account])->find();
        if(empty($user_info)){
            $this->ajaxReturn(array('status'=>0,'msg'=>'账号不存在'));exit;
        }

        $flag = $member->checkPassword($account,$oldpsw);
        if(!$flag && $type==''){
            $this->ajaxReturn(array('status'=>0,'msg'=>'原密码错误'));exit;
        }
        $msg=$this->pwd($user_info['id'],$newpsw);
        $this->ajaxReturn($msg);exit;

    }


    // 修改密码
    private function pwd($uid,$password) {
        $member = new MemberApi();
        $result = $member->updatePassword($uid,$password);
        if ($result!==false) {
            $data['status']=1;
            $data['msg']='密码修改成功';
        } else {
            $data['status']=0;
            $data['msg']='密码修改失败';
        }
        return $data;
    }




}