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

use app\service\StorageService;
use app\service\api\BaseApiService;
use app\service\domain\user\CoreUserVerifyService;
use think\facade\Log;
use think\Request;


/**
 * User Verify Service
 * @package app\service\api\user
 */
class UserVerifyService extends BaseApiService
{

    /**
     * 提交认证申请
     * @param Request $request 请求对象
     * @return array
     */
    public function submit(Request $request): array
    {
        $uid = (int)($request->uid ?? 0);
        if ($uid <= 0) {
            return ['code' => 401, 'msg' => '', '_http_status' => 401];
        }

        try {
            return $this->core()->submit($uid, [
                'user_type' => (int)$request->post('user_type', 1),
                'realname' => trim((string)$request->post('realname', '')),
                'company_name' => trim((string)$request->post('company_name', '')),
                'id_card_no' => trim((string)$request->post('id_card_no', '')),
                'id_card_front' => $this->resolveAsset($request->file('id_card_front'), (string)$request->post('id_card_front', '')),
                'id_card_back' => $this->resolveAsset($request->file('id_card_back'), (string)$request->post('id_card_back', '')),
                'business_license' => $this->resolveAsset($request->file('business_license'), (string)$request->post('business_license', '')),
            ]);
        } catch (\Throwable $e) {
            Log::error('api user verify failed: ' . $e->getMessage(), ['uid' => $uid]);
            return ['code' => 1, 'msg' => ''];
        }
    }

    /**
     * 解析认证附件（支持文件上传和已上传路径两种方式）
     * @param \think\File|null $file 上传文件对象
     * @param string $postedValue 已上传文件路径
     * @return string 存储路径
     */
    private function resolveAsset(?\think\File $file, string $postedValue): string
    {
        if ($file instanceof \think\File) {
            return $this->saveUploadedFileToPublicStorage($file, 'verify');
        }
        return $this->normalizePostedAsset($postedValue);
    }

    /**
     * 将上传文件保存至公共存储目录
     * @param \think\File $file 上传文件
     * @param string $subDir 子目录名
     * @return string 存储相对路径
     */
    private function saveUploadedFileToPublicStorage(\think\File $file, string $subDir): string
    {
        $normalizedDir = trim(str_replace('\\', '/', $subDir), '/');
        if ($normalizedDir === '') {
            $normalizedDir = 'verify';
        }
        $targetDir = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $normalizedDir);
        $saved = $file->move($targetDir);
        return '/storage/' . $normalizedDir . '/' . $saved->getFilename();
    }

    /**
     * 归一化已上传附件路径
     * @param string $value 原始路径值
     * @return string 归一化后的路径
     */
    private function normalizePostedAsset(string $value): string
    {
        $raw = trim($value);
        if ($raw === '') {
            return '';
        }
        if (str_starts_with($raw, '/storage/')) {
            return StorageService::normalizeAttachmentValue($raw);
        }
        if (preg_match('/^https?:\/\//i', $raw) === 1 && strpos($raw, '/storage/') !== false) {
            return StorageService::normalizeAttachmentValue($raw);
        }
        return '';
    }

    /**
     * 获取用户认证核心服务实例
     * @return CoreUserVerifyService
     */
    private function core(): CoreUserVerifyService
    {
        return $this->app->make(CoreUserVerifyService::class);
    }
}