package shop.alien.storeplatform.service.impl;

import com.alibaba.excel.util.StringUtils;
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.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.LifeDiscountCoupon;
import shop.alien.entity.store.LifeUser;
import shop.alien.entity.store.StoreImg;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.storePlatform.StoreOperationalActivity;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityDTO;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityVO;
import shop.alien.mapper.LifeDiscountCouponMapper;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.storePlantform.StoreOperationalActivityMapper;
import shop.alien.storeplatform.service.OperationalActivityService;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 运营活动服务实现类
 * <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;

    @Override
    public int createActivity(StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityServiceImpl.createActivity: dto={}", dto);
        
        StoreOperationalActivity activity = new StoreOperationalActivity();
        BeanUtils.copyProperties(dto, activity);
        
        // 设置默认值
        if (activity.getParticipationLimit() == null) {
            activity.setParticipationLimit(0);
        }
        if (activity.getStatus() == null) {
            activity.setStatus(1);
        }
        Integer result = activityMapper.insert(activity);
        if (result > 0) {
            dto.getActivityTitleImg().setBusinessId(activity.getId());
            dto.getActivityTitleImg().setImgType(26);
            imgMapper.insert(dto.getActivityTitleImg());

            dto.getActivityDetailImg().setBusinessId(activity.getId());
            dto.getActivityDetailImg().setImgType(27);
            imgMapper.insert(dto.getActivityDetailImg());
        }
        
        return result;
    }

    @Override
    public int updateActivity(StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityServiceImpl.updateActivity: dto={}", dto);
        
        if (dto.getId() == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }
        
        StoreOperationalActivity activity = new StoreOperationalActivity();
        BeanUtils.copyProperties(dto, activity);
        Integer result = activityMapper.updateById(activity);

        // 添加
        if (result > 0) {
            // 删除原本的图片
            LambdaUpdateWrapper<StoreImg> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(StoreImg::getBusinessId, dto.getId())
                    .eq(StoreImg::getStoreId, dto.getStoreId())
                    .set(StoreImg::getDeleteFlag, 1);
            imgMapper.update(null, wrapper);



            // 插入新图片
            StoreImg activityTitleImg = new StoreImg();
            activityTitleImg.setStoreId(dto.getStoreId());
            activityTitleImg.setImgType(26);
            activityTitleImg.setImgSort(dto.getActivityTitleImg().getImgSort());
            activityTitleImg.setImgUrl(dto.getActivityTitleImg().getImgUrl());
            activityTitleImg.setBusinessId(dto.getId());
            imgMapper.insert(activityTitleImg);

            // 插入新图片
            StoreImg activityDetailImg = new StoreImg();
            activityDetailImg.setStoreId(dto.getStoreId());
            activityDetailImg.setImgType(27);
            activityDetailImg.setImgSort(dto.getActivityDetailImg().getImgSort());
            activityDetailImg.setImgUrl(dto.getActivityDetailImg().getImgUrl());
            activityDetailImg.setBusinessId(dto.getId());
            imgMapper.insert(activityDetailImg);
        }
        return result;
    }

    @Override
    public int deleteActivity(Integer id) {
        log.info("OperationalActivityServiceImpl.deleteActivity: id={}", id);
        
        if (id == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }
        
        // 逻辑删除
        return activityMapper.deleteById(id);
    }

    @Override
    public StoreOperationalActivityVO queryActivityById(Integer id) {
        log.info("OperationalActivityServiceImpl.getActivityById: 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);

        if (activity.getStatus() == 1) {
            vo.setStatusName("待审核");
        } else if (activity.getStatus() == 2) {
            vo.setStatusName("未开始");
        } else if (activity.getStatus() == 3) {
            vo.setStatusName("审核拒绝");
        } else if (activity.getStatus() == 4) {
            vo.setStatusName("已售罄");
        } else if (activity.getStatus() == 5) {
            vo.setStatusName("进行中");
        } else if (activity.getStatus() == 6) {
            vo.setStatusName("已下架");
        } else if (activity.getStatus() == 7) {
            vo.setStatusName("已结束");
        }
        
        // 设置优惠券名称（判空处理）
        if (activity.getCouponId() != null) {
            LifeDiscountCoupon coupon = lifeDiscountCouponMapper.selectById(activity.getCouponId());
            if (coupon != null) {
                vo.setCouponName(coupon.getName());
            }
        }

        StoreImg activityTitleImg = imgMapper.selectOne(new LambdaQueryWrapper<StoreImg>()
                .eq(StoreImg::getStoreId, vo.getStoreId())
                .eq(StoreImg::getImgType, 26)
                .eq(StoreImg::getDeleteFlag, 0)
                .eq(StoreImg::getBusinessId, activity.getId()));
        if (activityTitleImg != null) {
            vo.setActivityTitleImgUrl(activityTitleImg.getImgUrl());
        }


        StoreImg activityDetailImg = imgMapper.selectOne(new LambdaQueryWrapper<StoreImg>()
                .eq(StoreImg::getStoreId, vo.getStoreId())
                .eq(StoreImg::getImgType, 27)
                .eq(StoreImg::getDeleteFlag, 0)
                .eq(StoreImg::getBusinessId, activity.getId()));
        if (activityDetailImg != null) {
            vo.setActivityDetailImgUrl(activityDetailImg.getImgUrl());
        }

        return vo;
    }


    @Override
    public IPage<StoreOperationalActivityVO> queryActivityList(Integer storeId, Integer status, String activityName, Integer pageNum, Integer pageSize) {
        log.info("OperationalActivityServiceImpl.queryActivityList: storeId={}, status={}, activityName={}, pageNum={}, pageSize={}", 
                storeId, status, activityName, pageNum, pageSize);
        
        LambdaQueryWrapper<StoreOperationalActivity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(storeId != null, StoreOperationalActivity::getStoreId, storeId);
        wrapper.like(activityName != null && activityName != "", StoreOperationalActivity::getActivityName, activityName);
        wrapper.eq(status != null, StoreOperationalActivity::getStatus, status);

        IPage<StoreOperationalActivity> list = activityMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        
        // 将list复制到vo
        List<StoreOperationalActivityVO> voRecords = new ArrayList<>();
        
        for (StoreOperationalActivity activity : list.getRecords()) {
            // 创建实体类
            StoreOperationalActivityVO vo = new StoreOperationalActivityVO();
            BeanUtils.copyProperties(activity, vo);

            if (activity.getStatus() == 1) {
                vo.setStatusName("待审核");
            } else if (activity.getStatus() == 2) {
                vo.setStatusName("未开始");
            } else if (activity.getStatus() == 3) {
                vo.setStatusName("审核拒绝");
            } else if (activity.getStatus() == 4) {
                vo.setStatusName("已售罄");
            } else if (activity.getStatus() == 5) {
                vo.setStatusName("进行中");
            } else if (activity.getStatus() == 6) {
                vo.setStatusName("已下架");
            } else if (activity.getStatus() == 7) {
                vo.setStatusName("已结束");
            }

            vo.setCouponName(lifeDiscountCouponMapper.selectById(activity.getCouponId()).getName());

            voRecords.add(vo);
        }
        
        // 创建分页结果对象
        Page<StoreOperationalActivityVO> voList = new Page<>(list.getCurrent(), list.getSize(), list.getTotal());
        voList.setRecords(voRecords);
        
        return voList;
    }

    public static void main(String[] args) {
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date now = new Date();
        System.out.println("当前时间: " + sdf.format(now));
        
        // 获取当天零点零分零秒时间
        Calendar todayStart = Calendar.getInstance();
        todayStart.setTime(now);
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        Date todayZero = todayStart.getTime();
        System.out.println("当天零点时间: " + sdf.format(todayZero));
        
        // now + 1天（零点）
        Calendar calendarPlus = Calendar.getInstance();
        calendarPlus.setTime(now);
        calendarPlus.add(Calendar.DAY_OF_MONTH, 1);
        calendarPlus.set(Calendar.HOUR_OF_DAY, 0);
        calendarPlus.set(Calendar.MINUTE, 0);
        calendarPlus.set(Calendar.SECOND, 0);
        calendarPlus.set(Calendar.MILLISECOND, 0);
        Date nowPlusOneDay = calendarPlus.getTime();
        System.out.println("当前时间+1天(零点): " + sdf.format(nowPlusOneDay));

    }

    @Override
    public int updateActivityStatus(Integer id, Integer status) {
        log.info("OperationalActivityServiceImpl.updateActivityStatus: id={}, status={}", id, status);
        
        if (id == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }
        
        StoreOperationalActivity activity = new StoreOperationalActivity();
        activity.setId(id);
        activity.setStatus(status);
        
        return activityMapper.updateById(activity);
    }
}

