<?php

namespace addons\shopro\controller\user;

use addons\shopro\controller\Common;
use app\admin\model\shopro\commission\Agent as AgentModel;

class Agent extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 申请成为代理商
     * POST /addons/shopro/user.agent/agentapply
     */
    public function agentapply()
    {
        if (!$this->request->isPost()) {
            $this->error('');
        }

        $user = auth_user();
        $userId = $user->id ?? 0;
        custom_log('[agent.apply] 收到代理申请请求, user_id=' . $userId, $userId, 'share');

        // 校验消费累计条件
        $commissionConfig = new \addons\shopro\service\commission\Config();
        $becomeAgentEvent = $commissionConfig->getBecomeAgentEvent();
        if ($becomeAgentEvent['type'] === 'consume') {
            $requiredConsume = $becomeAgentEvent['value'] ?? 0;
            $userConsume = floatval($user->total_consume ?? 0);
            if ($userConsume < $requiredConsume) {
                custom_log('[agent.apply] 消费金额不足, user_id=' . $userId . ', 累计消费=' . $userConsume . ', 要求=' . $requiredConsume, $userId, 'share', 'warning');
                $this->error('累计消费未达到申请要求，当前累计消费 ¥' . $userConsume . '，需达到 ¥' . $requiredConsume);
            }
        }

        $params = $this->request->only(['real_name', 'id_card', 'id_card_images']);
        custom_log('[agent.apply] 解析参数: ' . json_encode($params, JSON_UNESCAPED_UNICODE), $userId, 'share');

        $this->svalidate($params, '.agentApply');
        custom_log('[agent.apply] 参数校验通过', $userId, 'share');

        $service = new \addons\shopro\service\agent\ApplyService($user);
        try {
            $apply = $service->submit($params);
            custom_log('[agent.apply] 代理申请成功, apply_id=' . ($apply->id ?? ''), $userId, 'share');
            $this->success('申请已提交，请等待审核', $apply);
        } catch (\think\Exception $e) {
            custom_log('[agent.apply] 代理申请失败: ' . $e->getMessage(), $userId, 'share', 'warning');
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取代理商详情
     * GET /addons/shopro/user.agent/detail
     */
    public function detail()
    {
        $user = auth_user();
        $userId = $user->id ?? 0;

        $agent = \app\admin\model\shopro\agent\Agent::where('user_id', $userId)
            ->where('status', \app\admin\model\shopro\agent\Agent::STATUS_NORMAL)
            ->field('id,user_id,province_name,real_name,id_card,id_card_images,commission_rate,total_commission,status,apply_id,createtime')
            ->find();

        if (!$agent) {
            $this->error('数据不存在');
        }

        $this->success('成功', $agent);
    }
}
