<?php
/**
 * @Statement: [ An Ordinary Person ]
 * @Author: 闻子 < QQ：270988107 >
 * @Copyright: 闻子 2016-2019 All rights reserved.
 *
 *    .--,       .--,
 *   ( (  \.---./  ) )
 *    '.__/o   o\__.'
 *       {=  ^  =}
 *        >  -  <
 *       /       \
 *      //       \\
 *     //|   .   |\\
 *     "'\       /'"_.-~^`'-.
 *        \  _  /--'         `
 *      ___)( )(___
 *     (((__) (__)))    高山仰止,景行行止.虽不能至,心向往之.
 *
 */

namespace app\index\controller;

use Env;

use Db;

use Request;

use app\common\logic\User as LogicUser;

use app\common\logic\Scode as LogicScode;

use app\common\controller\Base as BaseController;

class Member extends BaseController
{
	/**
	 * 继承基类
	 * @Author: 闻子 < QQ：270988107 >
	 */
    use Basedata;

	/**
	 * 定义逻辑
	 * @Author: 闻子 < QQ：270988107 >
	 */
	private static $UserLogic = null;
	private static $ScodeLogic = null;

    /**
     * 实例化逻辑
     * @Author: 闻子 < QQ：270988107 >
     */
    public function __construct()
    {
        parent::__construct();
        self::$UserLogic = get_sington_object('LogicUser', LogicUser::class);
        self::$ScodeLogic = get_sington_object('LogicScode', LogicScode::class);
    }

	/**
	 * session检测
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function getSession()
    {
		$AdminExistence = session('admin.id');
		if (!$AdminExistence) {
			return $this->error('登录超时，请重新登录','index/member/login');
		}
    }
    
	/**
	 * 会员中心
	 * @Author: 闻子 < QQ：270988107 >
	 */
	public function index()
	{
		$this->getSession();
        $data = Db::name('notice')->order('time desc')->limit(5)->select();
		return view('',compact('data'));
	}

	/**
	 * 会员登录
	 * @Author: 闻子 < QQ：270988107 >
	 */
	public function login()
	{
		$AdminExistence = session('admin.id');
		if ($AdminExistence) {
			$this->redirect('/member/index');
		}
		$this->request->isPost() && $this->jump(self::$UserLogic->logindetection(input('post.')));
		return view();
	}

	/**
	 * 会员注册
	 * @Author: 闻子 < QQ：270988107 >
	 */
	public function register()
	{
		$AdminExistence = session('admin.id');
		if ($AdminExistence) {
			$this->redirect('/member/index');
		}
		$this->request->isPost() && $this->jump(self::$UserLogic->regUserRes(input('post.')));
		return view();
	}

