<?php

namespace app\admin\controller\News;

use app\BaseController;
use app\common\model\News\News as ModelNews;
use app\Request;
use think\Validate;
use think\exception\ValidateException;
use think\facade\Filesystem;
use app\common\arw\adjfut\src\Excel;
use app\common\arw\adjfut\src\UploadFile;
use think\facade\Db;
use think\facade\Env;


class News extends BaseController
{
    /**
     * 获取新闻列表
     */
    public function getNewsList(Request $request): array
    {
        $params = $request->param();
        $con = [];

        if (isset($params['news_title']) && $params['news_title']) {
            $con[] = ['news_title', 'LIKE', '%' . $params['news_title'] . '%'];
        };
        if (isset($params['news_type']) && $params['news_type']) {
            $con[] = ['news_type', '=', $params['news_type']];
        };

        $query = ModelNews::where($con);
        $select = self::pageWrapper($query)
            ->field([
                'news_id',
                'news_guid',
                'news_title',
                'news_author',
                'news_intro',
                'news_type',
                'news_img',
                'news_content',
                'news_num'
            ])
            ->order('news_update_time', 'desc')
            ->select();

        $count = $query->count();

        return [
            'code' => 0,
            'data' => $select,
            'count' => $count,
            'msg' => 'ok'
        ];
    }

    /**
     * 编辑新闻
     */
    public function editNews(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'news_title|新闻标题' => 'require',
            'news_author|新闻作者' => 'require',
            'news_intro|新闻简介' => 'require',
            'news_type|新闻类型' => 'require',
            'news_img|新闻封面' => 'require',
        ]);
        $model = ModelNews::where('news_guid', $params['news_guid'])->find();
        if (!$model) throwErrorMsg("该新闻不存在", 1);
        $model->allowField([
            'news_update_user_guid',
            'news_title',
            'news_author',
            'news_intro',
            'news_type',
            'news_img',
            'news_content',

            'news_num'
        ])->save($params);
        return [
            'code' => 0,
            'msg' => '编辑成功'
        ];
    }

    /**
     * 添加新闻
     */
    public function addNews(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'news_title|新闻标题' => 'require',
            'news_author|新闻作者' => 'require',
            'news_intro|新闻简介' => 'require',
            'news_type|新闻类型' => 'require',
            'news_img|新闻封面' => 'require',

        ]);
        $model = ModelNews::create($params, [
            'news_guid',
            'news_create_user_guid',
            'news_update_user_guid',
            'news_title',
            'news_author',
            'news_intro',
            'news_type',
            'news_img',
            'news_content',
            

            'news_num'
        ]);
        return [
            'code' => 0,
            'msg' => '添加成功'
        ];
    }

    /**
     * 删除新闻
     */
    public function deleteNews(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'news_guid' => 'require',
        ]);
        $news = ModelNews::where([
            'news_guid' => explode(',', $params['news_guid'])
        ])->select();
        $news->delete();
        return [
            'code' => 0,
            'msg' => "删除成功"
        ];
    }

    /**
     * 导出Excel
     */
    public function exportExcel(Request $request)
    {
        $params = $request->param();
        $select = ModelNews::field([
            'news_title',
            'news_author',
            'news_intro',
            'news_type',
            'news_img',
            'news_content',

            'news_num'
        ])
            ->order('news_update_time', 'desc')
            ->select();
        $data = [[
            '新闻标题',
            '新闻作者',
            '新闻简介',
            '新闻类型',
            '新闻封面',
            '新闻内容',

            '新闻数量'
        ]];
        foreach ($select as $key => $val) {
            $data[] = [
                $val['news_title'],
                $val['news_author'],
                $val['news_intro'],
                $val['news_type'],
                $val['news_img'],
                $val['news_content'],

                $val['news_num'],
            ];
        }
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('新闻.xlsx');
    }

    /**
     * 下载导入模板
     */
    public function downloadTemplate(Request $request)
    {
        $params = $request->param();
        $data = [
            '新闻标题',
            '新闻作者',
            '新闻简介',
            '新闻类型',
            '新闻封面',
            '新闻内容',

            '新闻数量'
        ];
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('新闻导入模板.xlsx');
    }

    /**
     * 导入excel
     */
    public function importExcel(Request $request)
    {
        $file = new UploadFile('uploads', 'fileExt:xlsx');
        $file->putFile('news');
        Db::startTrans();
        try {
            $excel = new Excel($file);
            $data = $excel->parseExcel(
                [[
                    'title' => '新闻标题',
                    'validate' => 'require',
                    'field' => 'news_title',
                ], [
                    'title' => '新闻作者',
                    'validate' => 'require',
                    'field' => 'news_author',
                ], [
                    'title' => '新闻简介',
                    'validate' => 'require',
                    'field' => 'news_intro',
                ], [
                    'title' => '新闻类型',
                    'validate' => 'require',
                    'field' => 'news_type',
                ], [
                    'title' => '新闻封面',
                    'validate' => 'require',
                    'field' => 'news_img',
                ], [
                    'title' => '新闻内容',
                    'validate' => 'require',
                    'field' => 'news_content',
                ], [
                    'title' => '新闻数量',
                    'validate' => 'require',
                    'field' => 'news_num',
                ],],
                [
                    'titleLine' => [1]
                ]
            );
            if (!$data)  throwErrorMsg('excel无数据', 1);
            $error = [];
            foreach ($data as $line => $value) {
                try {
                    $news_title = $value['news_title'];
                    $news_author = $value['news_author'];
                    $news_intro = $value['news_intro'];
                    $news_type = $value['news_type'];
                    $news_img = $value['news_img'];
                    $news_content = $value['news_content'];
                    $news_data = $value['news_data'];
                    $news_time = $value['news_time'];
                    $news_num = $value['news_num'];
                    ModelNews::create([
                        'news_title' => $news_title,
                        'news_author' => $news_author,
                        'news_intro' => $news_intro,
                        'news_type' => $news_type,
                        'news_img' => $news_img,
                        'news_content' => $news_content,

                        'news_num' => $news_num,
                    ]);
                } catch (\Throwable $th) {
                    $error[] = $line . '：' . $th->getMessage();
                }
            }
            if ($error)  throwErrorMsg(implode(', ', $error), 1);
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
        }
        return [
            'code' => 0,
            'msg' => '导入成功!'
        ];
    }
}
