<?php
/**
 *
 * User: inuo
 * Date: 2020-04-23
 * Time: 16:16
 */
namespace app\controller\admin\article;

use app\validate\admin\NoticeValidate;
use crmeb\basic\BaseController;
use app\common\repositories\article\ArticleCategoryRepository;
use app\common\repositories\article\ArticleContentRepository;
use app\common\repositories\article\ArticleRepository;
use FormBuilder\Exception\FormBuilderException;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use app\validate\admin\ArticleValidate;
use think\facade\Db;

class Article extends BaseController
{
    /**
     * @var ArticleRepository
     */
    protected $repository;

    /**
     * Article constructor.
     * @param App $app
     * @param ArticleRepository $repository
     */
    public function __construct(App $app,ArticleRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }


    /**
     * @return mixed
     * @author Qinii
     */
    public function getList()
    {
        [$page, $limit] = $this->getPage();

        $where = $this->request->params(['cid','title']);

        return app('json')->success($this->repository->search($this->request->merId(),$where, $page, $limit));
    }

    /**
     * 添加
     * @param ArticleValidate $validate
     * @param ArticleCategoryRepository $repository
     * @return mixed
     * @author Qinii
     */
    public function create(ArticleValidate $validate,ArticleCategoryRepository $repository)
    {
        $data = $this->checkParams($validate);
        $data['admin_id'] = $this->request->adminId();
        $data['mer_id']   = $this->request->merId()?? 0 ;
        if (!$repository->merExists($data['mer_id'],$data['cid']))
            return app('json')->fail('分类不存在');
        $this->repository->create($data);
        return  app('json')->success('添加成功');

    }

    public function detail($id)
    {
        if (!$this->repository->merExists($this->request->merId(),$id))
            return app('json')->fail('数据不存在');

        return app('json')->success($this->repository->get($id,$this->request->merId()));
    }

    /**
     * 更新
     * @param $id
     * @param ArticleValidate $validate
     * @param ArticleCategoryRepository $articleCategoryRepository
     * @return mixed
     * @author Qinii
     */
    public function update($id,ArticleValidate $validate,ArticleCategoryRepository $articleCategoryRepository)
    {
        $data = $this->checkParams($validate);
        if (!$this->repository->merExists($this->request->merId(),$id))
            return app('json')->fail('数据不存在');
        if (!$articleCategoryRepository->merExists($this->request->merId(),$data['cid']))
            return app('json')->fail('分类不存在');

        $this->repository->update($id,$data);

        return  app('json')->success('编辑成功');


    }

    /**
     * 删除
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Qinii
     */
    public function delete($id)
    {
        if (!$this->repository->merExists($this->request->merId(),$id))
            return app('json')->fail('数据不存在');

        $this->repository->delete($id,$this->request->merId());

        return  app('json')->success('删除成功');
    }


    /**
     * @param ArticleValidate $validate
     * @return array
     * @author Qinii
     */
    public function checkParams(ArticleValidate $validate)
    {
        $data = $this->request->params([['cid', 0], 'title', 'content', 'author', 'image_input','status','sort','synopsis','is_hot','is_banner','url']);
        $validate->check($data);
        return $data;
    }

    /**
     * @return mixed
     * @author cabbage
     */
    public function noticeList()
    {
        [$page, $limit] = $this->getPage();
        $data = $this->request->params(['title','status']);
        if(isset($data['title']) && $data['title'] != ''){
            $where['title'] = ["like","%{$data['title']}%"];
        }
        if(isset($data['status']) && $data['status'] != ''){
            $where['status'] =  $data['status'];
        }
        $where['is_del'] = 0 ;
        $where['mer_id'] = $this->request->merId();
//        var_dump($where);
        return app('json')->success($this->repository->notice($where, $page, $limit));
    }


