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

use think\Db;

use Env;

use think\captcha\Captcha;

use app\common\logic\Scode as LogicScode;

use app\common\controller\Base as BaseController;

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

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

    /**
     * 实例化逻辑
     * @Author: 闻子 < QQ：270988107 >
     */
    public function __construct()
    {
        parent::__construct();
        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()
    {
    	$id = input('id');
    	if (empty($id)) {
    		$this->error('参数异常');
    	}
    	$data = self::$ScodeLogic->getScodeInfo(['id'=>$id]);
    	if (!$data) {
    		$this->error('参数异常');
    	}
    	$value = $data['catid'];
    	$userres = Db::name('user')->where('id',$data['uid'])->find();
		$ass = Db::name('assortment')->alias('a')->join('column b','a.pid= b.id')->field('a.id,a.name,b.name as title')->whereIn('a.id',$data['catid'])->orderRaw("field(a.id,$value)")->select();
		$commentdata = Db::name('comment')->alias('a')->join('user b','a.uid = b.id')->field('a.id,a.user,a.content,a.time,b.auth_id,b.avatar')->where('a.codeid',$id)->where('a.juge',1)->select();
		$collectinfo = Db::name('collect')->where('uid',session('admin.id'))->where('codeid',$id)->find();
		$upgradeinfo = Db::name('upgrade')->select();
        $taginfo = Db::name('tag')->where('cid',$data['mid'])->select();
		foreach ($commentdata as $key => $value) {
			foreach ($upgradeinfo as $k => $v) {
				if ($value['auth_id'] == $v['id']) {
					$commentdata[$key]['title'] = $v['title'];
					$commentdata[$key]['icon'] = $v['icon'];
				}else{
                    $commentdata[$key]['title'] = "";
					$commentdata[$key]['icon'] = "";
				}
			}
		}
    	return view('',compact('data','ass','userres','commentdata','collectinfo','taginfo'));
    }

    /**
     * 源码下载
     * @Author: 闻子 < QQ：270988107 >
     */
    public function download()
    {
    	$this->getSession();
    	$id = input('id');
    	if (empty($id)) {
    		$this->error('参数异常');
    	}
    	$scodeinfo = Db::name('scode')->where('id',$id)->find();
    	$UserRes = Db::name('user')->where('id',session('admin.id'))->find();
    	$upgradeinfo = Db::name('upgrade')->where('id',$UserRes['auth_id'])->find();
    	$buyinfo = Db::name('purchase')->where('uid',session('admin.id'))->where('codeid',$id)->find();
        $configinfo = Db::name('config')->where('id',1)->find();
        if ($buyinfo) {
            $this->down_file(Env::get('root_path') .$scodeinfo['url']);
            exit;
        }
    	if ($scodeinfo['type'] == 1) {
    		if ($upgradeinfo['station'] == 0) {
	    		$moneyres = $UserRes['integral']-$scodeinfo['price'];
		    	if ($moneyres < 0) {
		    		$this->error('积分不足');
		    	}else{
					$this->down_file(Env::get('root_path') .$scodeinfo['url']);
                    $me = $scodeinfo['price'] * $configinfo['procedures'] /100;
                    Db::name('user')->where('id',$scodeinfo['uid'])->setInc('integral',$me);
					Db::name('user')->where('id',session('admin.id'))->update(['integral' => $moneyres]);
					Db::name('down')->insert(['uid' => session('admin.id'),'user' => session('admin.tel'),'codeid' => $id,'title' => $scodeinfo['title'],'time' => date('Y-m-d H:i:s')]);
					Db::name('purchase')->insert(['uid' => session('admin.id'),'user' => session('admin.tel'),'codeid' => $id,'title' => $scodeinfo['title'],'price' => $scodeinfo['price'],'time' => date('Y-m-d H:i:s')]);
                    Db::name('scode')->where('id',$id)->setInc('down',1);
		    	}
    		}else{
				$this->down_file(Env::get('root_path') .$scodeinfo['url']);
                $me = $scodeinfo['price'] * $configinfo['procedures'] /100;
                Db::name('scode')->where('id',$id)->setInc('down',1);
                Db::name('user')->where('id',$scodeinfo['uid'])->setInc('integral',$me);
				Db::name('down')->insert(['uid' => session('admin.id'),'user' => session('admin.tel'),'codeid' => $id,'title' => $scodeinfo['title'],'time' => date('Y-m-d H:i:s')]);
				Db::name('purchase')->insert(['uid' => session('admin.id'),'user' => session('admin.tel'),'codeid' => $id,'title' => $scodeinfo['title'],'price' => 0,'time' => date('Y-m-d H:i:s')]);
    		}
    	}
    	if ($scodeinfo['type'] == 2) {
            $me = $scodeinfo['price'] * $configinfo['procedures'] /100;
            if ($UserRes['auth_id'] > 1) {
                $zk = '0.'.$upgradeinfo['discount'];
                $jszk = $scodeinfo['price'] * $zk;
                $moneyres = $UserRes['money'] - $jszk;
            }else{
                $moneyres = $UserRes['money'] - $scodeinfo['price'];
            }
    		if ($upgradeinfo['rmb'] == 0) {
		    	if ($moneyres < 0) {
		    		$this->error('金额不足');
		    	}else{
					$this->down_file(Env::get('root_path') .$scodeinfo['url']);
                    Db::name('scode')->where('id',$id)->setInc('down',1);
                    Db::name('user')->where('id',$scodeinfo['uid'])->setInc('money',$me);
					Db::name('user')->where('id',session('admin.id'))->update(['money' => $moneyres]);
					Db::name('down')->insert(['uid' => session('admin.id'),'user' => session('admin.tel'),'codeid' => $id,'title' => $scodeinfo['title'],'time' => date('Y-m-d H:i:s')]);
					Db::name('purchase')->insert(['uid' => session('admin.id'),'user' => session('admin.tel'),'codeid' => $id,'title' => $scodeinfo['title'],'price' => $scodeinfo['price'],'time' => date('Y-m-d H:i:s')]);
		    	}
		    }else{
                $this->down_file(Env::get('root_path') .$scodeinfo['url']);
                Db::name('scode')->where('id',$id)->setInc('down',1);
				Db::name('down')->insert(['uid' => session('admin.id'),'user' => session('admin.tel'),'codeid' => $id,'title' => $scodeinfo['title'],'time' => date('Y-m-d H:i:s')]);
				Db::name('purchase')->insert(['uid' => session('admin.id'),'user' => session('admin.tel'),'codeid' => $id,'title' => $scodeinfo['title'],'price' => 0,'time' => date('Y-m-d H:i:s')]);
		    }
    	}
    }

	/**
	 * 收藏源码
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function favorite()
    {
    	if (!session('admin.id')) {
    		return json(1);
    	}
    	if (input('codeid')) {
    		$info = Db::name('scode')->where('id',input('codeid'))->find();
    		if (!$info) {
    			return json(2);
    		}
    	}else{
    		return json(0);
    	}
    	if (input('is_delete') == 1) {
    		$collectinfo = Db::name('collect')->where('uid',session('admin.id'))->where('codeid',input('codeid'))->find();
    		if ($collectinfo) {
                Db::name('user')->where('id', session('admin.id'))->setInc('collection');
    			Db::table('collect')->where('uid',session('admin.id'))->where('codeid',input('codeid'))->delete();
    			return json(3);
    		}else{
                Db::name('user')->where('id', session('admin.id'))->setDec('collection');
    			Db::table('collect')->insert(['uid' => session('admin.id'), 'user' => session('admin.tel'), 'codeid' => input('codeid'), 'time' => date('Y-m-d H:i:s')]);
    			return json(4);
    		}
    	}
    }

	/**
	 * 评论验证码
	 * @Author: 闻子 < QQ：270988107 >
	 */
	public function verify()
    {
		$config =    [
		    // 验证码字体大小
		    'fontSize'    =>    11,
		    // 验证码位数
		    'length'      =>    4,
		    // 关闭验证码杂点
		    'useNoise'    =>    false,
		    // 关闭画混淆曲线
		    'useCurve'    =>    false,
		];
        $captcha = new Captcha($config);
        return $captcha->entry();    
    }

	/**
	 * 发布评论
	 * @Author: 闻子 < QQ：270988107 >
	 */
    public function comment()
    {
    	if (!input('id')) {
    		return json(['status' => 0, 'code' => '参数异常']);
    	}
    	if (!session('admin.id')) {
    		return json(['status' => 0, 'code' => '您无权限评论']);
    	}
    	if (!input('code')) {
    		return json(['status' => 0, 'code' => '请输入验证码']);
    	}
    	if (!input('content')) {
    		return json(['status' => 0, 'code' => '请输入评论内容']);
    	}
        $captcha = new \think\captcha\Captcha();
        $result = $captcha->check(input('code'));
       	if($result === false){
            return json(['status' => 0, 'code' => '验证码错误']);
        }
    	$scodeinfo = Db::name('scode')->where('id',input('id'))->find();
    	$UserRes = Db::name('user')->where('id',session('admin.id'))->find();
    	if ($UserRes['manager'] == 1) {
    		$data = Db::name('comment')->insert(['uid' => session('admin.id'), 'user' => session('admin.tel'), 'codeid' => input('id'), 'title' => $scodeinfo['title'], 'content' => input('post.content'), 'juge' => 1, 'time' => date('Y-m-d H:i:s')]);
    	}else{
    		$data = Db::name('comment')->insert(['uid' => session('admin.id'), 'user' => session('admin.tel'), 'codeid' => input('id'), 'title' => $scodeinfo['title'], 'content' => input('post.content'), 'juge' => 0, 'time' => date('Y-m-d H:i:s')]);
    	}
		if ($data) {
			return json(['status' => 1, 'code' => '评论成功，需要管理员审核之后才能显示']);
		}else{
			return json(['status' => 0, 'code' => '评论失败']);
		}
    }

    /**
     * 封装下载
     * @Author: 闻子 < QQ：270988107 >
     */
	public function down_file($filename, $allowDownExt = array ('txt'))
	{
		$this->getSession();
	    if(!is_file($filename) && is_readable($filename)) {
	        return false;
	    }
	    $fileext=strtolower(pathinfo($filename,PATHINFO_EXTENSION));
	    if(!in_array($fileext,$allowDownExt)) {
	        return false;
	    }
	    set_time_limit(0);
	    header('content-type:application/octet-stream');
	    header('Accept-Ranges:bytes');
	    $filesize = filesize($filename);
	    header('Accept-Length:'.$filesize);
	    header('content-disposition:attachment;filename='.basename($filename));
	    $read_buffer = 4096;
	    $handle = fopen($filename, 'rb');
	    $sum_buffer = 0;
	    while(!feof($handle) && $sum_buffer < $filesize) {           
	        echo fread($handle,$read_buffer);
	        $sum_buffer += $read_buffer;
	    }
	    fclose($handle);
	}
}