package com.ruoyi.web.modules.account.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.account.constant.MemberConstants;
import com.ruoyi.web.modules.account.domain.BizMember;
import com.ruoyi.web.modules.account.domain.BizMemberAddress;
import com.ruoyi.web.modules.account.domain.BizMemberLevel;
import com.ruoyi.web.modules.account.dto.MemberCreateDTO;
import com.ruoyi.web.modules.account.dto.MemberOrderQueryDTO;
import com.ruoyi.web.modules.account.dto.MemberStatusDTO;
import com.ruoyi.web.modules.account.facade.IOrderFacade;
import com.ruoyi.web.modules.account.mapper.BizMemberAddressMapper;
import com.ruoyi.web.modules.account.mapper.BizMemberLevelMapper;
import com.ruoyi.web.modules.account.mapper.BizMemberMapper;
import com.ruoyi.web.modules.account.service.IMemberService;
import com.ruoyi.web.modules.account.support.MemberRegistrationSupport;
import com.ruoyi.web.modules.account.util.MemberMobileUtils;
import com.ruoyi.web.modules.account.vo.MemberAddressVO;
import com.ruoyi.web.modules.account.vo.MemberDetailVO;
import com.ruoyi.web.modules.account.vo.MemberLevelVO;
import com.ruoyi.web.modules.account.vo.MemberListVO;

/**
 * 平台端会员 Service 实现
 */
@Service
public class MemberServiceImpl implements IMemberService
{
    @Autowired
    private BizMemberMapper memberMapper;

    @Autowired
    private BizMemberLevelMapper memberLevelMapper;

    @Autowired
    private BizMemberAddressMapper addressMapper;

    @Autowired
    private IOrderFacade orderFacade;

    @Autowired
    private MemberRegistrationSupport memberRegistrationSupport;

    @Override
    public List<MemberListVO> selectMemberList(BizMember query)
    {
        if (query == null)
        {
            query = new BizMember();
        }
        query.setMemberRoleKey(MemberConstants.MEMBER_ROLE_KEY);
        List<BizMember> list = memberMapper.selectList(query);
        Map<Integer, BizMemberLevel> levelMap = buildLevelMap();
        List<MemberListVO> rows = new ArrayList<>();
        for (BizMember m : list)
        {
            rows.add(toListVo(m, true, levelMap));
        }
        return rows;
    }

    @Override
    public List<MemberLevelVO> selectMemberLevelList()
    {
        List<MemberLevelVO> rows = new ArrayList<>();
        for (BizMemberLevel level : memberLevelMapper.selectEnabledList())
        {
            rows.add(toLevelVo(level));
        }
        return rows;
    }

    @Override
    public MemberDetailVO selectMemberDetail(Long memberId)
    {
        BizMember member = memberMapper.selectById(memberId);
        if (member == null)
        {
            throw new ServiceException("会员不存在");
        }
        MemberDetailVO vo = new MemberDetailVO();
        vo.setMemberId(member.getMemberId());
        vo.setMemberCode(member.getMemberCode());
        vo.setNickName(member.getNickName());
        vo.setMobile(member.getMobile());
        fillMemberLevel(vo, member, buildLevelMap());
        vo.setStatus(member.getStatus());
        vo.setOrderCount(member.getOrderCount());
        vo.setTotalAmount(member.getTotalAmount());
        vo.setRegisterTime(member.getRegisterTime());
        vo.setAvatar(member.getAvatar());
        List<BizMemberAddress> addresses = addressMapper.selectByMemberId(memberId);
        for (BizMemberAddress addr : addresses)
        {
            vo.getAddressList().add(toAddressVo(addr));
        }
        return vo;
    }

    @Override
    public Long createMember(MemberCreateDTO dto, String operator)
    {
        Long memberId = memberRegistrationSupport.createMember(dto, operator);
        return memberId;
    }

    @Override
    public void updateMemberStatus(Long memberId, MemberStatusDTO dto, String operator)
    {
        if (dto == null || StringUtils.isEmpty(dto.getStatus()))
        {
            throw new ServiceException("状态不能为空");
        }
        if (!MemberConstants.STATUS_ENABLED.equals(dto.getStatus())
                && !MemberConstants.STATUS_DISABLED.equals(dto.getStatus()))
        {
            throw new ServiceException("状态参数无效");
        }
        BizMember member = memberMapper.selectById(memberId);
        if (member == null)
        {
            throw new ServiceException("会员不存在");
        }
        memberMapper.updateStatus(memberId, dto.getStatus(), operator);
    }