    /*添加公告*/
    public function noticeCreate(NoticeValidate $validate,ArticleCategoryRepository $repository)
    {
        $data = $this->noticeParams($validate);
        $data['admin_id'] = $this->request->adminId();
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['mer_id'] = $this->request->merId();
        $this->repository->noticeCreate($data);
        return  app('json')->success('添加成功');
    }

    /**
     * @param NoticeValidate $validate
     * @return array
     */
    public function noticeParams(NoticeValidate $validate)
    {
        $data = $this->request->params(['title','content','status']);
        $validate->check($data);
        return $data;
    }
    /*删除公告*/
    public function noticeDelete($id)
    {
        if (!$this->repository->noticeExist($id))
            return app('json')->fail('数据不存在');
        $this->repository->noticeDelete($id);
        return  app('json')->success('删除成功');
    }

    /*修改状态*/
    public function switchStatus($id)
    {
        $is_best = $this->request->param('status', 1) == 1 ? 1 : 2;
        if (!$this->repository->noticeExist($id))
            return app('json')->fail('数据不存在');
        $this->repository->noticeUpdate($id, ['status'=>$is_best]);
        return app('json')->success('修改成功');
    }

    /*详情*/
    public function noticeDetail($id){
        if (!$this->repository->noticeExist($id))
            return app('json')->fail('数据不存在');
        return app('json')->success($this->repository->noticeExist($id));
    }

    /*编辑*/
    public function noticeUpdate($id,NoticeValidate $validate){
        $data = $this->noticeParams($validate);
        if (!$this->repository->noticeExist($id))
            return app('json')->fail('数据不存在');

        $this->repository->noticeUpdate($id,$data);

        return  app('json')->success('编辑成功');
    }
    //评论详情
    public function article_comment($id)
    {
        [$page, $limit] = $this->getPage();
        $data=Db::name('information')->where('pid',$id)->where('is_del',0)->page($page,$limit)->field("id,content,uid,add_time")->select();
        if(!$data->isEmpty()){
            $data=$data->toArray();
        }
        foreach ($data as $k=>&$v){
            $v['user']=Db::name('user')->where('uid',$v['uid'])->field('nickname,avatar,uid')->find();
            //自己是否赞了自己
            $v["fabulous_status"]=Db::name('information_fabulous')->where(["pid"=>$v["id"],"uid"=>$v['uid'],'type'=>0])->count();
            //评论时间
            $v["add_time"]=$this->diffBetweenTwoDay($v["add_time"]);
            //有多少人赞了改评论
            $v["fabulous"]=Db::name('information_fabulous')->where(["pid"=>$v["id"],'type'=>0])->count();
        }
        return app('json')->success($data);
    }
    //删除评论
    public function article_comment_del($id)
    {
        $res=Db::name('information')->where('id',$id)->update(['is_del'=>1]);
        if($res!==false){
            return app('json')->success('删除成功');
        }else{
            return app('json')->fail('删除失败');
        }
    }
    /**
     * 格式化时间
     */
    public function diffBetweenTwoDay($pastDay){
        $timeC = time() - $pastDay;
        $dateC = round((strtotime(date('Y-m-d')) - strtotime(date('Y-m-d',$pastDay)))/60/60/24);
        if($timeC<=3*60){
            $dayC = '刚刚';
        }elseif($timeC>3*60&&$timeC<=5*60){
            $dayC = '3分钟前';
        }elseif($timeC>5*60&&$timeC<=10*60){
            $dayC = '5分钟前';
        }elseif($timeC>10*60&&$timeC<=30*60){
            $dayC = '10分钟前';
        }elseif($timeC>30*60&&$timeC<=60*60){
            $dayC = '30分钟前';
        }elseif($timeC>60*60&&$timeC<=120*60){
            $dayC = '1小时前';
        }elseif($timeC>120*60&&$dateC == 0){
            $dayC = '今天';
        }elseif($dateC == 1){
            $dayC = '昨天';
        }else{
            $dayC = date('Y-m-d',$pastDay);
        }
        return $dayC;
    }

}