	/**
	 * 短信接口
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function send()
    {
        $phone = input('tel');
        if (empty($phone)){
            return json(['status' => 0, 'msg' => '请输入手机号码']);
        }
        header('content-type:text/html;charset=utf-8');
        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        $code = rand(0001,9999);//验证码生成格式，请生成4-8位，数字或字母随机组合
        $smsConf = array(
            "key"       => "f999e8334322fcdfd7ec54d9f92f0fa6", //您申请的APPKEY
            "mobile"    => $phone, //接受短信的用户手机号码
            "tpl_id"    => "99393", //您申请的短信模板ID，根据实际情况修改
            "tpl_value" => "#code#=".$code."&#company#=聚合数据"//您设置的模板变量，根据实际情况修改
        );
        set_time_limit(0);
        $content = getcurl($sendUrl,$smsConf,1); //请求发送短信
        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
            	cookie('tel', $phone, 600);
            	cookie('checkcode', $code, 600);
                return json(['status' => 1, 'msg' => '短信发送成功，十分钟内有效']);
            }else{
                $msg = $result['reason'];
            	cookie('tel', null);
            	cookie('checkcode', null);
                if ($error_code == 205401) {
                	return json(['status' => 1, 'msg' => '请输入正确的手机号码']);
                }else{
                	return json(['status' => 1, 'msg' => $msg]);
                }
            }
        }else{
            return json(['status' => 1, 'msg' => '请求发送短信失败']);
        }
    }

	/**
	 * 用户资料
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function account()
    {
    	$this->getSession();
    	return view();
    }

	/**
	 * 修改密码
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function password()
    {
    	$this->getSession();
    	$this->request->isPost() && $this->jump(self::$UserLogic->changePassword(input('post.')));
    	return view();
    }

	/**
	 * 上传头像
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function avatar()
    {
    	$this->getSession();
    	$this->request->isPost() && $this->jump(self::$UserLogic->changePassword(input('post.')));
    	return view();
    }

	/**
	 * 会员升级
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function upgrade()
    {
    	$this->getSession();
    	if (!empty(input('id'))) {
    		$up = Db::name('upgrade')->where('id',input('id'))->find();
    		$user = Db::name('user')->where('id',session('admin.id'))->find();
            $upgradeinfo = Db::name('upgrade')->where('id',$user['auth_id'])->find();
    		$moneyres = $user['money']-$up['cost'];
    		if ($moneyres < 0) {
    			$msgico = '<div class="number font-red" style="top: 20px;"> <i class="layui-icon layui-icon-close-fill"></i></div>';
    			$res = "金额不足，本次需要 ".$up['cost']." 金额，当前金额为 ".$user['money']." 元";
    		}else{
    			if ($user['enddateline'] == "0000-00-00 00:00:00") {
    				$myc = userTime($up['duration']);
    			}else{
    				$myc = userXfTime($up['duration'],$user['enddateline']);
    			}
    			Db::name('user')->where('id',session('admin.id'))->update(['money' => $moneyres, 'auth_id' => $up['id'],'enddateline' => $myc]);
    			$msgico = '<div class="number font-green" style="top: 20px;"> <i class="layui-icon layui-icon-ok-circle"></i></div>';
    			if ($user['enddateline'] == "0000-00-00 00:00:00") {
                    if ($user['auth_id'] != 0) {
                        if ($upgradeinfo['song']) {
                            $data = Db::name('user')->where('id',session('admin.id'))->setInc('integral',$upgradeinfo['song']);
                        }
                    }
    				$res = "开通成功";
    				$msg = "您的会员组等级升级成功";
    				$time = date('Y-m-d H:i:s');
    				Db::name('notice')->insert(['user' => $user['tel'], 'msg' => $msg, 'time' => $time]);
    				$this->assign("res",$res);
    			}else{
                    if ($user['auth_id'] != 0) {
                        if ($upgradeinfo['song']) {
                            $data = Db::name('user')->where('id',session('admin.id'))->setInc('integral',$upgradeinfo['song']);
                        }
                    }
    				$res = "续费成功";
    				$msg = "您的会员时间续费成功";
    				$time = date('Y-m-d H:i:s');
    				Db::name('notice')->insert(['user' => $user['tel'], 'msg' => $msg, 'time' => $time]);
    				$this->assign("res",$res);
    			}
    			$this->assign("msgico",$msgico);
    		}
    	}
    	$data = Db::name('upgrade')->order('id asc')->select();
    	return view('',compact('data'));
    }

	/**
	 * 在线充值积分
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function pay_integral()
    {
    	$this->getSession();
    	return view();
    }

	/**
	 * 在线充值金额
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function pay_money()
    {
    	$this->getSession();
    	return view();
    }

    /**
     * 充值异常跳转
     * @Author: 闻子 < QQ：270988107 >
     */
    public function pay_sub()
    {
        $type = input('type');
        if (!$type) {
            $icon = '<i class="fa fa-times-circle-o"></i>';
            $msg = '参数异常';
        }
        if ($type == "Success") {
            $icon = '<i class="fa fa-check-circle-o"></i>';
            $msg = '充值成功';
        }
        if ($type == "Error") {
            $icon = '<i class="fa fa-times-circle-o"></i>';
            $msg = '充值失败';
        }
        return view('',compact('icon','msg'));
    }

	/**
	 * 通知提醒
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function notice()
    {
    	$this->getSession();
    	$data = Db::name('notice')->order('time','desc')->select();
    	return view('',compact('data'));
    }

	/**
	 * 投稿列表
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function contribute()
    {
        $this->getSession();
    	$id = input('id');
    	if (!empty(input('id'))) {
    		$title = Db::name('menu')->where('id',$id)->find();
            $data = Db::name('scode')->alias('a')->join('menu w','a.mid = w.id')->where('a.mid',$id)->where('a.uid',session('admin.id'))->where('a.examine',1)->field('a.id,a.title,a.create_time,w.name')->select();
    	}
    	return view('',compact('title','data'));
    }

	/**
	 * 发布投稿
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function contribute_add()
    {
        $this->getSession();
    	$id = input('id');
    	if (!empty(input('id'))) {
    		$title = Db::name('menu')->where('id',$id)->find();
    		$data = Db::name('column')->where('pid',$title['id'])->order('sort asc')->select();
    	}
    	$this->request->isPost() && $this->jump(self::$ScodeLogic->formdata(input('post.')));
    	return view('',compact('title','data'));
    }

    /**
     * 待投稿
     * @Author: 闻子 < QQ：270988107 >
     */
    public function examine()
    {
        $this->getSession();
        $id = input('id');
        if (!empty(input('id'))) {
            $title = Db::name('menu')->where('id',$id)->find();
            $data = Db::name('scode')->where('mid',$id)->where('uid',session('admin.id'))->where('examine',0)->select();
        }
        return view('',compact('title','data'));
    }

