package cn.iocoder.hake.module.agent.service.agent;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.hake.module.agent.enums.agent.AuditStatusEnum;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.text.SimpleDateFormat;
import java.util.*;
import cn.iocoder.hake.module.agent.controller.admin.agent.vo.*;
import cn.iocoder.hake.module.agent.dal.dataobject.agent.AgentDO;
import cn.iocoder.hake.framework.common.pojo.PageResult;

import cn.iocoder.hake.framework.common.util.object.BeanUtils;

import cn.iocoder.hake.module.agent.dal.mysql.agent.AgentMapper;

import static cn.iocoder.hake.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.hake.module.agent.enums.ErrorCodeConstants.*;

/**
 * 代理商管理 Service 实现类
 *
 * @author hake
 */
@Service
@Validated
public class AgentServiceImpl implements AgentService {

    @Resource
    private AgentMapper agentMapper;

    @Override
    public Long createAgent(AgentSaveReqVO createReqVO) {
        // 插入
        AgentDO agent = BeanUtils.toBean(createReqVO, AgentDO.class);
        agent.setStatus(AuditStatusEnum.UNVERIFIED.getCode());
        agent.setAgentCode(erateAgentCode(new StringBuilder("AGT")));
        agentMapper.insert(agent);
        // 返回
        return agent.getId();
    }

    /**
     * 生成代理商编码
     * @return 格式如"AGT202507301234"的代理商编码
     */
    public static String erateAgentCode(StringBuilder codeHeadStr) {
        if(codeHeadStr == null || codeHeadStr.length() == 0) {
            codeHeadStr=new StringBuilder("ST");
        }
        // 固定前缀
        StringBuilder codeBuilder = new StringBuilder(codeHeadStr);
        // 添加当前日期（yyyyMMdd格式）
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(new Date());
        codeBuilder.append(dateStr);

        // 生成4个随机数（0000-9999）
        Random random = new Random();
        // 生成0-9999的随机数，并补全为4位数字
        int randomNum = random.nextInt(10000);
        codeBuilder.append(String.format("%04d", randomNum));
        return codeBuilder.toString();
    }

    @Override
    public Long updateAgentStatus( AuditRespVO auditRespVO) {
        // 校验存在
        validateagentExists(auditRespVO.getId());
        // 更新
        AgentDO updateObj = BeanUtils.toBean(auditRespVO, AgentDO.class);
        agentMapper.updateById(updateObj);
        return auditRespVO.getId();
    }


    @Override
    public void updateAgent(AgentSaveReqVO updateReqVO) {
        // 校验存在
        AgentDO agentDO  =validateagentExists(updateReqVO.getId());
        //如果当前为未认证、审核驳回的状态，再次修改提交后应该变成待审核状态
        if(Objects.equals(agentDO.getStatus(), AuditStatusEnum.REJECTED.getCode()) || Objects.equals(agentDO.getStatus(), AuditStatusEnum.UNVERIFIED.getCode())) {
            updateReqVO.setStatus(AuditStatusEnum.UNDER_REVIEW.getCode());
        }
        // 更新
        AgentDO updateObj = BeanUtils.toBean(updateReqVO, AgentDO.class);
        agentMapper.updateById(updateObj);
    }


    @Override
    public void deleteAgent(Long id) {
        // 校验存在
        validateagentExists(id);
        // 删除
        agentMapper.deleteById(id);
    }

    @Override
        public void deleteAgentListByIds(List<Long> ids) {
        // 校验存在
        validateAgentExists(ids);
        // 删除
        agentMapper.deleteByIds(ids);
        }

    private void validateAgentExists(List<Long> ids) {
        List<AgentDO> list = agentMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(AGENT_NOT_EXISTS);
        }
    }

    private AgentDO validateagentExists(Long id) {
        AgentDO agentDO  =agentMapper.selectById(id);
        if (agentDO == null) {
            throw exception(AGENT_NOT_EXISTS);
        }
        return agentDO;
    }

    @Override
    public AgentDO getAgent(Long id) {
        return agentMapper.selectById(id);
    }

    @Override
    public PageResult<AgentDO> getAgentPage(AgentPageReqVO pageReqVO) {
        return agentMapper.selectPage(pageReqVO);
    }

}