<?php

namespace addons\shopro\controller\user;

use addons\shopro\controller\Common;
use app\admin\model\shopro\agent\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');

        // 校验是否已有代理商记录
        $existAgent = AgentModel::where('user_id', $userId)->find();
        if ($existAgent) {
            $statusText = (new AgentModel)->statusList()[$existAgent->status] ?? $existAgent->status;
            custom_log('[agent.apply] 已存在代理商记录, agent_id=' . $existAgent->id . ', status=' . $existAgent->status, $userId, 'share', 'warning');
            $this->error("您已是代理商，当前状态：{$statusText}");
        }

        // 校验消费累计条件
        $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;

        $agentModel = new AgentModel();
        $agent = $agentModel
            ->where('user_id', $userId)
            ->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('您还不是代理商');
        // }

        // 冻结或禁用状态不允许查看详情
        $allowStatus = [AgentModel::STATUS_NORMAL];
        if (!in_array($agent->status, $allowStatus)) {
            $statusText = $agentModel->statusList()[$agent->status] ?? $agent->status;
            $this->error("代理商状态{$statusText}，不可查看详情");
        }

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