package com.cyl.manager.ums.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyl.h5.service.H5MemberService;
import com.cyl.manager.oms.domain.Order;
import com.cyl.manager.oms.mapper.AftersaleMapper;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.domain.MemberCart;
import com.cyl.manager.ums.domain.MemberPointHistory;
import com.cyl.manager.ums.mapper.MemberCartMapper;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.cyl.manager.ums.pojo.dto.ChangeMemberStatusDTO;
import com.cyl.manager.ums.pojo.query.MemberQuery;
import com.cyl.manager.ums.pojo.vo.MemberDataStatisticsVO;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.AesCryptoUtils;
import com.ruoyi.common.utils.SortUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.cyl.manager.oms.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.annotation.Target;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会员信息Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class MemberService {
    private static final Logger log = LoggerFactory.getLogger(MemberService.class);
    @Autowired
    private MemberMapper memberMapper;
    @Value("${aes.key}")
    private String aesKey;

    @Autowired
    private MemberCartMapper memberCartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AftersaleMapper aftersaleMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private H5MemberService h5MemberService;


    @Autowired
    private  MemberPointHistoryService memberPointHistoryService;


    /**
     * 查询会员信息
     *
     * @param id 会员信息主键
     * @return 会员信息
     */
    public Member selectById(Long id) {
        return memberMapper.selectById(id);
    }

    /**
     * 查询会员信息列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 会员信息
     */
    public List<Member> selectList(MemberQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize(), SortUtil.sort2string(page.getSort(),"id desc"));
        }
        QueryWrapper<Member> qw = new QueryWrapper<>();
        String nicknameLike = query.getNickname();
        if (!StringUtils.isEmpty(nicknameLike)) {
            qw.like("nickname", nicknameLike);
        }
        String phone = query.getPhone();
        if (!StringUtils.isEmpty(phone)) {
            qw.eq("phone_encrypted", AesCryptoUtils.encrypt(aesKey, phone));
        }
        if (!StringUtils.isEmpty(query.getBeginTime()) && !StringUtils.isEmpty(query.getEndTime())){
            qw.ge("create_time", query.getBeginTime());
            qw.lt("create_time", query.getEndTime());
        }
        if (query.getHasMark() != null) {
            switch (query.getHasMark()) {
                case 0:
                    qw.isNull("mark").or().eq("mark","");
                    break;
                case 1:
                    qw.isNotNull("mark").ne("mark","");
                    break;
                default:
                    break;
            }
        }
        if (query.getStatus() != null){
            qw.eq("status", query.getStatus());
        }
        return memberMapper.selectList(qw);
    }

    /**
     * 新增会员信息
     *
     * @param member 会员信息
     * @return 结果
     */
    public int insert(Member member) {
        member.setCreateTime(LocalDateTime.now());
        return memberMapper.insert(member);
    }

    /**
     * 修改会员信息
     *
     * @param member 会员信息
     * @return 结果
     */
    public int update(Member member) {
        return memberMapper.updateById(member);
    }

    public int updateMark(Member member) {
        UpdateWrapper<Member> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("mark",member.getMark())
                .set("update_time",LocalDateTime.now())
                .eq("id",member.getId());
        return memberMapper.update(null,updateWrapper);
    }

    /**
     * 删除会员信息信息
     *
     * @param id 会员信息主键
     * @return 结果
     */
    public int deleteById(Long id) {
        return memberMapper.deleteById(id);
    }

    public Integer changeStatus(ChangeMemberStatusDTO dto) {
        UpdateWrapper<Member> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", dto.getMemberId());
        wrapper.set("status", dto.getStatus());
        return memberMapper.update(null, wrapper);
    }

    public String getPhoneDecrypted(String phoneEncrypted) {
        return AesCryptoUtils.decrypt(aesKey, phoneEncrypted);
    }

    public MemberDataStatisticsVO viewStatistics(Long memberId) {
        LambdaQueryWrapper<MemberCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberCart::getMemberId, memberId);
        int cartCount = memberCartMapper.selectCount(wrapper);
        MemberDataStatisticsVO vo = orderMapper.statOrderCountAndAmount(memberId);
        vo.setCartCount(cartCount);
        vo.setAftersaleCount(aftersaleMapper.countByMemberId(memberId));
        return vo;
    }

    @Transactional
    public String sync() {
        //查询所有有效订单 订单状态： 1->待发货；2->已发货；3->已完成
        log.info("查询所有有效订单  订单状态： 1->待发货；2->已发货；3->已完成");
        List<Order> orders = orderService.getAllValidOrder();
        if(CollectionUtils.isEmpty(orders)){
            log.info("查询所有有效订单完成,数量:0");
            return "未查询到订单数据";
        }
        log.info("查询所有有效订单完成,数量:{}", orders.size());
        //根据memberId订单分组
        Map<Long, List<Order>> map = orders.stream()
                .collect(Collectors.groupingBy(Order::getMemberId));
        //根据订单生成对应的积分明细，集点明细
        for (Map.Entry<Long, List<Order>> entry : map.entrySet()) {
            Long memberId = entry.getKey();
            List<Order> orderList = entry.getValue();
            Member member = memberMapper.selectById(memberId);
            //订单总金额
            BigDecimal totalAmount = orderList.stream()
                    .map(Order::getPayAmount) // 获取每个订单的 amount
                    .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加
            int[] levels =  h5MemberService.evaluateOrderAmount(totalAmount);
            int level = levels[0];
            BigDecimal coefficient = BigDecimal.ZERO;
            if (level == 1) {
                coefficient = BigDecimal.valueOf(1.1);
            } else if ( level == 2) {
                coefficient = BigDecimal.valueOf(1.1);
            } else if ( level == 3) {
                coefficient = BigDecimal.valueOf(1.3);
            } else if ( level == 4) {
                coefficient = BigDecimal.valueOf(1.5);
            } else {
                coefficient = BigDecimal.valueOf(1.1);
            }
            member.setLevel(level);
            member.setCentralPoint(BigDecimal.valueOf(orderList.size()));
            member.setIntegral(totalAmount.multiply(coefficient));
            memberMapper.updateById(member);
            log.info("更新member信息:{}", member);
            BigDecimal pointCount = BigDecimal.ZERO;
            BigDecimal gatherCount =  BigDecimal.ZERO;
            for (Order order : orderList) {
                MemberPointHistory point =  getPointEntity(order,pointCount,coefficient);
                memberPointHistoryService.insertMemberPointHistory(point);
                // 更新 pointCount
                pointCount = pointCount.add(order.getPayAmount().multiply(coefficient));
                log.info("新增积分明细:{}", point);
                MemberPointHistory gather =  getGatherEntity(order,gatherCount);
                memberPointHistoryService.insertMemberPointHistory(gather);
                // 更新 gatherCount
                gatherCount = gatherCount.add(BigDecimal.ONE);
                log.info("新增集点明细:{}", gather);
            }
        }
        return "同步完成";
    }

    private MemberPointHistory getGatherEntity(Order order, BigDecimal gatherCount) {
        MemberPointHistory memberPointHistory = new MemberPointHistory();
        memberPointHistory.setMemberId(order.getMemberId());
        memberPointHistory.setPoint(BigDecimal.ONE);
        memberPointHistory.setType("gather");
        memberPointHistory.setTransactionId(order.getId());
        memberPointHistory.setDescription("数据手工同步");
        memberPointHistory.setAction("added");
        memberPointHistory.setPointBefore(gatherCount);
        gatherCount = gatherCount.add(BigDecimal.valueOf(1));
        memberPointHistory.setPointAfter(gatherCount);
        memberPointHistory.setCreateAt(order.getCreateTime());
        return memberPointHistory;
    }

    private MemberPointHistory getPointEntity(Order order,BigDecimal pointCount,BigDecimal coefficient) {
        MemberPointHistory memberPointHistory = new MemberPointHistory();
        memberPointHistory.setMemberId(order.getMemberId());
        BigDecimal result = order.getPayAmount().multiply(coefficient);
        memberPointHistory.setPoint(result);
        memberPointHistory.setType("point");
        memberPointHistory.setTransactionId(order.getId());
        memberPointHistory.setDescription("数据手工同步");
        memberPointHistory.setAction("added");
        if(pointCount.compareTo(BigDecimal.ZERO) == 0){
            memberPointHistory.setPointBefore(BigDecimal.ZERO);
        }else{
            memberPointHistory.setPointBefore(pointCount);
        }
        pointCount = pointCount.add(order.getPayAmount().multiply(coefficient));
        memberPointHistory.setPointAfter(pointCount);
        memberPointHistory.setCreateAt(order.getCreateTime());
        return memberPointHistory;
    }
}