    /**
     * 我的购买
     * @Author: 闻子 < QQ：270988107 >
     */
    public function buy()
    {
        $this->getSession();
        $data = Db::name('purchase')->where('uid',session('admin.id'))->select();
        return view('',compact('data'));
    }

    /**
     * 我的收藏
     * @Author: 闻子 < QQ：270988107 >
     */
    public function favorite()
    {
        $this->getSession();
        $data = Db::name('collect')->alias('a')->join('scode w','a.codeid = w.id')->where('a.uid',session('admin.id'))->field('a.*,w.title')->select();
        return view('',compact('data'));
    }

    /**
     * 我的评论
     * @Author: 闻子 < QQ：270988107 >
     */
    public function comment()
    {
        $this->getSession();
        $data = Db::name('comment')->where('uid',session('admin.id'))->field('*,count(codeid) count')->select();
        return view('',compact('data'));
    }

    /**
     * 财务记录
     * @Author: 闻子 < QQ：270988107 >
     */
    public function pay_list()
    {
        $this->getSession();
        $data = Db::name('pay')->where('uid',session('admin.id'))->where('type',input('type'))->select();
        return view('',compact('data'));
    }

    /**
     * 每日签到
     * @Author: 闻子 < QQ：270988107 >
     */
    public function qiandao()
    {
        $this->getSession();
        $first = strtotime(date("Y-m-01 00:00:00"));
        $first = date("w", $first);
        $maxDay = date('t', strtotime("" . date("Y") . "-" . date("m") . ""));
        for ($j = 0; $j < $first; $j++) {
            $blankArr[] = $j;
        }
        for ($i = 0; $i < $maxDay; $i++) {
            $z = $first + $i;
            $days[] = array("key" => $i, "key2" => $z % 7);
        }
        $this->assign("days", $days);
        $this->assign("first", $first);
        $this->assign("blankArr", $blankArr);
        $other = array();
        $total = $first + count($days);
        for ($x = 0; $x < ceil($maxDay / 7) * 7 - $total; $x++) {
            $other[] = $x;
        }
        $this->assign("other", $other);
        return $this->fetch();
    }

    /**
     * 签到处理
     * @Author: 闻子 < QQ：270988107 >
     */
    public function signDay()
    {
        if (!session("admin.id")) {
            echo -1;
            exit;
        }
        $data['addtime'] = strtotime(date("Y-m-d 00:00:00"));
        $data['uid'] = session("admin.id");
        $data['status'] = 0;
        $info = model("sign")->field("id")->where($data)->find();
        if (empty($info)) {
            $data['money'] = 1;
            $lastid = model('sign')->save($data);
            Db::table('user')->where('id', session("admin.id"))->setInc('integral', $data['money']);
            if ($lastid > 0) {
                echo $data['money'];
            }
        } else {
            echo -1;
        }
    }

    /**
     * 上传头像
     * @Author: 闻子 < QQ：270988107 >
     */
    public function upload()
    {
    	$this->getSession();
        $file = request()->file('file');
        $info = $file->move(Env::get('root_path') . 'public/static/avatar');
        if ($info) {
            $res['code'] = 1;
            $res['msg'] = '上传成功';
            $res['name'] = $info->getFilename();
            $NamePath = str_replace('\\', "/", $info->getSaveName());
            $res['filepath'] = '/public/static/avatar/' . $NamePath;
            Db::name('user')->where('id', session('admin.id'))->update(['avatar' => $res['filepath']]);
        } else {
            $res['code'] = 0;
            $res['msg'] = '上传失败' . $file->getError();
        }
        return $res;

    }

	/**
	 * 退出登录
	 * @Author: 闻子 < QQ：270988107 >
	 */
	public function logout()
	{
		$this->getSession();
		session(null);
		return json(['msg'=>'退出成功','backurl'=>'/']);
	}

}