<?php

namespace app\api\controller\doctor;

use app\common\controller\Apic;
use app\common\library\Sms;
use think\Exception;
use think\Validate;

use think\Db;
use app\common\library\Wechat;

/**
 * 会员接口
 */
class User extends Apic
{
    protected $noNeedLogin = ['mobilelogin','wechatlogin','bindmobile'];
    protected $noNeedRight = '*';

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = input('mobile');
        $captcha = input('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 = \app\common\model\Doctor::getByMobile($mobile);
        if ($user) {
            if ($user->status == -1) {
                $this->error('账号已注销');
            }
            if ($user->status != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register('', '', '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $this->success(__('Logged in successful'), $this->auth->getUserinfo_simple());
        } else {
            $this->error($this->auth->getError());
        }
    }

    //微信登录,预先假注册
    public function wechatlogin(){
        $code = input('code','');
        if(!$code){
            $this->error();
        }
        //微信
        $wechat = new Wechat();
        $wxuserinfo = $wechat->getAccessToken($code);

        if(!$wxuserinfo){
            $this->error('openid获取失败');
        }
        if(!is_array($wxuserinfo) || !isset($wxuserinfo['openid'])){
            $this->error('openid获取失败');
        }

        $openid = $wxuserinfo['openid'];

        //检查用户
        $user = Db::name('doctor')->where('wechat_openid',$openid)->find();
        if ($user) {
            if ($user['status'] == -1) {
                $this->error('账户已注销');
            }
            if ($user['status'] != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user['id']);

            if ($ret) {
                $userInfo = $this->auth->getUserinfo_simple();
                $userInfo['is_register'] = 0;
                $userInfo['code'] = $code;
                $this->success(__('Logged in successful'), $userInfo);
            } else {
                $this->error($this->auth->getError());
            }

        } else {
            //记录code和openid，绑定手机号的时候更新openid
            $wechatCodeData = [
                'code' => $code,
                'openid' => $openid,
                'createtime' => time(),
            ];
            $wechatCode = Db::name('wechat_code')->where(['openid'=>$openid])->find();
            if (empty($wechatCode)) {
                Db::name('wechat_code')->insertGetId($wechatCodeData);
            } else {
                Db::name('wechat_code')->where(['openid'=>$openid])->update($wechatCodeData);
            }

            //直接返回
            $userInfo = [];
            $userInfo['is_register'] = 1;
            $userInfo['code'] = $code;
            $this->success('获取信息成功', $userInfo);
        }

    }

    /**
     * 微信注册来的，绑定手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function bindmobile()
    {
        $mobile  = input('mobile');
        $captcha = input('captcha');
        $code    = input('code');

        if (!$mobile || !$captcha || !$code) {
            $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'));
        }

        $wechatCodeWhere['code'] = $code;
        $wechatCode = Db::name('wechat_code')->where($wechatCodeWhere)->find();
        if (empty($wechatCode)) {
            $this->error('请先微信登录');
        }

        //检查appid绑定的用户
        $user = Db::name('doctor')->where('wechat_openid',$wechatCode['openid'])->find();
        if ($user) {
            if ($user['status'] == -1) {
                $this->error('账户已注销');
            }
            if ($user['status'] != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user['id']);
            $this->success(__('Logged in successful'), $this->auth->getUserinfo_simple());
        }

        //新的openid用户
        $where = [];
        $where['mobile'] = $mobile;
        $userData = Db::name('doctor')->where($where)->find();//老用户
        if (!empty($userData)) {
            if ($userData['status'] == -1) {
                $this->error('账户已注销');
            }
            if ($userData['status'] != 1) {
                $this->error(__('Account is locked'));
            }

            if (empty($userData['wechat_openid'])) {
                Db::name('doctor')->where('id',$userData['id'])->update(['wechat_openid' => $wechatCode['openid']]);//老用户更新openid
            } else {
                if ($userData['wechat_openid'] != $wechatCode['openid']) {
                    $this->error('该手机号已被其他用户绑定');
                }
            }
            $ret = $this->auth->direct($userData['id']);
        } else {
            $extend = [
                'wechat_openid' => $wechatCode['openid'],
            ];
            $ret = $this->auth->register('', '','', $mobile, $extend);
        }
        if (!$ret) {
            $this->error($this->auth->getError());
        }

        $this->success(__('Logged in successful'), $this->auth->getUserinfo_simple());

    }


    //用户详细资料
    public function userInfo(){
        $info = $this->auth->getUserinfo();

        $this->success(__('success'),$info);
    }




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



    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $captcha     验证码
     * @param string $newpassword 新密码
     */
    /*public function resetpwd()
    {
        $mobile      = $this->request->post('mobile');
        $captcha     = $this->request->post('captcha');
        $newpassword = $this->request->post("newpassword");
        if (!$mobile || !$captcha || !$newpassword) {
            $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 (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\CompanyStaff::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');

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->resetpwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }*/

  
    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $field_array = [
            'realname',
            'idcard',
            'english_status',
            'idcard_z_image',
            'idcard_f_image',
            'doctor_image',

            'avatar','nickname','gender',
            'keshi_id','hospital','goodat','level_id','info','job_status'
        ];

        $data = [];
        foreach($field_array as $key => $field){

            //前端传不了post，改了
            /*if(!request()->has($field,'post')){
                continue;
            }*/
            if(!input('?'.$field)){
                continue;
            }

            $newone = input($field);

            if($field == 'avatar'){
                $newone = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
            }

            $data[$field] = $newone;
        }

        //
        /*if(isset($data['birthday'])){
            $data['birthday'] = strtotime($data['birthday']);
        }*/

        if(empty($data)){
            $this->success();
        }

        if(isset($data['realname']) && isset($data['idcard']) && isset($data['idcard_z_image']) && isset($data['idcard_f_image'])){
            $data['idcard_status'] = 0;
        }
        if(isset($data['doctor_image'])){
            $data['doctor_status'] = 0;
        }

        $update_rs = Db::name('doctor')->where('id',$this->auth->id)->update($data);

        $this->success();
    }
    //问诊设置
    public function profile_wenzhen()
    {
        $field_array = [
            'typing_switch',
            'video_switch',
            'video_model',
            'typing_price',
            'video_price',
            'notice_switch',
            'jolt_switch',
        ];

        $data = [];
        foreach($field_array as $key => $field){

            if(!input('?'.$field)){
                continue;
            }

            $newone = input($field);

            $data[$field] = $newone;
        }
        if(empty($data)){
            $this->success();
        }
        $update_rs = Db::name('doctor_info')->where('doctor_id',$this->auth->id)->update($data);

        $this->success();
    }

    //假注销
    public function cancleUser(){
        /*$captcha = input('captcha','');

        if (!$captcha) {
            $this->error(__('Invalid parameters'));
        }

        if (!Sms::check($this->auth->mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }*/

        Db::name('doctor')->where('id',$this->auth->id)->update(['status'=>-1]);

        $this->auth->logout();
        $this->success('注销成功');
    }

//////////////////////////////////////////////////////


    //员工手机+密码登录
    public function login()
    {
        $mobile = input('mobile');
        $password = input('password');
        if (!$mobile || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($mobile, $password);
        if ($ret) {
            $data = $this->auth->getUserinfo();
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 修改密码
     *
     * @ApiMethod (POST)
     * @param string $newpassword 新密码
     * @param string $oldpassword 旧密码
     */
    public function changepwd(){
        $newpassword = input('newpassword');
        $oldpassword = input('oldpassword','');

        if (!$newpassword) {
            $this->error('请输入新密码');
        }
        if($this->auth->password && empty($oldpassword)){
            $this->error('旧密码必填');
        }

        if(empty($this->auth->password)){
            $ret = $this->auth->changepwd($newpassword, '', true);
        }else{
            $ret = $this->auth->changepwd($newpassword,$oldpassword,false);
        }

        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
