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

use app\admin\AdminBaseController;
use app\wendasns\model\Topic as byTopic;
use app\wendasns\model\Category;
use wendasns\facade\Image;
use think\facade\Request;

class Topic extends AdminBaseController
{

    public function index()
    {
		return view();
    }

	public function list()
	{
		$limit = input('get.limit',10,'intval');
		$dm = byTopic::order('id','desc')->paginate($limit);
		
        $data = $dm->toArray();
		success('ok', $data['data'], ['count'=>$data['total']]);
    }

	public function edit()
	{
		$id = input('post.id',0,'intval');
		if($id){
			$this->_update($id);
		}else{
			$this->_add();
		}
		success('操作成功');
	}

	private function _add()
	{
		$name = input('post.name','');
		$alias = input('post.alias','');
		$intro = input('post.intro','');
		$icon = input('post.icon','');
    	
    	byTopic::create([
		    'name' => $name,
    		'alias' => $alias,
			'intro' => $intro,
    		'icon' => $icon
		]);
    }
    
	private function _update($id)
	{
    	$dm = byTopic::find($id);
    	if(!$dm){
    		error('话题不存在');
    	}
		$data = Request::only(['name','alias','icon','intro']);
		$dm->save($data);
    }
    
	public function remove()
	{
		$id = input('post.id',[]);
		if(is_array($id)){
			byTopic::destroy($id);
		}
		success('操作成功');
	}

	//图片上传
	public function upload(){
		$file = request()->file('file');
		try {
			$this->app->http->name('wendasns');
			$src = Image::content('topic')->upload($file);
			$src = preg_replace('/(.*?\/\/.*?)\/.*?\.php(.*)/','$1$2',$src);
		} catch (\think\exception\ValidateException $e) {
			error($e->getMessage());
		}
		success('上传成功',['src'=>$src, 'title'=>'']);
	}
}