<?php

declare(strict_types=1);

namespace app\control\controller\system;

use app\BaseController;
use app\common\model\account\User as UserModel;
use app\common\model\Base;
use app\control\model\User;
use app\common\model\News as ModelNews;
use app\Request;
use think\response\Json;
use Exception;

/**
 * Class News
 * @package app\control\controller
 */
class News extends BaseController
{
    /**
     * @param Request $request
     * @return Json
     * @throws Exception
     * @api {post} /news/search 新闻列表
     * @apiGroup News
     * @apiName sort1
     * @apiVersion 1.0.0
     *
     * @apiDescription 新闻列表
     *
     * @apiParam {Number} [current]  页码
     * @apiParam {Number} [pageSize]  页数
     * @apiParam {Number} [founder]  创建者id
     * @apiParam {String} [timeCreatedMax]  最小筛选时间
     * @apiParam {String} [timeCreatedMin]  最大筛选时间
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","dataSet":[], "total" : 0}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function search(Request $request): Json
    {
        $input = $request->post();
        $pageIndex = empty($input['current']) ? 1 : intval($input['current']);
        $pageSize = empty($input['pageSize']) ? 10 : intval($input['pageSize']);
        $total = 0;
        $filters = [];
        $returnData = [];
        if (!empty($input['title'])) {
            $filters['title'] = $input['title'];
        }
        if (!empty($input['founder'])) {
            $filters['founder'] = $input['founder'];
        }
        if (!empty($input['timeCreatedMax'])) {
            $filters['timeCreatedMax'] = $input['timeCreatedMax'];
        }
        if (!empty($input['timeCreatedMin'])) {
            $filters['timeCreatedMin'] = $input['timeCreatedMin'];
        }
        $dataSet = ModelNews::search($filters, $pageIndex, $pageSize, $total);
        if (!empty($dataSet)) {
            $returnData = array_map(function ($row) {
                $userInfo = UserModel::fetch($row['founder']);
                $row['founderTitle'] = isset($userInfo['uid']) ? $userInfo['uid'] : '';
                return $row;
            }, $dataSet);
        }
        return payload(['dataSet' => $returnData, 'total' => $total]);
    }

    /**
     * @param Request $request
     * @return Json
     * @throws Exception
     * @api {post} /news/add 新增/修改新闻
     * @apiGroup News
     * @apiName  sort2
     * @apiVersion 1.0.0
     *
     * @apiDescription 新增/修改新闻
     *
     * @apiParam {Number} [id] 新闻id
     * @apiParam {String} title  新闻标题
     * @apiParam {String} content  新闻内容
     * @apiParam {String[]} watch 查看人员 可为空
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Number} id  新闻id
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","id":1}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function add(Request $request): Json
    {
        $input = $request->post();
        if (empty($input['title']) || empty($input['content'])) {
            return payload(error(-1, '参数不完整'));
        }
        $user = User::fetchCurrent();
        $id = isset($input['id']) ? $input['id'] : 0;
        $data = [
            'title' => $input['title'],
            'content' => $input['content'],
            'founder' => $user['id'],
            'watch' => $input['watch']
        ];
        if (empty($id)) {
            $id = ModelNews::add($data);
            if (empty($id)) {
                return payload(error(-1, '新增失败'));
            }
        } else {
            $check = ModelNews::check([$id]);
            if (!$check) {
                return payload(error(-1, '您无操作权限'));
            }
            $res = ModelNews::update(['id' => $id], $data);
            if (!$res) {
                return payload(error(-1, '编辑失败'));
            }
        }
        return payload(['id' => $id]);
    }

    /**
     * @param Request $request
     * @return Json
     * @throws Exception
     * @api {post} /news/delete 删除新闻
     * @apiGroup News
     * @apiName  sort3
     * @apiVersion 1.0.0
     *
     * @apiDescription 删除新闻
     *
     * @apiParam {Number} ids 新闻id
     * @apiParam {String} type single 单删 batch 多删
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Number} id  新闻id
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","id":1}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function delete(Request $request): Json
    {
        $input = $request->post();
        if (empty($input['ids']) || empty($input['type'])) {
            return payload(error(-1, '参数不完整'));
        }
        if ($input['type'] == 'batch') {
            $ids = implode(',', $input['ids']);
        } else {
            $ids = (string)$input['ids'];
        }
        $check = ModelNews::check($ids, $input['type']);
        if (!$check) {
            return payload(error(-1, '您无操作权限'));
        }
        $res = ModelNews::delete($input['type'], $ids);
        if (!$res) {
            return payload(error(-1, '删除失败'));
        }
        return payload([]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /news/detail 新闻详情
     * @apiGroup News
     * @apiName  sort4
     * @apiVersion 1.0.0
     *
     * @apiDescription 新闻详情
     *
     * @apiParam {Number} id 新闻id
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Number} id  新闻id
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","id":1}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function detail(Request $request): Json
    {
        $input = $request->post();
        $id = isset($input['id']) ? $input['id'] : 0;
        if (empty($id)) {
            return payload(error(-1, '参数不完整'));
        }
        $detail = ModelNews::detail(['id' => $id]);
        $userInfo = UserModel::fetch(intval($detail['founder']));
        $detail['founderTitle'] = isset($userInfo['name']) ? $userInfo['name'] : '';
        return payload(['dataSet' => $detail]);
    }

    /**
     * @return Json
     * @api {post} /news/founder 新闻创建人列表
     * @apiGroup News
     * @apiName  sort5
     * @apiVersion 1.0.0
     *
     * @apiDescription 新闻创建人列表
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet  返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","dataSet":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function founder(): Json
    {
        $founder = ModelNews::founder();
        $dataSet = array_map(function ($val) {
            $userInfo = UserModel::fetch($val);
            if (!empty($userInfo)) {
                $val = [
                    'id' => $userInfo['id'],
                    'name' => $userInfo['name']
                ];
                return $val;
            }
        }, $founder);
        $dataSet = array_values(array_filter($dataSet));
        return payload(['dataSet' => $dataSet]);
    }

    /**
     * @param Request $request
     * @return Json
     * @api {post} /news/addView 新闻点击量更新
     * @apiGroup News
     * @apiName  sort6
     * @apiVersion 1.0.0
     *
     * @apiDescription 新闻点击量更新
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":""}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常"}
     */
    public function addView(Request $request)
    {
        $input = $request->post();
        if (empty($input['id'])) {
            return payload(error(-1, '参数不完整'));
        }
        $res = Base::addView('news', intval($input['id']));
        if (!$res) {
            return payload(error(-1, '更新失败'));
        }
        return payload([]);
    }

}