package shop.alien.store.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeCoupon;
import shop.alien.entity.store.LifeDiscountCoupon;
import shop.alien.entity.store.LifeNotice;
import shop.alien.entity.store.StoreImg;
import shop.alien.entity.store.StoreInfo;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.entity.storePlatform.StoreOperationalActivity;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityVO;
import shop.alien.mapper.LifeCouponMapper;
import shop.alien.mapper.LifeDiscountCouponMapper;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.StoreInfoMapper;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.mapper.storePlantform.StoreOperationalActivityMapper;
import shop.alien.store.config.WebSocketProcess;
import shop.alien.store.service.OperationalActivityService;
import shop.alien.util.common.Constants;
import shop.alien.util.type.LifeNoticeUtil;

import java.util.*;

/**
 * 运营活动服务实现类
 * <p>
 * 提供运营活动的增删改查功能，包括：
 * 1. 活动的创建、更新、删除
 * 2. 活动列表查询、分页查询
 * 3. 活动状态管理
 * </p>
 *
 * @author system
 * @since 2025-11-26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OperationalActivityServiceImpl implements OperationalActivityService {

    private final StoreOperationalActivityMapper activityMapper;

    private final StoreImgMapper imgMapper;

    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;

    private final LifeCouponMapper lifeCouponMapper;

    private final StoreInfoMapper storeInfoMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    private final StoreUserMapper storeUserMapper;

    private final WebSocketProcess webSocketProcess;

    @Override
    public int auditActivity(Integer id, Integer status, String approvalComments) {
        log.info("OperationalActivityServiceImpl.auditActivity: id={}, status={}, approvalComments={}", id, status, approvalComments);

        if (id == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }
        if (status == null) {
            throw new IllegalArgumentException("审核状态不能为空");
        }

        if (!Objects.equals(status, 1) && StringUtils.isBlank(approvalComments)) {
            throw new IllegalArgumentException("驳回原因不能为空");
        }

        StoreOperationalActivity update = new StoreOperationalActivity();
        update.setId(id);
        boolean approved = Objects.equals(status, 1);
        if (approved) {
            StoreOperationalActivity activity = activityMapper.selectById(id);
            if (activity == null) {
                throw new IllegalArgumentException("活动不存在");
            }
            update.setStatus(resolveApprovedStatus(activity));
            update.setApprovalComments(null);
        } else {
            update.setStatus(3);
            update.setApprovalComments(approvalComments);
        }

        int result = activityMapper.updateById(update);
        
        // 审核结束后给商户发送通知
        if (result > 0) {
            try {
                StoreOperationalActivity activity = activityMapper.selectById(id);
                if (activity != null) {
                    sendAuditNoticeToStore(activity, approved);
                }
            } catch (Exception e) {
                log.error("发送活动审核通知失败，activityId={}, error={}", id, e.getMessage(), e);
            }
        }
        
        return result;
    }

    @Override
    public IPage<StoreOperationalActivityVO> pageActivityDetail(Integer storeId, String storeName, Integer pageNum, Integer pageSize, Integer activityStatus, String activityName, String activityType, String startTime, String endTime) {
        log.info("OperationalActivityServiceImpl.pageActivityDetail: storeId={}, storeName={}, pageNum={}, pageSize={}, activityStatus={}, activityName={}, activityType={}, startTime={}, endTime={}", storeId, storeName, pageNum, pageSize, activityStatus, activityName, activityType, startTime, endTime);

//        if (storeId == null && StringUtils.isBlank(storeName)) {
//            throw new IllegalArgumentException("请至少提供商户ID或商户名称");
//        }

        int current = (pageNum == null || pageNum <= 0) ? 1 : pageNum;
        int size = (pageSize == null || pageSize <= 0) ? 10 : pageSize;

        // 收集门店ID
        LinkedHashSet<Integer> storeIds = new LinkedHashSet<>();
        if (storeId != null) {
            storeIds.add(storeId);
        }
        if (StringUtils.isNotBlank(storeName)) {
            LambdaQueryWrapper<StoreInfo> storeWrapper = new LambdaQueryWrapper<>();
            storeWrapper.like(StoreInfo::getStoreName, storeName)
                    .eq(StoreInfo::getDeleteFlag, 0)
                    .select(StoreInfo::getId, StoreInfo::getStoreName);
            List<StoreInfo> storeList = storeInfoMapper.selectList(storeWrapper);
            for (StoreInfo info : storeList) {
                if (info.getId() != null) {
                    storeIds.add(info.getId());
                }
            }
        }

//        if (storeIds.isEmpty()) {
//            return new Page<>(current, size, 0);
//        }

        LambdaQueryWrapper<StoreOperationalActivity> wrapper = new LambdaQueryWrapper<>();
        if (activityStatus != null) {
            wrapper.eq(StoreOperationalActivity::getStatus, activityStatus);
        }
        if (StringUtils.isNotBlank(activityName)) {
            wrapper.like(StoreOperationalActivity::getActivityName, activityName);
        }
        if (StringUtils.isNotBlank(activityType)) {
            wrapper.eq(StoreOperationalActivity::getActivityType, activityType);
        }
        if (StringUtils.isNotBlank(startTime)) {
            wrapper.ge(StoreOperationalActivity::getCreatedTime, normalizeStartTime(startTime));
        }
        if (StringUtils.isNotBlank(endTime)) {
            wrapper.le(StoreOperationalActivity::getCreatedTime, normalizeEndTime(endTime));
        }

        if (!storeIds.isEmpty()) {
            wrapper.in(StoreOperationalActivity::getStoreId, storeIds);
        }
        wrapper.eq(StoreOperationalActivity::getDeleteFlag, 0);
        wrapper.orderByDesc(StoreOperationalActivity::getCreatedTime);

        IPage<StoreOperationalActivity> entityPage = activityMapper.selectPage(new Page<>(current, size), wrapper);

        List<StoreOperationalActivityVO> voRecords = new ArrayList<>(entityPage.getRecords().size());
        Map<Integer, String> storeCache = new LinkedHashMap<>();

        for (StoreOperationalActivity activity : entityPage.getRecords()) {
            StoreOperationalActivityVO vo = new StoreOperationalActivityVO();
            BeanUtils.copyProperties(activity, vo);
            vo.setStatusName(resolveStatusName(activity.getStatus()));
            vo.setActivityTypeName(resolveActivityTypeName(activity.getActivityType()));

            // 设置优惠券名称（判空处理）
            if (activity.getCouponId() != null) {
                LifeDiscountCoupon coupon = lifeDiscountCouponMapper.selectByIdIncludeDeleted(activity.getCouponId());
                if (coupon != null) {
                    vo.setCouponName(coupon.getName());
                    vo.setCouponType(coupon.getType());
                }
            }

            // 设置代金券名称（判空处理）
            if (activity.getVoucherId() != null) {
                LifeCoupon voucher = lifeCouponMapper.selectById(String.valueOf(activity.getVoucherId()));
                if (voucher != null) {
                    vo.setVoucherName(voucher.getName());
                }
            }

            attachStoreInfo(vo, storeCache);
            fillActivityImages(vo);
            voRecords.add(vo);
        }

        Page<StoreOperationalActivityVO> voPage = new Page<>(entityPage.getCurrent(), entityPage.getSize(), entityPage.getTotal());
        voPage.setRecords(voRecords);
        return voPage;
    }

    @Override
    public StoreOperationalActivityVO getActivityDetailById(Integer id) {
        log.info("OperationalActivityServiceImpl.getActivityDetailById: id={}", id);

        if (id == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }

        StoreOperationalActivity activity = activityMapper.selectById(id);
        if (activity == null) {
            return null;
        }

        StoreOperationalActivityVO vo = new StoreOperationalActivityVO();
        BeanUtils.copyProperties(activity, vo);
        vo.setStatusName(resolveStatusName(activity.getStatus()));
        vo.setActivityTypeName(resolveActivityTypeName(activity.getActivityType()));

        // 设置优惠券名称（判空处理）
        if (activity.getCouponId() != null) {
            LifeDiscountCoupon coupon = lifeDiscountCouponMapper.selectByIdIncludeDeleted(activity.getCouponId());
            if (coupon != null) {
                vo.setCouponName(coupon.getName());
                vo.setCouponType(coupon.getType());
            }
        }

        // 设置代金券名称（判空处理）
        if (activity.getVoucherId() != null) {
            LifeCoupon voucher = lifeCouponMapper.selectById(String.valueOf(activity.getVoucherId()));
            if (voucher != null) {
                vo.setVoucherName(voucher.getName());
            }
        }

        attachStoreInfo(vo, new LinkedHashMap<>());
        fillActivityImages(vo);
        return vo;
    }

    private int resolveApprovedStatus(StoreOperationalActivity activity) {
        Date now = new Date();
        if (activity.getStartTime() == null || activity.getEndTime() == null) {
            return 2;
        }
        if (now.before(activity.getStartTime())) {
            return 2;
        }
        if (!now.after(activity.getEndTime())) {
            return 5;
        }
        return 7;
    }

    private String resolveStatusName(Integer status) {
        if (status == null) {
            return null;
        }
        switch (status) {
            case 1:
                return "待审核";
            case 2:
                return "未开始";
            case 3:
                return "审核驳回";
            case 4:
                return "已售罄";
            case 5:
                return "进行中";
            case 6:
                return "已下架";
            case 7:
                return "已结束";
            default:
                return null;
        }
    }

    private void attachStoreInfo(StoreOperationalActivityVO vo, Map<Integer, String> cache) {
        if (vo == null || vo.getStoreId() == null) {
            return;
        }
        Integer sid = vo.getStoreId();
        if (cache != null && cache.containsKey(sid)) {
            vo.setStoreName(cache.get(sid));
            return;
        }
        StoreInfo storeInfo = storeInfoMapper.selectById(sid);
        if (storeInfo != null) {
            vo.setStoreName(storeInfo.getStoreName());
            if (cache != null) {
                cache.put(sid, storeInfo.getStoreName());
            }
        }
    }

    private void fillActivityImages(StoreOperationalActivityVO vo) {
        if (vo == null || vo.getStoreId() == null || vo.getId() == null) {
            return;
        }
        // 查询活动标题图（单张）
        StoreImg titleImg = imgMapper.selectOne(new LambdaQueryWrapper<StoreImg>()
                .eq(StoreImg::getStoreId, vo.getStoreId())
                .eq(StoreImg::getBusinessId, vo.getId())
                .eq(StoreImg::getImgType, 26)
                .eq(StoreImg::getDeleteFlag, 0)
                .orderByAsc(StoreImg::getImgSort)
                .last("LIMIT 1"));
        if (titleImg != null) {
            vo.setActivityTitleImg(titleImg);
            vo.setActivityTitleImgUrl(titleImg.getImgUrl());
        }

        // 查询活动详情图（多张）
        List<StoreImg> detailImgs = imgMapper.selectList(new LambdaQueryWrapper<StoreImg>()
                .eq(StoreImg::getStoreId, vo.getStoreId())
                .eq(StoreImg::getBusinessId, vo.getId())
                .eq(StoreImg::getImgType, 27)
                .eq(StoreImg::getDeleteFlag, 0)
                .orderByAsc(StoreImg::getImgSort));
        if (detailImgs != null && !detailImgs.isEmpty()) {
            // 设置第一张详情图（兼容旧字段）
            vo.setActivityDetailImg(detailImgs.get(0));
            vo.setActivityDetailImgUrl(detailImgs.get(0).getImgUrl());
            // 设置详情图列表
            List<String> detailImgUrls = new ArrayList<>();
            for (StoreImg img : detailImgs) {
                if (img != null && img.getImgUrl() != null && !img.getImgUrl().trim().isEmpty()) {
                    detailImgUrls.add(img.getImgUrl().trim());
                }
            }
            vo.setActivityDetailImgUrlList(detailImgUrls);
        }
    }

    private String resolveActivityTypeName(String activityType) {
        if (StringUtils.isBlank(activityType)) {
            return null;
        }
        switch (activityType) {
            case "2":
                return "评论有礼";
            case "1":
                return "营销活动";
            default:
                return activityType;
        }
    }

    private String normalizeStartTime(String timeText) {
        if (StringUtils.isBlank(timeText)) {
            return timeText;
        }
        String value = timeText.trim();
        if (value.length() == 10) {
            return value + " 00:00:00";
        }
        return value;
    }

    private String normalizeEndTime(String timeText) {
        if (StringUtils.isBlank(timeText)) {
            return timeText;
        }
        String value = timeText.trim();
        if (value.length() == 10) {
            return value + " 23:59:59";
        }
        return value;
    }

    /**
     * 发送活动审核通知给商户
     *
     * @param activity 活动信息
     * @param approved 是否通过：true-通过，false-拒绝
     */
    private void sendAuditNoticeToStore(StoreOperationalActivity activity, boolean approved) {
        log.info("OperationalActivityServiceImpl.sendAuditNoticeToStore: activityId={}, approved={}", activity.getId(), approved);

        if (activity.getStoreId() == null) {
            log.warn("活动商户ID为空，无法发送通知，activityId={}", activity.getId());
            return;
        }

        // 查询商户用户信息（获取手机号）
        LambdaQueryWrapper<StoreUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(StoreUser::getStoreId, activity.getStoreId())
                .eq(StoreUser::getDeleteFlag, 0)
                .last("LIMIT 1");
        StoreUser storeUser = storeUserMapper.selectOne(userWrapper);
        if (storeUser == null || storeUser.getPhone() == null) {
            log.warn("商户用户信息不存在或手机号为空，无法发送通知，storeId={}", activity.getStoreId());
            return;
        }

        String phone = storeUser.getPhone();
        String receiverId = "store_" + phone;

        // 构建通知内容
        String message;
        if (approved) {
            // 审核通过
            message = "您提交的活动已审核通过";
        } else {
            // 审核拒绝
            message = "您提交的活动已被拒绝";
        }

        JSONObject contextJson = new JSONObject();
        contextJson.put("activityId", activity.getId());
        contextJson.put("activityName", activity.getActivityName());
        contextJson.put("status", approved ? "通过" : "拒绝");
        contextJson.put("message", message);

        LifeNotice lifeNotice = new LifeNotice();
        lifeNotice.setSenderId("system");
        lifeNotice.setReceiverId(receiverId);
        lifeNotice.setBusinessId(activity.getId());
        lifeNotice.setTitle("活动审核通知");
        lifeNotice.setContext(contextJson.toJSONString());
        lifeNotice.setNoticeType(Constants.Notice.SYSTEM_NOTICE); // 系统通知
        lifeNotice.setIsRead(0);

        // 保存通知到数据库
        lifeNoticeUtil.fillUserTypeAndRefId(lifeNotice);
        lifeNoticeMapper.insert(lifeNotice);

        // 通过WebSocket发送实时通知
        try {
            WebSocketVo webSocketVo = new WebSocketVo();
            webSocketVo.setSenderId("system");
            webSocketVo.setReceiverId(receiverId);
            webSocketVo.setCategory("notice");
            webSocketVo.setNoticeType("1");
            webSocketVo.setIsRead(0);
            webSocketVo.setText(JSONObject.toJSONString(lifeNotice));

            webSocketProcess.sendMessage(receiverId, JSONObject.toJSONString(webSocketVo));
            log.info("活动审核通知发送成功，activityId={}, receiverId={}, approved={}", activity.getId(), receiverId, approved);
        } catch (Exception e) {
            log.error("发送WebSocket通知失败，activityId={}, receiverId={}, error={}", activity.getId(), receiverId, e.getMessage(), e);
        }
    }
}

