<?php

namespace addons\shopro\service\agent;

use think\Db;
use app\admin\model\shopro\agent\Apply as ApplyModel;
use app\admin\model\shopro\agent\Agent as AgentModel;
use app\admin\model\shopro\data\Area as AreaModel;

class ApplyService
{
    protected $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * 提交代理申请
     */
    public function submit($params)
    {
        $userId = $this->user->id;

        // 1. 校验是否已有申请中的记录
        $existApply = ApplyModel::where('user_id', $userId)
            ->where('status', ApplyModel::STATUS_PENDING)
            ->find();
        if ($existApply) {
            throw new \think\Exception('您已提交过代理申请，正在审核中，请耐心等待');
        }

        // 2. 校验是否已经是代理商
        $existAgent = AgentModel::where('user_id', $userId)
            ->where('status', AgentModel::STATUS_NORMAL)
            ->find();
        if ($existAgent) {
            throw new \think\Exception('您已是代理商，无需重复申请');
        }

        // 3. 写入申请记录
        $apply = ApplyModel::create([
            'user_id' => $userId,
            'real_name' => $params['real_name'],
            'id_card' => $params['id_card'],
            'id_card_images' => $params['id_card_images'] ?? [],
            'status' => ApplyModel::STATUS_PENDING,
        ]);

        custom_log('[agent.apply] 代理申请提交成功, apply_id=' . $apply->id . ', user_id=' . $userId, $userId, 'share');

        return $apply;
    }
}
