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

import java.util.ArrayList;
import java.util.List;
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.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.BizMemberMapper;
import com.ruoyi.web.modules.account.service.IMemberService;
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.MemberListVO;

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

    @Autowired
    private BizMemberAddressMapper addressMapper;

    @Autowired
    private IOrderFacade orderFacade;

    @Override
    public List<MemberListVO> selectMemberList(BizMember query)
    {
        List<BizMember> list = memberMapper.selectList(query);
        List<MemberListVO> rows = new ArrayList<>();
        for (BizMember m : list)
        {
            rows.add(toListVo(m, true));
        }
        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);
        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 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)
    {
        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);
        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 void fillMemberLevel(MemberListVO vo, BizMember m)
    {
        vo.setMemberLevel(m.getMemberLevel());
        if (m.getMemberLevel() != null)
        {
            String label = DictUtils.getDictLabel(MemberConstants.DICT_MEMBER_LEVEL,
                    String.valueOf(m.getMemberLevel()));
            vo.setMemberLevelLabel(StringUtils.isNotEmpty(label) ? label : String.valueOf(m.getMemberLevel()));
        }
    }

    private void fillMemberLevel(MemberDetailVO vo, BizMember m)
    {
        vo.setMemberLevel(m.getMemberLevel());
        if (m.getMemberLevel() != null)
        {
            String label = DictUtils.getDictLabel(MemberConstants.DICT_MEMBER_LEVEL,
                    String.valueOf(m.getMemberLevel()));
            vo.setMemberLevelLabel(StringUtils.isNotEmpty(label) ? label : String.valueOf(m.getMemberLevel()));
        }
    }

    private MemberAddressVO toAddressVo(BizMemberAddress addr)
    {
        MemberAddressVO vo = new MemberAddressVO();
        vo.setAddressId(addr.getAddressId());
        vo.setConsigneeName(addr.getConsigneeName());
        vo.setMobile(addr.getMobile());
        vo.setProvince(addr.getProvince());
        vo.setCity(addr.getCity());
        vo.setDistrict(addr.getDistrict());
        vo.setDetailAddress(addr.getDetailAddress());
        vo.setIsDefault(addr.getIsDefault());
        vo.setFullAddress(addr.getProvince() + addr.getCity() + addr.getDistrict() + addr.getDetailAddress());
        return vo;
    }
}
