IndexController.php 12.5 KB
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use app\admin\model\HospitalModel;
use app\portal\model\OrderModel;
use app\user\model\UserModel;
use cmf\controller\HomeBaseController;
use think\Db;
use EasyWeChat\Foundation\Application;
use think\Log;
use think\Request;



class IndexController extends HomeBaseController
{

    protected $UserModel;

    public function __construct(UserModel $UserModel)
    {
        parent::__construct();
        $this->UserModel = $UserModel;
    }


    public function callback(){
        $appId=config('wechat_config.app_id');
        $secret=config('wechat_config.secret');
        $config = [
            'app_id'  => $appId,
            'secret'  => $secret,
        ];

        $app = new Application($config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        $wechat_user = $user->toArray();
        if(isset($wechat_user['id'])){
            $openid=$wechat_user['id'];
            $findThirdPartyUser = Db::name("third_party_user")
                ->where('openid', $openid)
                ->where('app_id', $appId)
                ->find();
            if ($findThirdPartyUser) {
                $this->wechatUserLogin($findThirdPartyUser,$openid,$appId);
            }else{
                $this->wechatUserRegister($wechat_user,$openid,$appId);
            }
            $target_url=session('target_url');
            $targetUrl = empty($target_url) ? '/' : $target_url;
            header('location:'. $targetUrl);
        }else{
            Log::write('获取微信用户数据失败');
            $this->error('获取微信用户数据失败');
        }

    }

    /**
     * 微信用户登录
     * @param $findThirdPartyUser
     * @param $openid
     * @param $appId
     */
    protected function wechatUserLogin($findThirdPartyUser,$openid,$appId){
        $currentTime = time();
        $ip          = $this->request->ip(0, true);
        $token = cmf_generate_user_token($findThirdPartyUser['user_id'], 'public');
        $userData = [
            'last_login_ip'   => $ip,
            'last_login_time' => $currentTime,
            'login_times'     => ['exp', 'login_times+1']
        ];
        $row1=Db::name("third_party_user")
            ->where('openid', $openid)
            ->where('app_id', $appId)
            ->update($userData);
        $userInfo=Db::name("third_party_user")
            ->where('openid', $openid)
            ->where('app_id', $appId)->find();
        unset($userData['login_times']);
        $row2=Db::name("user")
            ->where('id', $userInfo['user_id'])
            ->update($userData);
        if($row1!==false&&$row2!==false){
            $userModel=new UserModel();
            $user=$userModel->getUserInfo(['user_id'=>$userInfo['user_id'],'app_id'=>$appId]);
            cmf_update_current_user($user);
            session('token',$token);
            Db::commit();
        }else{
            Db::rollback();
        }
    }

    /**
     * 微信用户注册
     * @param $wechat_user
     * @param $openid
     * @param $appId
     */
    protected function wechatUserRegister($wechat_user,$openid,$appId){
        $currentTime = time();
        $ip          = $this->request->ip(0, true);
        Db::startTrans();
        $userId = Db::name("user")->insertGetId([
            'create_time'     => $currentTime,
            'user_status'     => 1,
            'user_type'       => 2,
            'sex'             => $wechat_user['original']['sex'],
            'user_nickname'   => $wechat_user['nickname'],
            'avatar'          => $wechat_user['avatar'],
            'last_login_ip'   => $ip,
            'last_login_time' => $currentTime,
        ]);

        $row=Db::name("third_party_user")->insert([
            'openid'          => $openid,
            'user_id'         => $userId,
            'third_party'     => 'public',
            'nickname'        => $wechat_user['nickname'],
            'app_id'          => $appId,
            'last_login_ip'   => $ip,
            'union_id'        => '',
            'last_login_time' => $currentTime,
            'create_time'     => $currentTime,
            'login_times'     => 1,
            'status'          => 1,
            'more'            => json_encode($wechat_user)
        ]);
        if($userId && $row){
            $token = cmf_generate_user_token($userId, 'public');
            $userModel=new UserModel();
            $user=$userModel->getUserInfo(['user_id'=>$userId,'app_id'=>$appId]);
            cmf_update_current_user($user);
            session('token',$token);
            Db::commit();
        }else{
            Db::rollback();
        }
    }

    /**
     * 前台用户首页(公开)
     */
    public function index_bak()
    {
        $id   = $this->request->param("id", 0, "intval");
        $userQuery = Db::name("User");
        $user = $userQuery->where('id',$id)->find();
        if (empty($user)) {
            session('user',null);
            $this->error("查无此人!");
        }
        $this->assign($user);
        return $this->fetch(":index");

    }

    /**
     * 个人首页
     * @return mixed
     */
    public function index(){
        $user=$this->UserModel->getMyself()->toArray();
        $message=$this->UserModel->userMessage()->toArray();
        $message_count=count($message);
        $this->assign('user',$user);
        $this->assign('message_count',$message_count);
       return $this->fetch();
    }

    /**
     * 打卡页面
     * @return mixed
     */
    public function signIn(){
        $map['user_id']=cmf_get_current_user_id();
        $map['month']=date('m',time());
        $map['year']=date('Y',time());
        $sign_info=\db('sign_in')->field('month,day')->where($map)->select()->toArray();
        $this->assign('sign_info',$sign_info);
        return $this->fetch();
    }

    /**
     * 打卡操作
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function doSignIn(){
        $data['user_id']=cmf_get_current_user_id();
        $data['month']=date('m',time());
        $data['year']=date('Y',time());
        $data['day']=date('d',time());
        $isin=\db('sign_in')->where($data)->find();
        if ($isin){
            $this->error('今日已打卡!');
        }
        $data['add_time']=time();
        $result=db('sign_in')->insert($data);
        if ($result){
            $this->success();
        }else{
            $this->error();
        }
    }
    /**
     * 前台ajax 判断用户登录状态接口
     */
    function isLogin()
    {
        if (cmf_is_user_login()) {
            $this->success("用户已登录",null,['user'=>cmf_get_current_user()]);
        } else {
            $this->error("此用户未登录!");
        }
    }

    /**
     * 退出登录
    */
    public function logout()
    {
        session("user", null);//只有前台用户退出
        return redirect($this->request->root() . "/");
    }



    public function myScore(){

        return $this->fetch();
    }

    public function myScoreInInfo(){
       return $this->fetch();
    }

    public function myScoreOutInfo(){
        return $this->fetch();
    }

    public function myData(){
        $id=cmf_get_current_user_id();
        $user=$this->UserModel->getUser($id)->toArray()[0];
        $user1=$this->UserModel->getMyself()->toArray();
        $user=array_merge($user1,$user);

        $this->assign('user',$user);
        return $this->fetch();
    }

    public function myOrder(){
        $Order=new  OrderModel();
        $user_id=cmf_get_current_user_id();
        $order=$Order->getOrderByType($user_id)->toArray();
        $order2=$Order->getOrderByType($user_id,2)->toArray();
        $order3=$Order->getOrderByType($user_id,3)->toArray();
        $this->assign('order',$order);
        $this->assign('order2',$order2);
        $this->assign('order3',$order3);
        return $this->fetch();
    }

    public function myAdress(){
        return $this->fetch();
    }

    public function myFriends(){
        return $this->fetch();
    }

    public function kefu(){
        return $this->fetch();
    }


    public function editInfo(){
        $map['id']=cmf_get_current_user_id();
        $avatar=input('avatar');
        if(!empty($avatar)){
            $data['avatar']=input('avatar');
        }
        $data['user_login']=input('name');
        $data['mobile']=input('mobile');
        $result=$this->UserModel->where($map)->update($data);
        if ($result==1){
                $this->success();
        }else{
                $this->error();
        }
    }

    public function uploadavatar(){
        header("content-type:text/html;charset=utf-8");
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $_FILES["image"]["name"]);
        $extension = end($temp);
        if ((($_FILES["image"]["type"] == "image/gif")
                || ($_FILES["image"]["type"] == "image/jpeg")
                || ($_FILES["image"]["type"] == "image/jpg")
                || ($_FILES["image"]["type"] == "image/pjpeg")
                || ($_FILES["image"]["type"] == "image/x-png")
                || ($_FILES["image"]["type"] == "image/png"))
            && ($_FILES["image"]["size"] < 2048000)
            && in_array($extension, $allowedExts)) {
            if ($_FILES["image"]["error"] > 0) {
                $list['ok'] = 0;
                $list['error'] = "上传错误";
//     echo json_encode($list);
            } else {
                if ($_FILES["image"]["type"] == "image/gif") {
                    $img = date('Ymdgi-s') . '.gif';
                } else if ($_FILES["image"]["type"] == "image/jpeg" || $_FILES["image"]["type"] == "image/jpg" || $_FILES["image"]["type"] == "image/pjpeg") {
                    $img = date('Ymdgi-s') . '.jpg';
                } else {
                    $img = date('Ymdgi-s') . '.png';
                }
                $path = ROOT_PATH . 'public' . DS . 'static' . DS . 'avatar/' . $img;
                move_uploaded_file($_FILES["image"]["tmp_name"], $path);
                $request = Request::instance();
                $domain = $request->domain();
                $url = $domain . "/static/avatar/" . $img;
                $image = \think\Image::open($path);
                $image->thumb(300, 300, \think\Image::THUMB_CENTER)->save($path);
                $msg['url'] = $url;
                $data['avatar']=$url;
                $result=$this->UserModel->where('id',cmf_get_current_user_id())->Update($data);
                if ($result==1){
                    $this->success('上传成功!');
                }else{
                    $this->error('上传失败!');
                }

            }
        } else {
            $list['ok'] = 2;
            $list['error'] = "无效的图像";
            $this->error('无效的图像');
        }

    }

    public function orderInfo(){
        $order_id=input('id');
        $Order=new OrderModel();
        $order=$Order->getOrderById($order_id)->toArray();
        $this->assign('order',$order);
        return $this->fetch();
    }


    public function inquiry(){
        $Hospital= new HospitalModel();
        $config=config('wechat_config');
        $Wechat=new Application($config);
        $js = $Wechat->js;
        $config=$js->config(array('onMenuShareQQ', 'onMenuShareWeibo'), true);
        dump($config);
        $platment=$Hospital->getPaltform()->toArray();
        $hospital=$Hospital->getHospital()->toArray();
        $this->assign('hospital',$hospital);
        $this->assign('platment',$platment);
        return $this->fetch();
    }

    /**
     * 通过平台获取专家
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getExportByPlatment(){
        $platment_id=input('platment_id');
        $Hospital= new HospitalModel();
        $User=new UserModel();
        $export=$User->getExpertByPlatment($platment_id)->toArray();
        $this->success('','',$export);
    }

}