<?php

namespace app\controller\api;

use app\model\AccountRecord;
use app\model\Disease;
use app\repository\ArchivesRepository;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;
use app\exception\RepositoryException;

class Archives extends Base
{
    protected $noNeedLogin = ['course', 'detail'];

    /**
     * 病种列表
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function disease(): Json
    {
        $data = Disease::getListByPid();

        return $this->json(0, 'success', $data);
    }

    /**
     * 病种问题文章列表 分类问题
     *
     * @return Json
     */
    public function diseaseQuestion(): Json
    {
        $diseaseId = input('disease_id/d', 0);

        try {
            $data = ArchivesRepository::getInstance()->diseaseQuestion($diseaseId);

            return $this->json(0, 'success', $data);
        } catch (RepositoryException $e) {
            return $this->json(4001, $e->getMessage());
        } catch (Exception $e) {
            ArchivesRepository::log($e->getMessage(), $e);
            return $this->json(5000, '操作失败');
        }
    }

    /**
     * 恒美小课堂
     *
     * @return Json
     * @throws Exception
     */
    public function course(): Json
    {
        $accountId = $this->request->user['user_id'] ?? 0;
        $courseId  = input('course_id/d', 0);
        $page      = input('page/d', 1);
        $size      = input('size/d', 20);

        try {
            $data = ArchivesRepository::getInstance()->course($accountId, $courseId, $page, $size);

            return $this->json(0, 'success', $data);
        } catch (RepositoryException $e) {
            return $this->json(4001, $e->getMessage());
        } catch (Exception $e) {
            ArchivesRepository::log($e->getMessage(), $e);
            return $this->json(5000, '操作失败');
        }
    }

    /**
     * 热门推荐
     *
     * @return Json
     * @throws Exception
     */
    public function hot(): Json
    {
        $categoryId = input('category_id/d', 0);
        $page       = input('page/d', 1);
        $size       = input('size/d', 20);
        $keyword    = input('keyword/s', '');
        $accountId  = $this->request->user['user_id'] ?? 0;

        try {
            $where[] = ['hot', '=', 1];
            if (!empty($keyword)) {

                $keyword = trim($keyword);
                $where[] = ['title|subtitle|disease_name|doctor_name', 'like', '%'.$keyword.'%'];
                AccountRecord::saveSearch($accountId, $keyword);
            }

            $order = ['sort' => 'desc'];
            $data = ArchivesRepository::getInstance()->category($accountId, $categoryId, $where, $page, $size, $order);

            return $this->json(0, 'success', $data);
        } catch (RepositoryException $e) {
            return $this->json(4001, $e->getMessage());
        } catch (Exception $e) {
            ArchivesRepository::log($e->getMessage(), $e);
            return $this->json(5000, '操作失败');
        }
    }

    /**
     * 获取指定栏目内容列表
     *
     * @return Json
     * @throws Exception
     */
    public function category(): Json
    {
        $categoryId = input('category_id/d', 0);
        $page       = input('page/d', 1);
        $size       = input('size/d', 20);
        $keyword    = input('keyword/s', '');
        $diseaseIds = input('disease_id/s', '');//病种 多个用逗号分隔
        $accountId  = $this->request->user['user_id'] ?? 0;

        try {
            $where = [];
            if (!empty($keyword)) {
                $keyword = trim($keyword);
                $where[] = ['title|subtitle|disease_name|doctor_name', 'like', '%'.$keyword.'%'];
                AccountRecord::saveSearch($accountId, $keyword);
            }

            if (!empty($diseaseIds)) {
                $where[] = ['disease_id', 'in', explode(',', $diseaseIds)];
            }

            $order = ['sort' => 'desc'];
            $data = ArchivesRepository::getInstance()->category($accountId, $categoryId, $where, $page, $size, $order);
            return $this->json(0, 'success', $data);
        } catch (RepositoryException $e) {
            return $this->json(4001, $e->getMessage());
        } catch (Exception $e) {
            ArchivesRepository::log($e->getMessage(), $e);
            return $this->json(5000, '操作失败');
        }
    }

    /**
     * 获取关于我们栏目内容列表
     *
     * @return Json
     * @throws Exception
     */
    public function about(): Json
    {
        $categoryId = input('category_id/d', 0);
        $page       = input('page/d', 1);
        $size       = input('size/d', 20);
        $exceptId   = input('except_id/d', 0);
        $keyword    = input('keyword/s', '');
        $accountId  = $this->request->user['user_id'] ?? 0;

        try {
            $where = [];
            if (!empty($keyword)) {
                $keyword = trim($keyword);
                $where[] = ['title|subtitle|disease_name|doctor_name', 'like', '%'.$keyword.'%'];
                AccountRecord::saveSearch($accountId, $keyword);
            }

            if ($exceptId > 0) {
                $where[] = ['id', '<>', $exceptId];
            }

            $order = ['published_at' => 'desc'];

            $data = ArchivesRepository::getInstance()->about($accountId, $categoryId, $where, $page, $size, $order);
            return $this->json(0, 'success', $data);
        } catch (RepositoryException $e) {
            return $this->json(4001, $e->getMessage());
        } catch (Exception $e) {
            ArchivesRepository::log($e->getMessage(), $e);
            return $this->json(5000, '操作失败');
        }
    }

    /**
     * 内容详情
     *
     * @return Json
     * @throws Exception
     */
    public function detail(): Json
    {
        $id        = input('id/d', 0);
        $shareId   = input('share_id/d', 0);//分享人ID
        $accountId = $this->request->user['user_id'] ?? 0;

        try {
            $data = ArchivesRepository::getInstance()->detail($id, $accountId, $shareId);
            return $this->json(0, 'success', $data);
        } catch (RepositoryException $e) {
            return $this->json(4001, $e->getMessage());
        } catch (Exception $e) {
            ArchivesRepository::log($e->getMessage(), $e);
            return $this->json(5000, '获取详情失败');
        }

    }

    /**
     * 点赞、收藏
     */
    public function record(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '无效请求');
        }

        $accountId = $this->request->user['user_id'] ?? 0;
        $archiveId = $this->request->param('archive_id/d', 0);
        $action    = $this->request->param('action/s', '');

        try {
            ArchivesRepository::getInstance()->record($accountId, $archiveId, $action);
        } catch (RepositoryException $e) {
            return $this->json(4001, $e->getMessage());
        }

        return $this->json();
    }

    /**
     * 取消 点赞、收藏
     */
    public function unRecord(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '无效请求');
        }

        $accountId = $this->request->user['user_id'] ?? 0;
        $archiveId = $this->request->param('archive_id/d', 0);
        $action    = $this->request->param('action/s', '');

        try {
            ArchivesRepository::getInstance()->unRecord($accountId, $archiveId, $action);
        } catch (RepositoryException $e) {
            return $this->json(4001, $e->getMessage());
        }

        return $this->json();
    }

    /**
     * 用户内容收藏列表
     */
    public function collects(): Json
    {
        $accountId  = $this->request->user['user_id'] ?? 0;
        $categoryId = $this->request->param('category_id/d', 0);
        $page       = $this->request->param('page/d', 1);
        $size       = $this->request->param('size/d', 10);

        $page = $page <= 0 ? 1 : $page;
        $size = $size <= 0 ? 10 : $size;
        $data = ArchivesRepository::getInstance()->accountCollects($accountId, $categoryId, $page, $size);
        return $this->json(0, 'success', $data);
    }
}