package com.jeesharp.business.modules.member.application;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.member.convert.MemberVipConvert;
import com.jeesharp.business.modules.member.dto.MemberVipSaveDTO;
import com.jeesharp.business.modules.member.entity.Member;
import com.jeesharp.business.modules.member.entity.MemberLevel;
import com.jeesharp.business.modules.member.entity.MemberVip;
import com.jeesharp.business.modules.member.enums.MemberVipStatusEnum;
import com.jeesharp.business.modules.member.service.MemberLevelService;
import com.jeesharp.business.modules.member.service.MemberService;
import com.jeesharp.business.modules.member.service.MemberVipService;
import com.jeesharp.business.modules.member.vo.MemberVipInfoVO;
import com.jeesharp.business.modules.member.vo.MemberVipQueryVO;
import com.jeesharp.framework.exception.BizErrorException;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员付费开通应用服务
 *
 * @author jeesharp
 * @version 2026-03-19
 */
@Service
@Transactional
@AllArgsConstructor
public class MemberVipApplicationService {

    private final MemberVipService memberVipService;
    private final MemberService memberService;
    private final MemberLevelService memberLevelService;

    /**
     * 获取付费等级下拉选项（用于开通时选择）
     *
     * @return 选项列表 [{ value: levelCode, label: levelName }]
     */
    @Transactional(readOnly = true)
    public List<Map<String, String>> getPaidLevelOptions() {
        List<MemberLevel> list = memberLevelService.listPaidLevels();
        List<Map<String, String>> options = new ArrayList<>();
        for (MemberLevel level : list) {
            Map<String, String> item = new HashMap<>();
            item.put("value", level.getLevelCode());
            item.put("label", level.getLevelName());
            options.add(item);
        }
        return options;
    }

    /**
     * 获取付费开通记录详情
     *
     * @param id 记录ID
     * @return 详情VO
     */
    @Transactional(readOnly = true)
    public MemberVipInfoVO getMemberVip(String id) {
        MemberVip entity = memberVipService.get(id);
        if (entity == null) {
            throw new BizErrorException("付费开通记录不存在");
        }
        MemberVipInfoVO vo = MemberVipConvert.INSTANCE.toInfoVO(entity);
        fillMemberAndLevelInfo(vo, entity);
        return vo;
    }

    /**
     * 分页查询付费开通记录
     *
     * @param page  分页对象
     * @param query 查询条件
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public PageRespVO<MemberVipInfoVO> findPage(Page<MemberVip> page, MemberVipQueryVO query) {
        Page<MemberVip> result = memberVipService.findPage(page, query);
        List<MemberVipInfoVO> voList = result.getRecords().stream()
                .map(MemberVipConvert.INSTANCE::toInfoVO)
                .toList();
        for (int i = 0; i < voList.size(); i++) {
            fillMemberAndLevelInfo(voList.get(i), result.getRecords().get(i));
        }
        PageRespVO<MemberVipInfoVO> pageResp = new PageRespVO<>();
        pageResp.setRecords(voList);
        pageResp.setTotal(result.getTotal());
        pageResp.setPageNo(result.getPageNo());
        pageResp.setPageSize(result.getPageSize());
        return pageResp;
    }

    /**
     * 开通付费会员
     *
     * @param dto 开通请求
     * @return 开通记录详情
     */
    public MemberVipInfoVO openVip(MemberVipSaveDTO dto) {
        Member member = memberService.get(dto.getMemberId());
        if (member == null) {
            throw new BizErrorException("会员不存在");
        }
        MemberLevel level = memberLevelService.getByLevelCode(dto.getLevelCode());
        if (level == null || level.getIsPaidLevel() == null || level.getIsPaidLevel() != 1) {
            throw new BizErrorException("付费等级不存在或非付费等级");
        }
        MemberVip entity = MemberVipConvert.INSTANCE.fromSaveDTO(dto);
        entity.setStatus(MemberVipStatusEnum.ACTIVE.getValue());
        MemberVip saved = memberVipService.openVip(entity);
        return getMemberVip(saved.getId());
    }

    /**
     * 取消付费开通
     *
     * @param id 记录ID
     */
    public void cancelVip(String id) {
        MemberVip entity = memberVipService.get(id);
        if (entity == null) {
            throw new BizErrorException("付费开通记录不存在");
        }
        if (!MemberVipStatusEnum.ACTIVE.getValue().equals(entity.getStatus())) {
            throw new BizErrorException("当前状态无法取消");
        }
        memberVipService.cancelVip(id);
    }

    /**
     * 查询某会员的开通历史
     *
     * @param memberId 会员ID
     * @return 开通记录列表
     */
    @Transactional(readOnly = true)
    public List<MemberVipInfoVO> listByMemberId(String memberId) {
        List<MemberVip> list = memberVipService.listByMemberId(memberId);
        List<MemberVipInfoVO> voList = list.stream()
                .map(MemberVipConvert.INSTANCE::toInfoVO)
                .toList();
        for (int i = 0; i < voList.size(); i++) {
            fillMemberAndLevelInfo(voList.get(i), list.get(i));
        }
        return voList;
    }

    /**
     * 填充会员和等级信息到 VO
     */
    private void fillMemberAndLevelInfo(MemberVipInfoVO vo, MemberVip entity) {
        if (StrUtil.isNotBlank(entity.getMemberId())) {
            Member member = memberService.get(entity.getMemberId());
            if (member != null) {
                vo.setMemberNo(member.getMemberNo());
                vo.setMemberNickname(member.getNickname());
            }
        }
        if (StrUtil.isNotBlank(entity.getLevelCode())) {
            MemberLevel level = memberLevelService.getByLevelCode(entity.getLevelCode());
            if (level != null) {
                vo.setLevelName(level.getLevelName());
            }
        }
    }
}
