<?php

namespace app\repository;

use app\exception\RepositoryException;
use app\model\AccountRecord;
use app\model\Archives;
use app\model\ArchivesCategory;
use app\model\ArchivesModel;
use app\model\Course;
use app\model\Diary;
use app\model\Disease;
use app\model\DoctorRelation;
use Exception;
use think\Model;
use think\Collection;
use app\service\Repository;
use think\db\exception\DbException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

/**
 * 内容 相关
 *
 * Class ArchivesRepository
 * @package app\repository
 * @method self getInstance(Model $model = null) static
 */
class ArchivesRepository extends Repository
{
    /**
     * 恒美小课堂
     *
     * @param  int  $accountId
     * @param  int  $courseId
     * @param  int  $page
     * @param  int  $size
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws RepositoryException
     */
    public function course(int $accountId = 0, int $courseId = 0, int $page = 1, int $size = 20): array
    {
        $courseList = Course::field('id,title,sort')->order('sort', 'desc')->select()->toArray();
        $activeList = $this->handleActiveStatus($courseList, $courseId);
        $courseList = $activeList['data'];
        $courseId   = $activeList['current_id'];

        $res['course'] = $courseList;
        $res['list']   = [
            'total'   => 0,
            'current' => $page,
            'size'    => $size,
            'list'    => new Collection(),
        ];

        if (count($courseList) > 0) {
            $field   = ['id', 'category_id', 'title', 'diary_id','subtitle', 'cover', 'video', 'views', 'collects', 'shares', 'asks'];
            $where[] = ['course_id', '=', $courseId];
            $where[] = ['is_check', '=', ArchivesModel::COMMON_ON];

            $order = ['sort' => 'desc'];
            $res['list'] = $this->fetchList($accountId, $where, $field, $page, $size, $order);
            // if ($courseId == ($courseList[0]['id'] ?? 0) && $page == 1) {
            //     // 第一个栏目的第一页每次打乱顺序
            //     // 数据打乱
            //     $res['list']['list'] = $res['list']['list']->shuffle();
            // }
        }

        return $res;
    }

    /**
     * 获取列表 添加是否收藏
     * @param  int  $accountId
     * @param  array  $where
     * @param  array  $field
     * @param  int  $page
     * @param  int  $size
     * @param  array  $order
     * @return array|null
     * @throws RepositoryException
     */
    public function fetchList(int $accountId = 0, array $where = [], array $field = [], int $page = 1, int $size = 20, array $order = []): ?array
    {
        $data = $this->findList($where, $field, $page, $size, function ($q) use ($accountId, $order) {
            //是否收藏
            return $q->with([
                'collect' => function ($query) use ($accountId) {
                    $query->where('account_id', $accountId)
                        ->where('is_record', Archives::COMMON_ON)
                        ->where('type', AccountRecord::TYPE_CONTENT)
                        ->where('action', AccountRecord::ACTION_COLLECT);
                }, 'diaryInfo'
            ])->order($order);
        });

        $data['list']->each(function ($item) use ($accountId) {
            if ($accountId > 0) {
                $item->is_collected = (int) $item->is_collected;
            } else {
                $item->is_collected = self::BOOL_FALSE;
            }
        });

        return $data;
    }

    /**
     * 查询指定栏目下 内容列表
     * @param  int  $accountId
     * @param  int  $categoryId
     * @param  array  $where
     * @param  int  $page
     * @param  int  $size
     * @param  array  $order
     * @return array
     * @throws RepositoryException
     */
    public function category(int $accountId = 0, int $categoryId = 0, array $where = [], int $page = 1, int $size = 20, array $order = []): array
    {
        $categoryList = ArchivesModel::categories()->toArray();
        $activeList   = $this->handleActiveStatus($categoryList, $categoryId);
        $categoryList = $activeList['data'];
        $categoryId   = $activeList['current_id'];

        $res['category'] = $categoryList;
        $res['list']     = [
            'total'   => 0,
            'current' => $page,
            'size'    => $size,
            'list'    => new Collection(),
        ];

        if (count($categoryList) > 0) {
            $where[]     = ['category_id', '=', $categoryId];
            $where[]     = ['is_check', '=', ArchivesModel::COMMON_ON];
            $where[]     = ['diary_check', '=', ArchivesModel::COMMON_ON];//日记审核1才能展示 默认1 过滤用户未审核的日记
            $field       = ['id', 'category_id', 'title', 'diary_id', 'subtitle', 'cover', 'video', 'views', 'collects', 'likes', 'asks', 'shares', 'published_at'];
            $res['list'] = $this->fetchList($accountId, $where, $field, $page, $size, $order);
        }

        return $res;
    }

