<?php
declare (strict_types = 1);

namespace app\admin\validate\v1;

use app\admin\model\v1\AttachmentCategoryModel;
use think\facade\Db;
use think\Validate;

class AttachmentCategoryValidate extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'id'          => 'require|integer',
        'pid'         => 'integer|checkPidNotBeChildren',
        'language_id' => 'require|integer',
        'name'        => 'require|max:64',
        'sort'        => 'integer',
        'is_show'     => 'in:0,1',
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
        'id.require'                => 'ID不能为空',
        'id.integer'                => 'ID必须是整数',
        'pid.integer'               => '父级ID必须是整数',
        'pid.checkPidNotBeChildren' => '父级分类不能为自身或自身的子分类',
        'language_id.require'       => '语言ID不能为空',
        'language_id.integer'       => '语言ID必须是整数',
        'name.require'              => '名称不能为空',
        'name.max'                  => '名称不能超过64个字符',
        'sort.integer'              => '排序必须是整数',
        'is_show.in'                => '是否显示必须是0或1',
    ];

    // 验证pid
    protected function checkPidNotBeChildren($value, $rule, $data = [])
    {
        if ($value == 0) {
            return true;
        }

        $children   = [];
        $table_name = (new AttachmentCategoryModel)->getTable();
        if (env('DB_VERSION', '5') == '8') {
            $children = Db::query(
                preg_replace(
                    '/\s+/u', 
                    ' ',
                    "WITH RECURSIVE attachment_tree_by AS (
                        SELECT a.id, a.pid FROM $table_name a WHERE a.id = {$data['id']}
                        UNION ALL
                        SELECT k.id, k.pid FROM $table_name k INNER JOIN attachment_tree_by t ON t.id = k.pid
                    )
                    SELECT id FROM attachment_tree_by WHERE id <> {$data['id']};"
                )
            );
        } else {
            $children = \think\facade\Db::query("
                SELECT t2.id
                    FROM ( 
                        SELECT 
                            @r AS _id, (SELECT @r := GROUP_CONCAT(id) FROM $table_name WHERE FIND_IN_SET(pid, _id)) AS parent_id
                        FROM 
                            (SELECT @r := {$data['id']}) vars, $table_name h 
                        WHERE @r <> 0) t1 
                    JOIN $table_name t2 
                    ON FIND_IN_SET(t2.pid, t1._id)
                ORDER BY t2.id;
            ");
        }
        if (!empty($children) && in_array($data['pid'], array_column($children, 'id'))) {
            return false;
        }

        return true;
    }

    /**
     * 新增场景
     */
    public function sceneCreate()
    {
        return $this->remove('id', 'require|integer')->remove('pid', 'checkPidNotBeChildren');
    }

    /**
     * 更新场景
     */
    public function sceneUpdate()
    {
        return $this->remove('language_id', 'require|integer');
    }

    /**
     * 排序场景
     */
    public function sceneSort()
    {
        return $this->only(['sort']);
    }
}
