<?php

namespace app\common\model\ExaminationInformation;

use app\common\arw\adjfut\src\Validate;
use app\BaseModel;
use think\model\concern\SoftDelete;
use app\common\arw\adjfut\src\Excel;
use app\Request;
use app\common\exception\Tool;
use think\facade\Db;
use app\common\model\Dictionary\Dictionary as ModelDictionary;
use app\common\model\ExaminationInformation\InfoArticleType as ModelInfoArticleType;

class InfoArticle extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'info_article_delete_time';
    // 设置主键名
    protected $pk = 'info_article_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [

        "info_article_id" => "int",

        "info_article_guid" => "string",

        "info_article_type_guid" => "string",

        "info_article_title" => "string",

        "info_article_cover" => "string",

        "info_article_content" => "string",

        "info_article_status" => "int",

        "info_article_order" => "int",

        "info_article_create_time" => "datetime",

        "info_article_create_user_guid" => "string",

        "info_article_update_time" => "datetime",

        "info_article_update_user_guid" => "string",

        "info_article_delete_time" => "datetime",

        "info_article_delete_user_guid" => "string",

    ];
    // 设置json类型字段
    protected $json = [''];
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 创建时间
    protected $createTime = 'info_article_create_time';
    // 修改时间
    protected $updateTime = 'info_article_update_time';


    // excel导入/下载模板表头
    public const EXCELFIELD = [
        'info_article_type_name' => '文章类型',
        'info_article_title' => '文章标题',
        'info_article_cover' => '文章封面',
        // 'info_article_content' => '文章内容',
        'info_article_order' => '文章排序',
        'info_article_status' => '首页是否展示',
    ];

    //排序字段
    public $order_field = 'info_article_order';
    /**
     * 新增前
     */
    public static function onBeforeInsert(self $model): void
    {
        Tool::sortInsertProc(
            self::class,
            $model->info_article_order,
            ['info_article_type_guid' => $model->info_article_type_guid]
        );
        // self::checkRepeatData($model);
        $model->completeCreateField();
    }

    /**
     * 更新前
     */
    public static function onBeforeUpdate(self $model): void
    {
        Tool::sortEditProc(
            self::class,
            $model->info_article_guid,
            $model->info_article_order,
            ['info_article_type_guid' => $model->info_article_type_guid]
        );
        // self::checkRepeatData($model);
        $model->completeUpdateField();
    }

    /**
     * 删除前
     */
    public static function onBeforeDelete(self $model): void
    {
        Tool::sortDeleteProc(self::class, $model->info_article_guid);
        $model->completeDeleteField();
    }

    /**
     * 导出Excel
     */
    public static function exportExcel($select)
    {
        $data = [[
            '文章类型',
            '文章标题',
            '文章封面',
            // '文章内容',
            '文章排序',
            "首页是否展示"
        ]];
        foreach ($select as $key => $val) {
            $show_status = ModelDictionary::getDictionaryData('show_status');
            $val['info_article_status'] =  ModelDictionary::getDataDictionaryName($show_status, $val['info_article_status']);

            $data[] = [
                $val['info_article_title'],
                $val['info_article_title'],
                Excel::ExportImgFiled($val['info_article_cover']),
                // $val['info_article_content'],
                $val['info_article_order'],
                $val['info_article_status'],
            ];
        }
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('资讯文章.xlsx');
    }

    /**
     * 导入excel
     */
    public static function importExcel($file)
    {
        $msg = [];

        Db::startTrans();
        try {
            $excel = new Excel($file);
            $data = $excel->parseExcel(
                Tool::getExcelRule(self::EXCELFIELD),
                [
                    'titleLine' => [1]
                ]
            );
            if (!$data)  throwErrorMsg('excel无数据', 1);
            $msg = [];
            foreach ($data as $line => $value) {
                try {
                    $model = self::importExcelInit($value);
                    $msg[] = "{$line} <span style='color:#27af49'>{$model->info_article_title}新增成功!</span><br>";
                } catch (\Throwable $th) {
                    $msg[] = "{$line} <span style='color:red'>{$th->getMessage()}</span><br>";
                }
            }
            Db::commit();
            return implode(', ', $msg);
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
        }
    }

    /**
     * 导入excel初始化
     */
    public static function importExcelInit($value)
    {
        $info_article_type_name = $value['info_article_type_name'];
        $info_article_title = $value['info_article_title'];
        $info_article_cover = $value['info_article_cover'];
        $info_article_order = $value['info_article_order'];
        $info_article_status = $value['info_article_status'];

        $info_article_type = ModelInfoArticleType::where('info_article_type_name', $info_article_type_name)->find();
        if (!$info_article_type) throwErrorMsg($info_article_type_name . "不存在,请重新确认！");
        $info_article_type_guid = $info_article_type->info_article_type_guid;

        $show_status = ModelDictionary::getDictionaryData('show_status');
        $info_article_status =  ModelDictionary::getDataDictionaryValue($show_status, $info_article_status);

        return self::create([
            'info_article_type_guid' => $info_article_type_guid,
            'info_article_title' => $info_article_title,
            'info_article_cover' => $info_article_cover,
            'info_article_order' => $info_article_order,
            'info_article_status' => $info_article_status,
        ]);
    }

    /**
     * 构建前台首页新闻接口数据
     */
    public static function buildApiHomeInfoArticleList(array $info_article_data): array
    {
        $info_article_type_arr = [];
        $info_article_arr = [];
        $data = [];

        //【步骤一】新闻标题数组构建
        foreach ($info_article_data as $info_article) {
            $info_article_type_name = $info_article['info_article_type_name'];
            $info_article_type_sort = $info_article['info_article_type_sort'];
            if (!in_array($info_article_type_name, $info_article_type_arr)) {
                $info_article_type_arr[$info_article_type_sort] =  $info_article_type_name;
            }
        };
        //新闻标题数组按照下标升序处理
        ksort($info_article_type_arr);
        //排序后，只保留值
        $info_article_type_arr = array_values($info_article_type_arr);

        //【步骤二】新闻数组构建
        foreach ($info_article_data as $info_article) {
            $info_article_type_name = $info_article['info_article_type_name'];
            $info_article_order = $info_article['info_article_order'];
            $info_article_arr[$info_article_type_name][$info_article_order] = $info_article;
        };
        //新闻标题数组按照下标升序处理
        foreach ($info_article_arr as &$info_article) {
            ksort($info_article);
            //排序后，只保留值
            $info_article = array_values($info_article);
        };

        //【步骤二】最终数据合并
        //类型名称数据构建
        foreach ($info_article_type_arr as $info_article_type_name) {
            $data[$info_article_type_name] = [];
        };
        //文章数据匹配添加
        foreach ($info_article_data as $info_article) {
            $info_article_type_name = $info_article['info_article_type_name'];
            $data[$info_article_type_name][] = $info_article;
        };

        return $data;
    }
}
