<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\adminapi\service;

use app\common\exception\BaseException;
use app\common\model\Category as CategoryModel;
use app\common\library\utils\Image;
use app\common\library\utils\Data as DataUtils;

/**
 * @package app\adminapi\service
 * @class Category
 * @author xzncit 2023-09-04
 */
class Category {

    /**
     * 获取列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params = []){
        $array = [];
        $list  = CategoryModel::where("module",$params["module"])->where("pid",intval($params["id"]??0))->order('id','asc')->select()->toArray();
        foreach($list as $key=>$value){
            $array[$key]                  = $value;
            $array[$key]["photo"]         = Image::thumb($value["photo"]);
            $array[$key]["hasChildren"]   = CategoryModel::where("module",$params["module"])->where("pid",$value["id"])->count() ? true : false;
        }

        return $array;
    }

    /**
     * 详情
     * @param $id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        $row = CategoryModel::where("id",$id)->find();
        $array = [];
        if(empty($row)){
            return $array;
        }

        $path             = array_map(function ($num){ return (int)$num; },explode(",",$row["path"]));
        array_pop($path);
        $array["cat_id"]  = $path;
        $array["title"]   = $row["title"];
        $array["sort"]    = $row["sort"];
        $array["status"]  = $row["status"];
        $array["id"]      = $row["id"];
        $array["photo"]   = !empty($row["photo"]) ? Image::thumb($row["photo"]) : "";
        $array["content"] = Image::replace(Image::removeAttribute($row["content"]),function($path,$content){
            return str_replace($path, Image::thumb($path), $content);
        });

        return $array;
    }

    /**
     * 添加/编辑
     * @param $data
     * @return bool
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function save($data){
        if(empty($data["cat_id"])){
            $data["cat_id"] = [];
        }

        $data["pid"]    = empty($data["cat_id"]) ? 0 : end($data["cat_id"]);
        $data["photo"]  = Image::parseUrl($data["photo"]??"");
        if(!empty($data["content"])){
            $data["content"] = Image::replace(Image::removeAttribute($data["content"]),function($path,$content){
                return str_replace($path, Image::parseUrl($path), $content);
            });
        }
        if(!empty($data["id"]) && $res=CategoryModel::where("id",$data["id"])->find()){
            $result = CategoryModel::where("module",$data["module"])->select()->toArray();
            if(!DataUtils::checkTree($result,$data)){
                throw new BaseException("{$data['title']} 是 ID {$data['pid']} 的父栏目,不能修改！",0);
            }

            if($res["id"] == $data["pid"]){
                throw new BaseException("不允许选择上一级作为分类",0);
            }

            $data["cat_id"][]       = $data["id"];
            $data["path"]           = implode(",",$data["cat_id"]);
            $data["update_time"]    = time();
            (new CategoryModel())->where("id",$data["id"])->save($data);
        }else{
            $data["create_time"]    = time();
            $data["update_time"]    = time();
            $data["id"]             = (new CategoryModel())->withoutField("id")->insert($data,true);
            $data["cat_id"][]       = $data["id"];
            $data["path"]           = implode(",",$data["cat_id"]);
            (new CategoryModel())->where("id",$data["id"])->save($data);
        }

        return true;
    }

    public static function parent($id,$res=[]){
        $row = CategoryModel::where("id",$id)->find();

        if(!empty($row)){
            $res[] = $row["id"];
            if($row["pid"] != 0){
                $res = array_merge(self::parent($row["pid"],$res));
            }
        }

        return $res;
    }

    /**
     * 修改状态
     * @param $params
     * @return bool
     * @throws BaseException
     */
    public static function status($params){
        if(!in_array($params["type"],["status","is_menu"])){
            throw new BaseException("error status",0);
        }

        $data = [ $params["type"]=>intval($params["value"]??0) ];
        CategoryModel::where("id",$params["id"]??0)->update($data);
        return true;
    }

    /**
     * 删除
     * @param $id
     * @return bool
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function delete($id){
        if(CategoryModel::where("pid",$id)->count() > 0){
            throw new BaseException("该分类下有子分类，请先删除子分类。",0);
        }

        $condition = ["id"=>$id];
        $row = CategoryModel::where($condition)->find();
        if(empty($row)){
            throw new BaseException("您要删除的内容不存在",0);
        }else if($row["is_lock"] == 1){
            throw new BaseException("该内容您无权删除",0);
        }

        CategoryModel::where($condition)->delete();
        return true;
    }

}