    /**
     * 查询指定栏目下 关于我们 内容列表
     *
     * @param  int  $accountId
     * @param  int  $categoryId
     * @param  array  $where
     * @param  int  $page
     * @param  int  $size
     * @param  array  $order
     * @return array
     * @throws RepositoryException
     */
    public function about(int $accountId = 0, int $categoryId = 0, array $where = [], int $page = 1, int $size = 20, array $order = []): array
    {
        $categoryList = ArchivesModel::about()->toArray();
        $activeList   = $this->handleActiveStatus($categoryList, $categoryId);
        $categoryList = $activeList['data'];
        $categoryId   = $activeList['current_id'];

        $res['category'] = $categoryList;
        $res['list']     = [
            'total'   => 0,
            'current' => $page,
            'size'    => $size,
            'list'    => new Collection(),
        ];

        if (count($categoryList) > 0) {
            $where[]     = ['category_id', '=', $categoryId];
            $where[]     = ['is_check', '=', ArchivesModel::COMMON_ON];
            $field       = ['id', 'category_id', 'diary_id','title', 'subtitle', 'cover', 'published_at'];
            $res['list'] = $this->fetchList($accountId, $where, $field, $page, $size, $order);
        }

        return $res;
    }

    /**
     * 查询指定病种问题列表 目标列表仅为 具有二级病种的【问题文章】内容
     *
     * @param  int  $diseaseId  一级病种
     * @param  array  $where
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws RepositoryException
     */
    public function diseaseQuestion(int $diseaseId = 0, array $where = []): array
    {
        $diseaseList      = Disease::getListByPid()->toArray();
        $activeList       = $this->handleActiveStatus($diseaseList, $diseaseId);
        $diseaseList      = $activeList['data'];
        $currentDiseaseId = $activeList['current_id'];
        $secondList       = Disease::getListByPid($currentDiseaseId);
        $list             = $secondList->toArray();

        $res['first'] = $diseaseList;

        foreach ($list as $k => $v) {
            $list[$k]['children'] = [];
        }
        $res['list'] = $list;

        if (count($secondList) > 0) {
            $where[]     = ['disease_id', '=', $currentDiseaseId];
            $where[]     = ['is_check', '=', ArchivesModel::COMMON_ON];
            $where[]     = ['disease_second_id', 'in', $secondList->column('id')];
            $field       = ['id', 'title', 'category_id', 'subtitle', 'disease_id', 'disease_second_id'];
            $contentList = $this->findList($where, $field)['list']->toArray();
            foreach ($contentList as $content) {
                foreach ($list as &$item) {
                    if ($content['disease_second_id'] == $item['id']) {
                        $item['children'][] = $content;
                    }
                }
            }
            $res['list'] = $list;
        }

        return $res;
    }

    /**
     * 添加选中状态 不传相关ID 则默认第一个选中
     *
     * @param  array  $data
     * @param  int  $relationId
     * @param  bool  $random  是否随机获取 仅$relationId=0时 生效
     * @return array
     */
    public function handleActiveStatus(array $data, int $relationId = 0, bool $random = false): array
    {
        $k = $random ? mt_rand(0, count($data) - 1) : 0;
        foreach ($data as $key => &$item) {
            $item['active'] = 0;
            if ($key == $k && $relationId == 0) {
                $item['active'] = 1;
                $relationId     = $item['id'];
            } elseif ($relationId == $item['id']) {
                $item['active'] = 1;
            }
        }

        $res['current_id'] = $relationId;
        $res['data']       = $data;
        return $res;
    }

