<?php

namespace app\api\validate;

use app\model\Project;

class ProjectValidate extends BaseValidate
{
    protected $rule = [
        'searchKeyWords' => 'require',
        'category_id' => 'require|number',
        'project_id' => 'require|number',
        'type' => 'require|number',
        'name' => 'require',
        'idcard' => 'require|number',
        'idcard_q' => 'require|number',
        'idcard_h' => 'require|number',
        'mobile' => 'require|mobile',
        'email' => 'require|email',
        'head_img_id' => 'require|number',
        'other_file_id' => 'require|number',
        'pay_type'=>'require|number',
        'project_put_id'=>'require|number',
        'complete_file_id_str'=>'require',
        'project_name'=>'require',
        'tag_ids'=>'require',
        'yusuan'=>'require',
        'zhouqi'=>'require',
        'description'=>'require',
        'content'=>'require',
        'file_id_str'=>'require',
        'cate_id'=>'require|number',
        'title'=>'require|checktitle',
        'user_id'=>'require|number',
        'pid'=>'require|number',
        'put_end_time'=>'require',
        'reason'=>'require',
    ];
    protected $message = [
        'title.require' => '项目名不能为空',
        'title.checktitle' => '项目名重复',
    ];

    protected function checktitle($value, $rule, $data=[])
    {
        $userId = request()->userId;
        // 如果是编辑操作（有传递ID）
        if (!empty($data['project_id'])) {
            $originalTitle = Project::where('id', $data['project_id'])
                ->value('title');

            // 如果标题没有改变，直接通过验证
            if ($originalTitle === $value) {
                return true;
            }

            $result = Project::where('title', $value)
                ->where('user_id', $userId)
                ->where('id', '<>', $data['project_id']) // 排除当前项目
                ->count();

            return !$result;
        }
        $result = Project::where(['title' => $value, 'user_id' => $userId])->count();
        if ($result) return false;

        return true;
    }

}