package com.ylx.massage.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.common.core.domain.model.WxLoginUser;
import com.ylx.common.exception.ServiceException;
import com.ylx.common.utils.StringUtils;
import com.ylx.lottery.domain.LotteryCountLog;
import com.ylx.lottery.domain.vo.LocalActivityTableVO;
import com.ylx.lottery.domain.vo.LotteryActivityVO;
import com.ylx.lottery.service.LotteryCountLogService;
import com.ylx.lottery.service.LotteryCountService;
import com.ylx.massage.domain.CommentUserAudit;
import com.ylx.massage.domain.TCommentUser;
import com.ylx.massage.domain.TOrder;
import com.ylx.massage.enums.OrderStatusEnum;
import com.ylx.massage.mapper.TCommentUserMapper;
import com.ylx.massage.service.TCommentUserAuditService;
import com.ylx.massage.service.TCommentUserService;
import com.ylx.massage.service.TOrderService;
import com.ylx.usercenter.domain.dto.UnifiedUserCenterDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 用户评论表(TCommentUser)表服务实现类
 *
 * @author makejava
 * @since 2024-08-08 10:32:08
 */
@Slf4j
@Service("tCommentUserService")
public class TCommentUserServiceImpl extends ServiceImpl<TCommentUserMapper, TCommentUser> implements TCommentUserService {

    @Resource
    private TOrderService orderService;

    @Resource
    private TCommentUserAuditService commentUserAuditService;