    /**
     * 内容详情
     *
     * @param  int  $id
     * @param  int  $accountId
     * @param  int  $shareId  分享人ID 存在则表明，本次请求是shareId分享带来的访问
     * @return array
     * @throws RepositoryException|ModelNotFoundException
     */
    public function detail(int $id, int $accountId = 0, int $shareId = 0): array
    {
        $field = [
            'id', 'category_id', 'title', 'subtitle', 'cover', 'share_img', 'images',
            'video', 'views', 'collects', 'likes', 'asks', 'shares', 'disease_id',
            'course_id', 'hot', 'published_at', 'doctor_id', 'diary_id', 'content'
        ];

        if (!$archives = $this->findById($id, $field)) {
            throw new RepositoryException('数据不存在');
        }

        $archives = $archives->toArray();

        // 是否收藏和点赞
        $doneAction               = AccountRecord::getDoneAction($accountId, $id);
        $archives['is_collected'] = (int) in_array(AccountRecord::ACTION_COLLECT, $doneAction);
        $archives['is_liked']     = (int) in_array(AccountRecord::ACTION_LIKE, $doneAction);

        if (!$archives) {
            throw new RepositoryException('数据不存在');
        }

        // 相关栏目
        $category = ArchivesModel::categories()->toArray();
        foreach ($category as &$cate) {
            $cate['active'] = 0;
            if ($archives['category_id'] == $cate['id']) {
                $cate['active'] = 1;
            }
        }

        // 日记合集 相关推荐
        $res['diary'] = [];
        $archives['published_by'] = '';
        $archives['published_headimgurl'] = '';
        $archives['published_at'] = !empty($archives['published_at']) ? explode(' ', $archives['published_at'])[0] : '';
        if ($archives['diary_id'] > 0) {
            $where[] = ['diary_id', '=', $archives['diary_id']];
            $where[] = ['is_check', '=', ArchivesModel::COMMON_ON];
            $where[] = ['id', '<>', $id];
            $field   = ['id', 'category_id', 'diary_id', 'title', 'subtitle', 'cover', 'video', 'views', 'collects', 'likes', 'shares', 'asks'];

            $res['diary'] = $this->fetchList($accountId, $where, $field)['list'];

            $diaryInfo = Diary::findById($archives['diary_id']);
            $archives['published_by'] = $diaryInfo['user'] ?? '';
            $archives['published_headimgurl'] = $diaryInfo['headimg'] ?? '';
        }

        // 关联医生
        $field   = ['id', 'account_id', 'name', 'phone', 'work_time', 'headimg', 'show_detail', 'gender', 'dept_name', 'account_roles', 'diseases'];
        $doctors = AccountRepository::getInstance()->getRelationDoctorList(DoctorRelation::TYPE_CONTENT, $id);
        $doctors = $doctors->toArray();
        foreach ($doctors as $k => $doctor) {
            $extraFields = arrayKeysFilter($doctor['doctor_extra'] ?? [], $field);
            $baseFields  = arrayKeysFilter($doctor, $field);
            $doctors[$k] = array_merge($baseFields, $extraFields);
        }

        $res['doctor'] = $doctors;

        // 统计查看
        if ($accountId) {
            AccountRecord::record($accountId, AccountRecord::TYPE_CONTENT, AccountRecord::ACTION_VIEW, $id);
        }

        // 分享统计
        if ($shareId) {
            AccountRecord::record($shareId, AccountRecord::TYPE_CONTENT, AccountRecord::ACTION_SHARE_VIEW, $id);
        }

        $res['category'] = $category;
        $res['detail']   = $archives;

        return $res;
    }