    @Override
    public TableDataInfo selectMemberOrders(Long memberId, MemberOrderQueryDTO query)
    {
        assertMemberExists(memberId);
        TableDataInfo data = orderFacade.pageOrdersByMember(memberId, query);
        if (data.getRows() != null)
        {
            for (Object row : data.getRows())
            {
                if (row instanceof java.util.Map)
                {
                    @SuppressWarnings("unchecked")
                    java.util.Map<String, Object> map = (java.util.Map<String, Object>) row;
                    map.put("operateType", "readonly");
                }
            }
        }
        return data;
    }

    @Override
    public Object selectMemberOrderDetail(Long memberId, Long orderId)
    {
        assertMemberExists(memberId);
        return orderFacade.getOrderDetail(memberId, orderId);
    }

    private void assertMemberExists(Long memberId)
    {
        if (memberMapper.selectById(memberId) == null)
        {
            throw new ServiceException("会员不存在");
        }
    }

    private MemberListVO toListVo(BizMember m, boolean maskMobile, Map<Integer, BizMemberLevel> levelMap)
    {
        MemberListVO vo = new MemberListVO();
        vo.setMemberId(m.getMemberId());
        vo.setMemberCode(m.getMemberCode());
        vo.setNickName(m.getNickName());
        vo.setMobile(maskMobile ? MemberMobileUtils.mask(m.getMobile()) : m.getMobile());
        fillMemberLevel(vo, m, levelMap);
        vo.setStatus(m.getStatus());
        String label = DictUtils.getDictLabel(MemberConstants.DICT_MEMBER_STATUS, m.getStatus());
        if (StringUtils.isEmpty(label))
        {
            label = MemberConstants.STATUS_ENABLED.equals(m.getStatus()) ? "启用" : "禁用";
        }
        vo.setStatusLabel(label);
        vo.setOrderCount(m.getOrderCount());
        vo.setTotalAmount(m.getTotalAmount());
        vo.setRegisterTime(m.getRegisterTime());
        return vo;
    }

    private Map<Integer, BizMemberLevel> buildLevelMap()
    {
        Map<Integer, BizMemberLevel> map = new HashMap<>();
        for (BizMemberLevel level : memberLevelMapper.selectEnabledList())
        {
            map.put(level.getLevelNo(), level);
        }
        return map;
    }

    private MemberLevelVO toLevelVo(BizMemberLevel level)
    {
        MemberLevelVO vo = new MemberLevelVO();
        vo.setLevelId(level.getLevelId());
        vo.setLevelNo(level.getLevelNo());
        vo.setLevelName(level.getLevelName());
        vo.setLevelIcon(level.getLevelIcon());
        vo.setBenefits(level.getBenefits());
        vo.setSortNo(level.getSortNo());
        return vo;
    }

    private void fillMemberLevel(MemberListVO vo, BizMember m, Map<Integer, BizMemberLevel> levelMap)
    {
        vo.setMemberLevel(m.getMemberLevel());
        if (m.getMemberLevel() == null)
        {
            return;
        }
        BizMemberLevel level = levelMap.get(m.getMemberLevel());
        if (level == null)
        {
            level = memberLevelMapper.selectByLevelNo(m.getMemberLevel());
        }
        if (level != null)
        {
            vo.setMemberLevelLabel(level.getLevelName());
        }
        else
        {
            vo.setMemberLevelLabel(String.valueOf(m.getMemberLevel()));
        }
    }

    private void fillMemberLevel(MemberDetailVO vo, BizMember m, Map<Integer, BizMemberLevel> levelMap)
    {
        MemberListVO temp = new MemberListVO();
        fillMemberLevel(temp, m, levelMap);
        vo.setMemberLevel(temp.getMemberLevel());
        vo.setMemberLevelLabel(temp.getMemberLevelLabel());
    }

    private MemberAddressVO toAddressVo(BizMemberAddress addr)
    {
        MemberAddressVO vo = new MemberAddressVO();
        vo.setAddressId(addr.getAddressId());
        vo.setConsigneeName(addr.getConsigneeName());
        vo.setMobile(addr.getMobile());
        vo.setRegionCode(addr.getRegionCode());
        vo.setRegionName(addr.getRegionName());
        vo.setDetailAddress(addr.getDetailAddress());
        vo.setIsDefault(addr.getIsDefault());
        vo.setFullAddress(buildFullAddress(addr.getRegionName(), addr.getDetailAddress()));
        return vo;
    }

    private String buildFullAddress(String regionName, String detailAddress)
    {
        String region = StringUtils.isEmpty(regionName) ? "" : regionName.replace("/", "");
        return region + (detailAddress != null ? detailAddress : "");
    }
}
