<?php

namespace app\admin\controller;

use app\admin\AdminBaseController;
use app\common\model\ArticleModel;
use app\common\model\ArticleCateModel;
use app\admin\validate\ArticleCateValidate;
use app\admin\validate\ArticleValidate;
use think\exception\ValidateException;

class Article extends AdminBaseController
{
    /**
     * 列表
     */
    public function index()
    {
        $cate_list = ArticleCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();

        return view('', [
            'cate_list'   => $cate_list,
            'type_list'   => ArticleModel::TYPE,
            'status_list' => ArticleModel::STATUS,
        ]);
    }

    public function articleForm()
    {
        $cate_list = ArticleCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        $id        = input('id/d, 0');
        $info      = ArticleModel::find($id);

        return view('', [
            'cate_list'   => $cate_list,
            'info'        => $info,
            'type_list'   => ArticleModel::TYPE,
            'status_list' => ArticleModel::STATUS,
        ]);
    }

    public function listArticle()
    {
        $map = $this->dealEqualInput(['cate_id', 'type', 'status'], $this->dealLikeInput(['title']));

        $list  = ArticleModel::with('cate')
            ->where($map)
            ->order(['priority' => 'desc', 'id' => 'desc'])
            ->limit(input('limit'))
            ->page(input('page'))
            ->append(['type_text', 'status_text'])
            ->select();
        $count = ArticleModel::where($map)->count();

        if ($count == 0) {
            ajax_return(1, '未查询到数据');
        }
        list_return($list, $count);
    }

    public function delArticle()
    {
        $id_arr = input('id_arr/a');
        ArticleModel::destroy($id_arr);
        ajax_return();
    }

    public function editArticle()
    {
        $data = input('post.');
        try {
            validate(ArticleValidate::class)->check($data);
        } catch (ValidateException $e) {
            ajax_return(1, $e->getError());
        }

        if ($data['type'] == 1 && empty($data['content'])) {
            ajax_return(1, '详情不能为空');
        }
        if ($data['type'] == 2 && empty($data['url'])) {
            ajax_return(1, '链接不能为空');
        }

        if (empty($data['id'])) {
            ArticleModel::create($data, ArticleModel::EDIT_ALLOW);
        } else {
            ArticleModel::update($data, ['id' => $data['id']], ArticleModel::EDIT_ALLOW);
        }

        ajax_return();
    }

    public function fieldArticle()
    {
        $id      = input('id/d', 0);
        $article = ArticleModel::find($id);
        if (empty($article)) {
            ajax_return(1, '信息不存在');
        } else {
            $article->save([
                input('field/s') => input('value/s', ""),
            ]);
        }
        ajax_return();
    }


    /**
     * 分类
     */
    public function cate()
    {
        return view('', [
            'status_list' => ArticleCateModel::STATUS,
        ]);
    }

    public function cateForm()
    {
        $id   = input('id/d, 0');
        $info = ArticleCateModel::find($id);
        return view('', [
            'info'        => $info,
            'status_list' => ArticleCateModel::STATUS,
        ]);
    }

    public function listCate()
    {
        $map   = $this->dealEqualInput(['status']);
        $list  = ArticleCateModel::where($map)
            ->order(['priority' => 'desc', 'id' => 'desc'])
            ->limit(input('limit'))
            ->page(input('page'))
            ->append(['status_text'])
            ->select();
        $count = ArticleCateModel::where($map)->count();
        if ($count == 0) {
            ajax_return(1, '未查询到数据');
        }
        list_return($list, $count);
    }

    public function fieldCate()
    {
        $id   = input('id/d');
        $cate = ArticleCateModel::find($id);
        if (empty($cate)) {
            ajax_return(1, '分类信息不存在');
        } else {
            $cate->save([
                input('field/s') => input('value/s', ""),
            ]);
        }
        ajax_return();
    }

    public function editCate()
    {
        $data = input('post.');
        try {
            validate(ArticleCateValidate::class)->check($data);
        } catch (ValidateException $e) {
            ajax_return(1, $e->getError());
        }

        if (empty($data['id'])) {
            ArticleCateModel::create($data, ArticleCateModel::EDIT_ALLOW);
        } else {
            ArticleCateModel::update($data, ['id' => $data['id']], ArticleCateModel::EDIT_ALLOW);
        }

        ajax_return();
    }

    public function delCate()
    {
        $id    = input('id/d');
        $check = ArticleModel::where('cate_id', $id)->find();
        if (!empty($check)) {
            ajax_return(1, '该分类下还有文章，无法删除');
        }
        ArticleCateModel::destroy($id);
        ajax_return();
    }

    public function importCate()
    {
        return view('public/import', [
            'url'           => url('article/importCatePost'),
            'last_table'    => 'lay-article-cate-table',
            'template_file' => '/static/common/exl/article_cate.xls',
        ]);
    }

    public function importCatePost()
    {
        $file_url = input('file_url/s', "");
        if (!file_exists($file_url)) {
            ajax_return(1, '文件不存在');
        }

        $data        = ['title', 'priority'];
        $list        = import_exl($file_url, $data, 1);
        $empty_check = [
            'title' => '分类名称',
        ];

        foreach ($list as $k => $v) {
            foreach ($empty_check as $key => $value) {
                if (empty($v[$key])) {
                    return ajax_return(1, '第' . ($k + 2) . '行的' . $value . '不能为空');
                }
            }
            $list[$k]['priority'] = empty($v['priority']) ? 255 : (int)$v['priority'];
        }

        ArticleCateModel::insertAll($list);
        ajax_return(0);
    }

    public function exportCate()
    {
        $map  = $this->dealInInput(['id'],$this->dealEqualInput(['status']));
        $list = ArticleCateModel::where($map)
            ->order(['priority' => 'desc', 'id' => 'desc'])
            ->select();

        $xlsCell = [
            ['id', '表ID'],
            ['title', '分类名称'],
            ['status_text', '状态'],
            ['priority', '排序'],
        ];
        export_exl("文章分类", $xlsCell, $list);
    }
}