<?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();

        if (input('order') == 2) {
            $order = ['sort' => 'desc', 'id' => 'desc'];
        } else {
            $order = ['id' => 'desc'];
        }
        // 模糊查询title
        if ($title) {
            $map['title'] = ['like', "%" . $title . "%"];
        }
        $posts = model('guide')->where($map)->order($order)->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);

        $this->assign('article', 0);
        $this->assign('tag_arr', []);
        $this->assign('tags', '');

        if (request()->isPost()) {
            $type = input("post.type");
            $data = array(
                'title' => input("post.title"),
                'tags' => input("post.tags/a"),
                '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_decode($data['content'])
            ]);
            if ($article->save()) {
                $this->success('添加成功', url('@admin/Guide/index'), '', 1);
            } else {
                $this->error('添加失败', $_SERVER['HTTP_REFERER'], '', 1);
            }
        } else {
            return view('update');
        }
    }

    /**
     * 修改攻略
     *
     * @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/a")
            );
            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' => implode(',',$data['tags']),
                'title' => $data['title'],
                'intro' => input('post.intro'),
                'type' => $type,
                'content' => htmlspecialchars_decode($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();
                }
                $condition['poster'] = $result['result']['url'];
            }

            $res = model('post')->save($condition, ['id' => $id]);
            if ($res) {
                $this->success('修改成功', url('@admin/Guide/index'), '', 1);
            } else {
                $this->success('修改失败', $_SERVER['HTTP_REFERER'], '', 1);
            }
        } 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);
    }

    //修改排序
    public function changeSort()
    {
        if(request()->isPost()){
            $res = \app\common\model\Guide::update(input('post.'));
            if($res){
                return json(['code'=>0,'msg'=>'修改成功']);
            }else{
                return json(['code'=>1,'msg'=>'修改失败']);
            }
        }
    }

}
