<?php

namespace app\controller\manager;

use app\model\Log;
use app\model\Archives as ArchivesModel;
use app\model\ArchivesCategory as ArticleCategoryModel;
use app\model\ArchivesModelField;
use app\model\Config;
use app\repository\CmsRepository;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;
use think\response\View;

/**
 * 档案管理|内容管理
 *
 * Class Archives
 * @package app\controller\manager
 */
class Archives extends Base
{
    protected $noNeedLogin = [];

    /**
     * 删除
     *
     * @return Json
     */
    public function del(): Json
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a', []);
            if (empty($ids)) {
                $ids[] = input('post.id/d');
            }
            ArchivesModel::deleteByIds($ids);
//            Log::write(get_class().'Del', 'del', '涉及到的ID为:'.implode(',', $ids));
            return $this->json();
        }
        return $this->json(4001, '非法请求!');
    }

    /**
     * 编辑
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function edit()
    {
        $id = input('id/d', 0);

        if (!$info = ArchivesModel::findById($id)) {
            return $this->json(4001, '记录不存在');
        }

        if ($this->request->isPost()) {
            $item = input('post.');
            if (isset($item['video_src'])) {
                $item['video'] = $item['video_src'];
                unset($item['video_src']);
            }

            $validate = $this->validateByApi($item, [
                'category_id|栏目' => 'require|gt:0',
                'title|标题'       => 'require|max:255',
                'summary|摘要'     => 'max:255',
                'content|内容'     => 'require',
            ], ['category_id.gt' => '请选择栏目']);

            if ($validate !== true) {
                return $validate;
            }

            try {
                $now                = date('Y-m-d H:i:s');
                $item['updated_at'] = $now;
                $item['updated_by'] = $this->auth['user_id'];
                $info->save($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $showFieldList     = ArchivesModelField::showFieldList();//所有栏目 可展示字段列表
        $currentShowFields = $showFieldList[$info['category_id']] ?? [];//当前选中栏目 可展示字段列表

        $this->data['item']        = $info;
        $this->data['jsonList']    = $this->xmSelectJson([$info['category_id']]);
        $this->data['showList']    = json_encode($showFieldList, JSON_UNESCAPED_UNICODE);
        $this->data['currentList'] = $currentShowFields;

        return $this->view();
    }

    /**
     * 单个字段编辑
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function modify(): Json
    {
        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'field' => 'require',
                'value' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if (!$info = ArchivesModel::findById($item['id'])) {
                return $this->json(4001, '记录不存在');
            }

            $update = [$item['field'] => $item['value']];

            try {
                $info->save($update);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }
        return $this->json(4000, '非法请求');
    }

    /**
     * 添加
     *
     * @return Json|View
     * @throws Exception
     */
    public function add()
    {
        $categoryId = input('category_id/d', 0);

        if ($this->request->isPost()) {
            $item = input('post.');
            if (isset($item['video_src'])) {
                $item['video'] = $item['video_src'];
                unset($item['video_src']);
            }

            $validate = $this->validateByApi($item, [
                'category_id|栏目' => 'require|gt:0',
                'title|标题'       => 'require|max:255',
                'summary|摘要'     => 'max:255',
                'content|内容'     => 'require',
            ], ['category_id.gt' => '请选择栏目']);

            if ($validate !== true) {
                return $validate;
            }

            try {
                $now                  = date('Y-m-d H:i:s');
                $item['created_at']   = $now;
                $item['published_at'] = $now;
                $item['created_by']   = $this->auth['user_id'];
                ArchivesModel::create($item);

                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $showFieldList = ArchivesModelField::showFieldList();//所有栏目 可展示字段列表
        //有指定栏目获取指定栏目 否则获取第一个 可展示字段列表
        $currentShowFields = $categoryId > 0 ? ($showFieldList[$categoryId] ?? []) : array_values($showFieldList)[0];

        $this->data['categoryId']  = $categoryId ?? 0;
        $this->data['jsonList']    = $this->xmSelectJson([$categoryId]);
        $this->data['showList']    = json_encode($showFieldList, JSON_UNESCAPED_UNICODE);
        $this->data['currentList'] = $currentShowFields;

        return $this->view();
    }

    /**
     * 列表
     *
     * @return View|Json
     * @throws Exception
     */
    public function index()
    {
        $categoryId = input('category_id/d', 0);
        if ($this->request->isPost()) {
            $page         = input('page/d', 1);
            $limit        = input('size/d', 20);
            $searchParams = input('searchParams');
            $where        = [];

            if ($categoryId > 0) {
                $where[] = ['category_id', '=', $categoryId];
            }

            if ($searchParams) {
                foreach ($searchParams as $key => $param) {
                    if (!empty($param)) {
                        if (is_string($param)) {
                            $where[] = [$key, 'like', '%'.$param.'%'];
                        } elseif (is_array($param)) {
                            //数组空元素去除
                            foreach ($param as $k => $val) {
                                if (empty($val)) {
                                    unset($param[$k]);
                                }
                            }
                            if (!empty($param)) {
                                $where[] = [$key, 'in', $param];
                            }
                        }
                    }
                }
            }

            $items = ArchivesModel::findList($where, [], $page, $limit, function ($q) {
                return $q->with(['member', 'category'])
                    ->order('top', 'desc')
                    ->order('recommend', 'desc')
                    ->order('hot', 'desc')
                    ->order('sort', 'desc')
                    ->order('id', 'desc');
            });

            $diseaseCategoryIds = ArticleCategoryModel::diseaseCategoryIds();
            $items['list'] = $items['list']->each(function ($item) use ($diseaseCategoryIds) {
                $item->mpPath = in_array($item['category_id'], $diseaseCategoryIds) ? Config::MINI_PATH_PROBLEM : Config::MINI_PATH_ARCHIVES;
            });

            return $this->json(0, '操作成功', $items);
        }

        $selected = $categoryId > 0 ? [$categoryId] : [];

        $this->data['categoryId']   = $categoryId;
        $this->data['categoryJson'] = $this->categoryJson($selected);
        $this->data['archivesPath'] = '/'.Config::MINI_PATH_ARCHIVES;

        return $this->view();
    }

    /**
     * 构造分类 json数据[zTree用]
     *
     * @param  array  $selected
     * @return false|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function categoryJson(array $selected = [])
    {
        $category = ArticleCategoryModel::order('sort', 'desc')
            ->field('id,pid,title')
            ->select()
            ->toArray();
        foreach ($category as $k => $m) {
            $category[$k]['checked'] = in_array($m['id'], $selected);
            $category[$k]['spread']  = true;
        }

        $category = CmsRepository::getInstance()->buildMenuChild(0, $category);
        return json_encode($category, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 内容分类 构造xmSelect json数据[xmSelect用]
     *
     * @param  array  $selected
     * @param  array  $disabled
     * @return false|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function xmSelectJson(array $selected = [], array $disabled = [])
    {
        $category = ArticleCategoryModel::order('sort', 'desc')
            ->field('id,pid,title,model_id')
            ->select();
        $modelList = \app\model\ArchivesModel::column('title', 'id');

        $category->each(function ($item) use ($modelList) {
            $item->title = sprintf("%s-[所属模型:%s]", $item->title, $modelList[$item->model_id]);
        });
        $category = $category->toArray();
        foreach ($category as $k => $m) {
            $category[$k]['selected'] = in_array($m['id'], $selected);
            $category[$k]['disabled'] = in_array($m['id'], $disabled);
        }

        $category = CmsRepository::getInstance()->buildMenuChild(0, $category);
        $category = CmsRepository::getInstance()->handleSelectedList($category);
        return json_encode($category, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 批量审核
     *
     * @return View|Json
     * @throws Exception
     */
    public function check()
    {
        $id = input('id/s', '');
        if ($this->request->isPost()) {
            $ids  = input('ids/s');
            $check = input('is_check/d');

            if (!in_array($check, [ArchivesModel::COMMON_ON, ArchivesModel::COMMON_OFF])) {

                return $this->json(4001, '请选择是否展示');
            }

            $ids = explode(',', $ids);

            Db::startTrans();
            try {
                (new ArchivesModel())->whereIn('id', $ids)->save(['is_check' => $check]);
                Db::commit();
                return $this->json(0, '操作成功');
            } catch (Exception $e) {
                Db::rollback();
                Log::error('批量审核操作失败'.$e->getMessage());
                return $this->json(5001, '批量审核操作失败');
            }
        }

        $this->data['id'] = $id;

        return $this->view();
    }
}