package com.liquidnet.client.admin.zhengzai.adam.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.common.utils.ShiroUtils;
import com.liquidnet.client.admin.zhengzai.adam.service.IAdamMemberRightsAdminService;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.adam.constant.AdamRedisConst;
import com.liquidnet.service.adam.dto.admin.AdamMemberRightsBuildParam;
import com.liquidnet.service.adam.dto.vo.AdamMemberRightsVo;
import com.liquidnet.service.adam.entity.AdamMemberRights;
import com.liquidnet.service.adam.mapper.AdamMemberRightsMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdamMemberRightsAdminServiceImpl extends ServiceImpl<AdamMemberRightsMapper, AdamMemberRights> implements IAdamMemberRightsAdminService {
    @Autowired
    private AdamMemberRightsMapper adamMemberRightsMapper;
    @Autowired
    private RedisDataSourceUtil redisDataSourceUtil;

    @Override
    public AdamMemberRights edit(AdamMemberRightsBuildParam param) {
        String loginName = ShiroUtils.getLoginName();
        LocalDateTime now = LocalDateTime.now();
        String mrightsId = param.getMrightsId();

        boolean saveOrUpadateRst, isAddFlag = StringUtils.isEmpty(mrightsId);
        AdamMemberRights saveOrUpdateInfo = new AdamMemberRights();
        if (isAddFlag) {
            saveOrUpdateInfo.setMrightsId(IDGenerator.nextMilliId2());
            saveOrUpdateInfo.setMemberId(param.getMemberId());
            saveOrUpdateInfo.setMemberPriceId(StringUtils.trimToNull(param.getMemberPriceId()));
            saveOrUpdateInfo.setState(1);

            saveOrUpdateInfo.setSeqNo(param.getSeqNo());
            saveOrUpdateInfo.setTitle(param.getTitle());
            saveOrUpdateInfo.setSubTitle(param.getSubTitle());
            saveOrUpdateInfo.setLabel(param.getLabel());
            saveOrUpdateInfo.setCover(param.getCover());
            saveOrUpdateInfo.setDetail(param.getDetail());
            saveOrUpdateInfo.setOperator(loginName);
            saveOrUpdateInfo.setCreatedAt(now);

            saveOrUpadateRst = adamMemberRightsMapper.insert(saveOrUpdateInfo) > 0;
        } else {
            LambdaUpdateWrapper<AdamMemberRights> updateWrapper = Wrappers.lambdaUpdate(AdamMemberRights.class).eq(AdamMemberRights::getState, 1)
                    .eq(AdamMemberRights::getMemberId, param.getMemberId())
                    .eq(AdamMemberRights::getMrightsId, param.getMrightsId());

            saveOrUpdateInfo.setMrightsId(param.getMrightsId());
            saveOrUpdateInfo.setMemberId(param.getMemberId());
            saveOrUpdateInfo.setState(param.getState());
            saveOrUpdateInfo.setOperator(loginName);
            saveOrUpdateInfo.setUpdatedAt(now);
            if (param.getState() != 2) {
                saveOrUpdateInfo.setMemberPriceId(StringUtils.trimToNull(param.getMemberPriceId()));
                saveOrUpdateInfo.setSeqNo(param.getSeqNo());
                saveOrUpdateInfo.setTitle(param.getTitle());
                saveOrUpdateInfo.setSubTitle(param.getSubTitle());
                saveOrUpdateInfo.setLabel(param.getLabel());
                saveOrUpdateInfo.setCover(param.getCover());
                saveOrUpdateInfo.setDetail(param.getDetail());
                // 允许清空绑定：用 set 显式更新可空字段
                updateWrapper.set(AdamMemberRights::getMemberPriceId, StringUtils.trimToNull(param.getMemberPriceId()));
            }

            saveOrUpadateRst = adamMemberRightsMapper.update(saveOrUpdateInfo, updateWrapper) > 0;
        }

        if (!saveOrUpadateRst) {
            return null;
        }
        // 与价格包一致：从 DB 全量重载 Redis，避免增量补丁丢权益 / 缺 memberPriceId
        refreshMemberRightsRedis(param.getMemberId());
        return saveOrUpdateInfo;
    }

    private void refreshMemberRightsRedis(String memberId) {
        List<AdamMemberRights> onlineList = adamMemberRightsMapper.selectList(Wrappers.lambdaQuery(AdamMemberRights.class)
                .eq(AdamMemberRights::getMemberId, memberId)
                .eq(AdamMemberRights::getState, 1)
                .orderByAsc(AdamMemberRights::getSeqNo));
        List<AdamMemberRightsVo> vos = CollectionUtils.isEmpty(onlineList) ? new ArrayList<>()
                : onlineList.stream()
                .sorted(Comparator.comparing(AdamMemberRights::getSeqNo, Comparator.nullsLast(Integer::compareTo)))
                .map(r -> AdamMemberRightsVo.getNew().copy(r))
                .collect(Collectors.toList());
        redisDataSourceUtil.getRedisAdamUtil().set(AdamRedisConst.INFO_MEMBER_RIGHTS.concat(memberId), vos);
    }
}
