<?php
namespace app\admin\controller;

use think\Db;
use app\admin\controller\AuthBase;
use app\common\model\Post as PostModel;
use app\common\model\Admin as AdminModel;
use app\admin\controller\Upload;

class Guide extends AuthBase
{
    public function index()
    {
        $title = input('title');
        $map = array();

        // 模糊查询title
        if ($title) {
            $map['title'] = ['like', "%".$title."%"];
        }
        $posts = PostModel::where($map)->order('id desc')->paginate(10);

        $this->assign('articles', $posts);
        return view("index");
    }

    public function create()
    {
        $tag_model = model("tags");
        $tag_list = $tag_model -> order('sort','asc') -> select();
        $this -> assign('tag_list', $tag_list);
        if (request()->isPost()) {
            $type = input("post.type");
            $data = array(
                'title' => input("post.title"),
                'tags' => input("post.tags"),
                'poster' => input('file.poster')
            );
            if($type == 1){
                $data['content'] =input("post.content");
            }else{
                $data['content'] =input("post.href");
            }
            $validate = validate('Post');
            if (!$validate->scene('create')->check($data)) {
                $msg = $validate->getError();
                $this->assign('msg', $msg);
                return view();
            }
//            上传封面到七牛云
            $upload = new Upload();
            $result =  $upload -> sava(input('file.poster'));
            if($result['error']){
                $this->assign('msg', $result['error']);
                return view();
            }
            $article = new PostModel([
                'admin_id' => intval(session('uid')),
                'poster' => $result['result']['url'],
                'tags' => $data['tags'],
                'title' => $data['title'],
                'type' => $type,
                'intro' => input('post.intro'),
                'content' => htmlspecialchars($data['content'])
            ]);
            if ($article->save()) {
                $this->redirect(url('@admin/Guide/index'));
             } else {
                return view();
             }
        } else {
            return view();
        }
    }

    /**
     * 修改文章
     *
     * @return \think\Response
     */
    public function update($id)
    {
        $tag_model = model("tags");
        $tag_list = $tag_model -> order('sort','asc') -> select();
        $this -> assign('tag_list', $tag_list);
        $article = PostModel::get($id);
        $tags =$article['tags'];
        $this->assign('tags',$tags);
        if($tags!=''){
            $tag_arr = explode(',',$tags);
        }else{
            $tag_arr = [];
        }

        $this->assign('tag_arr',$tag_arr);
        if (request()->isPost()) {
            $type = input("post.type");
            $data = array(
                'title' => input("post.title"),
                'tags' => input("post.tags")
            );
            if($type == 1){
                $data['content'] =input("post.content");
            }else{
                $data['content'] =input("post.href");
            }
            $validate = validate('Post');
            if (!$validate->scene('update')->check($data)) {
                $msg = $validate->getError();
                $this->assign('msg', $msg);
                return view();
            }
            $condition = [
                'tags' => $data['tags'],
                'title' => $data['title'],
                'intro' => input('post.intro'),
                'type' => $type,
                'content' => htmlspecialchars($data['content'])
            ];
            if(input('file.poster')){
              //            上传封面到七牛云
              $upload = new Upload();
              $result =  $upload -> sava(input('file.poster'));
              if($result['error']){
                  $this->assign('msg', $result['error']);
                  return view();
              }
              // 将资源目录该图的引用设为0
//              $resource_model = model('Resource');
//              $res = $resource_model->where('address',input('post.old_poster'))->setDec("use_num");
              $condition['poster'] = $result['result']['url'];
            }

            $res = model('post')->save($condition,['id'=>$id]);
            if ($res) {
                $this->redirect(url('@admin/Guide/index'));
            } else {
                return view();
            }
        }else{
            $this->assign('article', $article);
            return view();
        }
    }

    /**
     * 删除文章
     *
     * @return \think\Response
    */
    public function delete()
    {
        $result["error"] = 0;
        $result["msg"] = '删除成功';

        if( request()->isPost() ) {
            $id = input("post.id");
            $article = PostModel::get($id);
            if( $article ) {
                if( $article->delete() ){

                }else{
                    $result["error"] = 1;
                    $result["msg"] = '删除失败！';
                }
            }else{
                $result["error"] = 1;
                $result["msg"] = '删除对象不存在';
            }
        }else{
            $result["error"] = 1;
            $result["msg"] = '不支持的请求方法';
        }
        echo json_encode($result);
    }

}
