<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
namespace app\wendasns\admin;

use app\admin\AdminBaseController;
use app\wendasns\model\Recommend as byRecommend;
use app\wendasns\model\Adpic;
use wendasns\facade\Image;

class Recommend extends AdminBaseController
{
	//置顶推荐页
    public function index()
    {
    	$dm = byRecommend::select();
    	$data = [];
    	foreach($dm as $v){
    		if($v->mode=='top'){
    			$data['top'] = $v->article_id;
    		}else{
    			$data['recommend'][$v->sort] = $v->article_id;
    		}
    	}
		return view('index',$data);
    }
    
    //轮播页
    public function adpic()
    {
    	return view();
    }
    
    //轮播图片列表
    public function image()
	{
		$limit = input('get.limit',10,'intval');
		$dm = Adpic::paginate($limit);

        $data = $dm->toArray();
		success('ok', $data['data'], ['count'=>$data['total']]);
    }
    
    //轮播图添加
    public function add()
    {
		$pic = input('post.pic','');
		$url = input('post.url','');
		Adpic::create([
		    'src' => $pic,
		    'url' => $url,
		]);
		success('操作成功');
    }
    
    //轮播图编辑
    public function edit()
	{
		$post = input('post.',[]);
		isset($post['sort']) && $post['sort'] = intval($post['sort']);
		Adpic::update($post);
		success('操作成功');
    }
    
    //轮播图删除
    public function remove()
	{
		$id = input('post.id',[]);
		if(is_array($id)){
			$dm = Adpic::select($id);
			$path = root_path('runtime'.DIRECTORY_SEPARATOR.'wendasns'.DIRECTORY_SEPARATOR.'focus');
			foreach($dm as $v){
				$n = strrpos($v->src,'/');
				$name = substr($v->src,$n+1);
				if(file_exists($path.$name)){
					unlink($path.$name);
				}
			}
			Adpic::destroy($id);
		}
		success('操作成功');
    }

    //添加置顶和推荐
	public function post()
	{
		$top = input('post.top',0,'intval');
		$recommend = input('post.recommend',[]);
		
		$dm = byRecommend::select();
		$list = [];

		if($dm->toArray()){
			foreach($dm as $v){
				$list[] = ['id'=>$v->id, 'article_id'=>$v->mode=='top'?$top:intval($recommend[$v->sort])];
			}
		}else{
			$list[] = ['article_id'=>$top,'mode'=>'top'];
			foreach($recommend as $k=>$v){
				$list[] = ['article_id'=>intval($v),'mode'=>'recommend','sort'=>$k];
			}
		}
		
		$recommend = new byRecommend;
		$recommend->saveAll($list);
		
		success('操作成功');
    }
	
	//图片上传
	public function upload(){
		$file = request()->file('file');
		try {
			$this->app->http->name('wendasns');
			$src = Image::content('focus')->upload($file);
			$src = str_replace("/admin.php","",$src);
    	} catch (\think\exception\ValidateException $e) {
        	error($e->getMessage());
    	}
    	success('上传成功',['src'=>$src, 'title'=>'']);
	}

}