<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\domain\user;

use app\event\user\UserVerified;
use app\repository\user\UserRepository;
use app\repository\user\UserVerifyProfileRepository;
use Core\service\BaseCoreService;
use think\facade\Event;

/**
 * 用户验证服务
 * Class CoreUserVerifyService
 * @package app\service\domain\user
 */
class CoreUserVerifyService extends BaseCoreService
{
    /**
     * 提交用户验证信息
     * @param int $userId 用户ID
     * @param array $payload 更新数据
     * @return array
     */
    public function submit(int $userId, array $payload): array
    {
        $realname = trim((string)($payload['realname'] ?? ''));
        $companyName = trim((string)($payload['company_name'] ?? ''));
        $idCardNo = trim((string)($payload['id_card_no'] ?? ''));
        $userType = (int)($payload['user_type'] ?? 1);
        $idCardFront = trim((string)($payload['id_card_front'] ?? ''));
        $idCardBack = trim((string)($payload['id_card_back'] ?? ''));
        $businessLicense = trim((string)($payload['business_license'] ?? ''));

        if ($realname === '') {
            return ['code' => 1, 'msg' => ''];
        }
        if ($idCardNo === '' || preg_match('/(^\d{15}$)|(^\d{17}[\dXx]$)/', $idCardNo) !== 1) {
            return ['code' => 1, 'msg' => ''];
        }
        if ($idCardFront === '') {
            return ['code' => 1, 'msg' => ''];
        }
        if ($idCardBack === '') {
            return ['code' => 1, 'msg' => ''];
        }
        if ($userType === 2 && $businessLicense === '') {
            return ['code' => 1, 'msg' => ''];
        }

        $user = $this->userRepository()->findById($userId);
        if (!$user) {
            return ['code' => 1, 'msg' => ''];
        }

        $profile = $this->verifyProfileRepository()->findByUserId($userId);
        if (!$profile) {
            $profile = $this->verifyProfileRepository()->newModel($userId);
        }

        $profile->user_type = in_array($userType, [1, 2], true) ? $userType : 1;
        $profile->realname = $realname;
        $profile->company_name = $companyName;
        $profile->id_card_no = $idCardNo;
        $profile->id_card_front = $idCardFront;
        $profile->id_card_back = $idCardBack;
        $profile->business_license = $profile->user_type === 2 ? $businessLicense : '';
        $profile->verify_remark = '';
        $profile->save();

        $user->verify_status = 1;
        $user->save();

        return ['code' => 0, 'msg' => ''];
    }

    /**
     * 审核用户验证信息
     * @param int $userId 用户ID
     * @param string $action 操作类型（pass/reject/cancel）
     * @param string $remark 备注（可选）
     * @return array
     */
    public function review(int $userId, string $action, string $remark = ''): array
    {
        $user = $this->userRepository()->findById($userId);
        if (!$user) {
            return ['code' => 1, 'msg' => ''];
        }

        $profile = $this->verifyProfileRepository()->findByUserId($userId);
        if (!$profile) {
            return ['code' => 1, 'msg' => ''];
        }

        if ($action === 'pass') {
            $user->verify_status = 2;
        } elseif ($action === 'reject') {
            $user->verify_status = 3;
        } elseif ($action === 'cancel') {
            $user->verify_status = 1;
        } else {
            return ['code' => 1, 'msg' => ''];
        }

        $user->save();
        $profile->verify_remark = $action === 'cancel' ? '' : mb_substr($remark, 0, 255);
        $profile->save();

        if ($action === 'pass') {
            Event::trigger(new UserVerified($userId, (string)$profile->verify_remark));
        }

        return ['code' => 0, 'msg' => ''];
    }

    /**
     * 获取用户仓储实例
     * @return UserRepository
     */
    private function userRepository(): UserRepository
    {
        return $this->app->make(UserRepository::class);
    }

    /**
     * 获取用户验证资料仓储实例
     * @return UserVerifyProfileRepository
     */
    private function verifyProfileRepository(): UserVerifyProfileRepository
    {
        return $this->app->make(UserVerifyProfileRepository::class);
    }
}