    @Resource
    private TCommentUserMapper tCommentUserMapper;
    @Resource
    private LotteryCountService lotteryCountService;
    @Resource
    private LotteryCountLogService lotteryCountLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveComment(TCommentUser comment, WxLoginUser wxLoginUser) {
        //订单ID不能为空
        if (StringUtils.isBlank(comment.getOrderId())) {
            throw new ServiceException("订单id不能为空");
        }
        //判断订单是否存在
        TOrder order1 = orderService.getById(comment.getOrderId());
        if (order1 == null) {
            throw new ServiceException("订单不存在");
        }
        if (StringUtils.isBlank(comment.getOrderNo())) {
            throw new ServiceException("订单号不能为空");
        }
        if (StringUtils.isBlank(comment.getText())) {
            throw new ServiceException("评论内容不能空");
        }
        if (StringUtils.isBlank(comment.getJsId())) {
            throw new ServiceException("技师id不能空");
        }
        if (StringUtils.isBlank(comment.getName())) {
            throw new ServiceException("技师姓名不能空");
        }
        comment.setOpenId(wxLoginUser.getCOpenid());
        //comment.setOpenId("o-HEJ6RAjBDjFvuZcAdHRX8mIZXw");
        comment.setCommentTime(new Date());
        this.save(comment);

        //向用户评论审核表中插入数据
        CommentUserAudit commentUserAudit = new CommentUserAudit();
        commentUserAudit.setCommentId(comment.getId());
        commentUserAudit.setOrderNo(comment.getOrderNo());
        commentUserAudit.setText(comment.getText());
        //默认审核状态为待审核
        commentUserAudit.setAuditStatus(0);
        commentUserAudit.setCreateTime(new Date());
        commentUserAudit.setUpdateTime(new Date());
        commentUserAudit.setIsDelete(0);
        commentUserAuditService.save(commentUserAudit);

        TOrder order = new TOrder();
        //修改订单状态（已完成）
        order.setnStatus(OrderStatusEnum.COMPLETE.getCode());
        order.setcId(comment.getOrderId());
        boolean bool = orderService.updateById(order);
        if (bool) {

            Integer isBind = wxLoginUser.getIsBind();
            String localLiveUserId = wxLoginUser.getLocalLiveUserId();
            // 评价有礼
            List<LotteryActivityVO> lotteryActivityVOS = lotteryCountService.queryActivityRules();
            if (CollUtil.isNotEmpty(lotteryActivityVOS)) {
                for (LotteryActivityVO activity : lotteryActivityVOS) {

                    List<LocalActivityTableVO> gyyPointTables = activity.getGyyPointTables();
                    if (CollUtil.isNotEmpty(gyyPointTables)) {
                        for (LocalActivityTableVO localActivityTable : gyyPointTables) {

                            LotteryCountLog lotteryCountLog = new LotteryCountLog();
                            lotteryCountLog.setOpenId(wxLoginUser.getCOpenid());
                            lotteryCountLog.setUserId(wxLoginUser.getId());
                            lotteryCountLog.setUserPhone(wxLoginUser.getCPhone());
                            // 活动类型：2.任务奖励
                            lotteryCountLog.setActivityType(2);
                            lotteryCountLog.setLocalActivityTableId(localActivityTable.getId());
                            lotteryCountLog.setLotteryNum(localActivityTable.getPointNumber());
                            lotteryCountLog.setReceiveTime(new Date());
                            lotteryCountLog.setIsDelete("0");
                            // 同步状态 0-未同步到本地生活
                            lotteryCountLog.setStatus(0);

                            lotteryCountLog.setIsLottery(0);
                            lotteryCountLog.setType(3);
                            lotteryCountLogService.save(lotteryCountLog);
                        }
                    } else {

                        // 非任务奖励活动
                        if (ObjectUtil.isNull(activity.getParticipationRules()) || ObjectUtil.notEqual(activity.getParticipationRules(), 3)) {
                            continue;
                        }

                        List<LocalActivityTableVO> localActivityTables = activity.getLocalActivityTables();
                        if (CollUtil.isEmpty(localActivityTables)) {
                            continue;
                        }

                        for (LocalActivityTableVO localActivityTable : localActivityTables) {

                            // 判断是否评价有礼
                            if (ObjectUtil.isNull(localActivityTable.getType()) || ObjectUtil.notEqual(localActivityTable.getType(), 4)) {
                                continue;
                            }

                            LotteryCountLog lotteryCountLog = new LotteryCountLog();
                            lotteryCountLog.setOpenId(wxLoginUser.getCOpenid());
                            lotteryCountLog.setUserId(wxLoginUser.getId());
                            lotteryCountLog.setUserPhone(wxLoginUser.getCPhone());
                            // 活动类型：2.任务奖励
                            lotteryCountLog.setActivityType(2);
                            lotteryCountLog.setLocalActivityTableId(localActivityTable.getId());
                            lotteryCountLog.setLotteryNum(1);
                            lotteryCountLog.setReceiveTime(new Date());
                            lotteryCountLog.setIsDelete("0");
                            // 同步状态 0-未同步到本地生活
                            lotteryCountLog.setStatus(0);

                            lotteryCountLog.setIsLottery(0);
                            lotteryCountLog.setType(3);
                            lotteryCountLogService.save(lotteryCountLog);
                        }
                    }
                }
            }

            // todo  事务问题 当前用户绑定一账通
            if (ObjectUtil.isNotNull(isBind) && (ObjectUtil.equals(isBind, 1) && ObjectUtil.isNotNull(localLiveUserId))) {
                // 同步抽奖次数（异步处理）
                UnifiedUserCenterDTO dto = new UnifiedUserCenterDTO();
                dto.setTargetUserId(localLiveUserId);
                dto.setSourceUserId(wxLoginUser.getId());
                syncLotteryCount(dto);
            }
        }
        return bool;
    }


    @Override
    public List<TCommentUser> selectAll(TCommentUser tCommentUser) {
        return tCommentUserMapper.selectAll(tCommentUser);
    }

    // 异步同步抽奖次数
    @Async
    public void syncLotteryCount(UnifiedUserCenterDTO dto) {
        try {
            boolean lotteryCountBool = this.lotteryCountService.batchAdd(dto);
            if (lotteryCountBool) {
                log.info("同步用户抽奖次数到本地生活服务成功, userId:{}", dto.getTargetUserId());
            } else {
                log.warn("同步用户抽奖次数到本地生活服务失败, userId:{}", dto.getTargetUserId());
                // 同步失败，记录告警日志
                log.error("【告警】同步用户抽奖次数到本地生活服务失败，需要人工处理, userId:{}", dto.getTargetUserId());
            }
        } catch (Exception e) {
            log.error("同步用户抽奖次数到本地生活服务异常, userId:{}", dto.getTargetUserId(), e);
            // 异常情况，记录告警日志
            log.error("【告警】同步用户抽奖次数到本地生活服务异常，需要人工处理, userId:{}", dto.getTargetUserId(), e);
        }
    }
}