    /**
     * 点赞|收藏
     *
     * @param  int  $accountId
     * @param  int  $archiveId
     * @param  string  $action
     * @throws RepositoryException
     */
    public function record(int $accountId, int $archiveId, string $action)
    {
        try {
            if ($accountId <= 0 || $archiveId <= 0) {
                throw new RepositoryException('无效请求');
            }

            if (!in_array($action, AccountRecord::allowActions())) {
                throw new RepositoryException('操作类型参数错误');
            }

            $archive = $this->findById($archiveId);
            if (empty($archive)) {
                throw new RepositoryException('没有相关的内容记录');
            }

            AccountRecord::record($accountId, AccountRecord::TYPE_CONTENT, $action, $archiveId);
        } catch (RepositoryException $e) {
            throw $e;
        } catch (Exception $e) {
            throw new RepositoryException('服务器内部错误！'.$e->getMessage());
        }
    }

    /**
     * 取消收藏|点赞
     *
     * @param  int  $accountId
     * @param  int  $archiveId
     * @param  string  $action
     * @throws RepositoryException
     */
    public function unRecord(int $accountId, int $archiveId, string $action)
    {
        try {
            if ($accountId <= 0 || $archiveId <= 0) {
                throw new RepositoryException('无效请求');
            }

            if (!in_array($action, AccountRecord::allowActions())) {
                throw new RepositoryException('操作类型参数错误');
            }

            $archive = $this->findById($archiveId);
            if (empty($archive)) {
                throw new RepositoryException('没有相关的内容记录');
            }

            AccountRecord::unRecord($accountId, $archiveId, AccountRecord::TYPE_CONTENT, $action);

        } catch (RepositoryException $e) {
            throw $e;
        } catch (Exception $e) {
            throw new RepositoryException('服务器内部错误！');
        }
    }

    /**
     * 获取用户内容收藏列表
     *
     * @param  int  $accountId  用户ID
     * @param  int  $categoryId  分类ID
     * @param  int  $page
     * @param  int  $size
     * @return array
     */
    public function accountCollects(int $accountId, int $categoryId = 0, int $page = 1, int $size = 20): array
    {
        try {
            $data = [
                'total'   => 0,
                'current' => $page,
                'size'    => $size,
                'list'    => new Collection(),
            ];

            $categoryList = ArchivesModel::categories();
            foreach ($categoryList as $key => $item) {
                $item['active'] = 0;

                if ($key == 0 && $categoryId == 0) {
                    $item['active'] = 1;
                    $categoryId     = $item['id'];
                } elseif ($categoryId == $item['id']) {
                    $item['active'] = 1;
                }
            }
            unset($item);

            $whereMap[] = ['ar.account_id', '=', $accountId];
            $whereMap[] = ['ar.is_record', '=', AccountRecord::BOOL_TRUE];
            $whereMap[] = ['ar.type', '=', AccountRecord::TYPE_CONTENT];
            $whereMap[] = ['ar.action', '=', AccountRecord::ACTION_COLLECT];
            if ($categoryId > 0) {
                $whereMap[] = ['archive.category_id', '=', $categoryId];
            }

            $q = $this->model->alias('archive')
                ->leftJoin('account_record ar', 'ar.relation_id = archive.id')
                ->where($whereMap)
                ->distinct(true);

            $data['total'] = $q->count();
            if ($data['total'] > 0) {
                $fields = [
                    'archive.id', 'archive.category_id', 'archive.title', 'archive.subtitle', 'archive.cover',
                    'archive.video', 'archive.views', 'archive.collects', 'archive.likes', 'archive.diary_id'
                ];
                $q      = $q->field($fields)->order(['ar.id' => 'desc']);
                if ($size) {
                    if ($page) {
                        $q = $q->page($page);
                    }
                    $q = $q->limit($size);
                }

                $data['list'] = $q->with(['diaryInfo'])->select();
            }

            return [
                'category' => $categoryList,
                'list'     => $data
            ];

        } catch (Exception $e) {
            return [
                'category' => new Collection(),
                'list'     => [
                    'total'   => 0,
                    'current' => $page,
                    'size'    => $size,
                    'list'    => new Collection(),
                ]
            ];
        }
    }

    /**
     * 内容模型关联栏目
     */
    public function getArchiveCategories()
    {
        return ArchivesModel::categories();
    }

}