package shop.alien.second.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import shop.alien.entity.second.SecondRiskControlRecord;
import shop.alien.entity.second.SecondUserCredit;
import shop.alien.entity.second.SecondUserCreditRecord;
import shop.alien.entity.second.vo.*;
import shop.alien.entity.store.LifeUser;

import shop.alien.entity.store.LifeNotice;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.util.type.LifeNoticeUtil;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.mapper.second.SecondRiskControlRecordMapper;
import shop.alien.mapper.second.SecondUserCreditMapper;
import shop.alien.second.feign.AlienStoreFeign;
import shop.alien.second.service.RiskControlService;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 风控服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RiskControlServiceImpl extends ServiceImpl<SecondRiskControlRecordMapper, SecondRiskControlRecord> implements RiskControlService {

    private final SecondRiskControlRecordMapper secondRiskControlRecordMapper;
    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;
    private final LifeUserMapper lifeUserMapper;
    private final AlienStoreFeign alienStoreFeign;

    private final RiskControlGoodsServiceImpl riskControlGoodsService;
    private final PlatformSecondTradeServiceImpl tradeService;
    private final SecondUserCreditMapper secondUserCreditMapper;
    private final SecondUserCreditRecordServiceImpl sreditRecordService;

    @Lazy
    @Autowired
    private SecondGoodsServiceImpl secondGoodsService;
    /**
     * 记录风控数据
     *
     * @param userId     用户ID
     * @param ruleType   规则类型 1:洗钱嫌疑 2:账号异常 3:交易欺诈 4:异常发布
     * @param ruleName   规则名称
     * @param businessId 业务ID
     * @param detailInfo 详细信息（JSON格式）
     */
    @Override
    public void recordRiskControlData(Integer userId,
                                       Integer ruleType,
                                       String ruleName,
                                      String businessId,
                                       String detailInfo) {
        try {
            SecondRiskControlRecord record = new SecondRiskControlRecord();
            record.setUserId(userId);
            record.setRuleType(ruleType);
            record.setRuleName(ruleName);
            record.setBusinessId(businessId);
            record.setDetailInfo(detailInfo);
            record.setCreatedTime(Date.from(LocalDateTime.now().plusDays(7).atZone(ZoneId.systemDefault()).toInstant()));
            record.setUpdatedTime(Date.from(LocalDateTime.now().plusDays(7).atZone(ZoneId.systemDefault()).toInstant()));
            record.setDeleteFlag(0);
            record.setCreatedUserId(userId);
            record.setUpdatedUserId(userId);

            secondRiskControlRecordMapper.insert(record);
        } catch (Exception e) {
            log.error("记录风控数据时发生异常: 用户ID={}, 规则类型={},业务id={}", userId, ruleType, businessId, e);
        }
    }

    /**
     * 获取相同类型的风控数据
     *
     * @param ruleType   规则类型 1:洗钱嫌疑 2:账号异常 3:交易欺诈 4:异常发布
     * @param businessId 业务ID
     * @return 相同类型的风控数据列表
     */
    @Override
    public List<SecondRiskControlRecord> getSameTypeRiskControlRecords(Integer ruleType, String businessId) {
        log.info("获取相同类型的风控数据: 规则类型={},业务id={}", ruleType, businessId);
        QueryWrapper<SecondRiskControlRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rule_type", ruleType);
        queryWrapper.eq("business_id", businessId);
        log.info("查询条件: {}", queryWrapper.getSqlSegment());
        return secondRiskControlRecordMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<SecondRiskControlRecordVo> queryRiskControlRecords(SecondRiskControlRecordVo vo) {
        try {
            // 3. 获取商品操作记录集合
            QueryWrapper<SecondRiskControlRecordVo> recordQueryWrapper = new QueryWrapper<>();
            recordQueryWrapper
                    .eq(vo.getRuleType() != null, "r.rule_type", vo.getRuleType())
                    .eq(vo.getRiskStatus() != null, "r.risk_status", vo.getRiskStatus())
                    .eq("r.delete_flag",0)
                    .orderByDesc("r.created_time");
            return secondRiskControlRecordMapper.queryRiskControlRecords(new Page<>(vo.getPageNum(), vo.getPageSize()), recordQueryWrapper);
        } catch (Exception e) {
            log.error("记录风控数据时发生异常: ", e);
            return null;
        }
    }


    /**
     * 发送封禁通知
     */
    public void sendNotice(Integer userId) {
        LifeUser lifeUser = lifeUserMapper.selectById(userId);
        if (lifeUser == null) return;

        String phoneId = "user_" + lifeUser.getUserPhone();

        // 给买家发送通知
        LifeNotice lifeNotice = new LifeNotice();
        lifeNotice.setSenderId("system");
        lifeNotice.setReceiverId(phoneId);
        lifeNotice.setBusinessId(userId);
        lifeNotice.setTitle("账号违规处理");
        lifeNotice.setNoticeType(1);
        // 封装通知信息
        JSONObject noticeMessage = new JSONObject();
        noticeMessage.put("message", "账号违反平台规约进行封禁处理");
        lifeNotice.setContext(noticeMessage.toJSONString());
        lifeNoticeUtil.fillUserTypeAndRefId(lifeNotice);
        lifeNoticeMapper.insert(lifeNotice);

        // 给买家推送通知
        WebSocketVo webSocketVo = new WebSocketVo();
        webSocketVo.setSenderId("system");
        webSocketVo.setReceiverId(phoneId);
        webSocketVo.setCategory("notice");
        webSocketVo.setNoticeType("1");
        webSocketVo.setType("1");
        webSocketVo.setText(JSONObject.from(lifeNotice).toJSONString());
        alienStoreFeign.sendMsgToClientByPhoneId(phoneId, JSONObject.from(webSocketVo).toJSONString());
    }


    @Override
    public SecondRiskRecordVo queryRiskControlRecordsDetail(SecondRiskRecordVo vo) throws Exception {
        // 返回实体
        SecondRiskRecordVo item = new SecondRiskRecordVo();

        if (vo.getRuleType() == 1) {
            item.setTradeRecordList(tradeService.getTradeRecordListByRiskId(vo.getId()));
        } else if (vo.getRuleType() == 2) {
            // 将数组转换为包含整数的列表
            List<Integer> userIds = Arrays.stream(vo.getDetailInfo().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());

            // 使用LambdaQueryWrapper进行查询
            LambdaQueryWrapper<LifeUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(LifeUser::getId, userIds);
            item.setUserList(lifeUserMapper.selectList(queryWrapper));
        } else if (vo.getRuleType() == 3 || vo.getRuleType() == 4) {
            // 移除方括号并按逗号分割，然后转换为Integer列表
            List<Integer> integerList = Arrays.stream(vo.getDetailInfo().substring(1, vo.getDetailInfo().length() - 1)
                            .split(","))
                    .map(String::trim)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());

            if (vo.getRuleType() == 3) {
                item.setGoodsRecordList(riskControlGoodsService.getGoodsInfoByRecordIds(integerList));
            } else {
                item.setGoodsList(riskControlGoodsService.getGoodsInfoByGoodsIds(integerList));
            }
        }
        return item;
    }


    @Override
    public boolean accountBan(SecondRiskRecordVo vo) throws Exception {
        if (1 == vo.getIsExecute()) {
            // 封禁时间
            Date freezeTime = Date.from(LocalDateTime.now().plusDays(7).atZone(ZoneId.systemDefault()).toInstant());

            if (vo.getRuleType() == 2) {
                // 查询所有待交易
                LambdaQueryWrapper<SecondRiskControlRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SecondRiskControlRecord::getBusinessId, vo.getBusinessId());
                List<SecondRiskControlRecord> records = secondRiskControlRecordMapper.selectList(wrapper);

                // 将所有记录的detailInfo用逗号连接在一起
                String combinedDetailInfo = records.stream()
                        .map(SecondRiskControlRecord::getDetailInfo)
                        .filter(Objects::nonNull) // 过滤掉null值
                        .collect(Collectors.joining(","));

                // 将数组转换为包含整数的列表
                Set<Integer> userIds = Arrays.stream(combinedDetailInfo.split(","))
                        .map(Integer::parseInt)
                        .collect(Collectors.toSet());

                // 方式1: 使用LambdaUpdateWrapper
                LambdaUpdateWrapper<SecondUserCredit> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.in(SecondUserCredit::getUserId, userIds)
                        .set(SecondUserCredit::getFreezeTime, freezeTime)
                        .set(SecondUserCredit::getUpdatedTime, new Date());
                secondUserCreditMapper.update(null, updateWrapper);
            } else {
                LambdaQueryWrapper<SecondUserCredit> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SecondUserCredit::getUserId, vo.getUserId())
                        .eq(SecondUserCredit::getDeleteFlag, 0);
                SecondUserCredit userPoints = secondUserCreditMapper.selectOne(queryWrapper);
                if (userPoints == null) {
                    return false;
                }
                if (vo.getRuleType() == 1) {
                    tradeService.bannedAccountCancelTrade(vo.getUserId());
                } else {
                    if (vo.getRuleType() == 3 || vo.getRuleType() == 4) {
                        // 更新积分
                        int newPoints = userPoints.getUserPoints() - 50;
                        // 创建积分记录
                        SecondUserCreditRecord record = new SecondUserCreditRecord();
                        record.setUserId(vo.getUserId());
                        record.setPoints(-50);
                        record.setCurrentScoreCount(userPoints.getUserPoints() - 50);
                        record.setPointsType(3);
                        sreditRecordService.createRecord(record);
                        userPoints.setUserPoints(newPoints);
                        secondGoodsService.batchShelveGoodsByRiskControlRecord(vo.getRuleType(), vo.getBusinessId());
                    }
                }
                userPoints.setFreezeTime(freezeTime);
                secondUserCreditMapper.updateById(userPoints);
            }
        }
        // 方式1: 使用LambdaUpdateWrapper
        LambdaUpdateWrapper<SecondRiskControlRecord> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SecondRiskControlRecord::getDeleteFlag, 0)
                .eq(SecondRiskControlRecord::getRuleType, vo.getRuleType())
                .set(SecondRiskControlRecord::getRiskStatus, vo.getIsExecute())
                .set(SecondRiskControlRecord::getUpdatedTime, new Date());
        if (vo.getRuleType() == 4) {
            updateWrapper.in(SecondRiskControlRecord::getUserId, vo.getUserId());

        } else {
            updateWrapper.in(SecondRiskControlRecord::getBusinessId, vo.getBusinessId());
        }
        secondRiskControlRecordMapper.update(null, updateWrapper);
        return true;
    }

}