package com.cyl.manager.act.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.time.LocalDateTime;
import java.util.Optional;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyl.manager.act.domain.entity.ActivityApplyInfo;
import com.cyl.manager.act.domain.entity.ActivityInfo;
import com.cyl.manager.act.domain.query.ActivityApplyInfoQuery;
import com.cyl.manager.act.domain.vo.ActivityApplyInfoSaveVo;
import com.cyl.manager.act.mapper.ActivityApplyInfoMapper;
import com.cyl.manager.act.mapper.ActivityInfoMapper;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 活动报名信息Service业务层处理
 *
 * @author zcc
 */
@Service
public class ActivityApplyInfoService {
    @Autowired
    private ActivityApplyInfoMapper activityApplyInfoMapper;

    @Autowired
    private ActivityInfoMapper activityInfoMapper;

    @Autowired
    private MemberMapper memberMapper;

    /**
     * 查询活动报名信息
     *
     * @param id 活动报名信息主键
     * @return 活动报名信息
     */
    public ActivityApplyInfo selectById(Long id) {
        ActivityApplyInfo activityApplyInfo = activityApplyInfoMapper.selectById(id);
        int num;
        List<ActivityApplyInfo> list = activityApplyInfoMapper.selectList(Wrappers.<ActivityApplyInfo>lambdaQuery()
                .eq(ActivityApplyInfo::getActivityId, activityApplyInfo.getActivityId()).ne(ActivityApplyInfo::getStatus,3));
        if (CollectionUtils.isNotEmpty(list)) {
            num = list.size();
        } else {
            num = 0;
        }
        Optional.ofNullable(activityInfoMapper.selectById(activityApplyInfo.getActivityId()))
                .ifPresent(activityInfo -> {
                    activityApplyInfo.setActivityTitle(activityInfo.getActivityTitle());
                    activityApplyInfo.setCoverUrl(activityInfo.getCoverUrl());
                    activityApplyInfo.setActivityDate(activityInfo.getActivityDate());
                    activityApplyInfo.setActivityAddress(activityInfo.getActivityAddress());
                    activityApplyInfo.setApplyStartTime(activityInfo.getApplyStartTime());
                    activityApplyInfo.setApplyEndTime(activityInfo.getApplyEndTime());
                    activityApplyInfo.setNum(num + "/" + activityInfo.getPersonCondition());
                    activityApplyInfo.setPersonCondition(activityInfo.getPersonCondition());
                });
        Member member = memberMapper.selectById(activityApplyInfo.getUserId());
        if (null != member) {
            activityApplyInfo.setCancelUserName(member.getNickname());
        }
        return activityApplyInfo;
    }

    /**
     * 查询活动报名信息列表
     *
     * @param query 查询条件
     * @param page  分页条件
     * @return 活动报名信息
     */
    public List<ActivityApplyInfo> selectList(ActivityApplyInfoQuery query, Pageable page) {
        List<ActivityApplyInfo> result = activityApplyInfoMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(result)) {
            result.forEach(activityApplyInfo -> {
                //判断报名活动是否到期并且未核销
                if (activityApplyInfo.getStatus().equals("0")) {
                    if (isBeforeCurrentTime(activityApplyInfo.getActivityEndTime())) {
                        UpdateWrapper<ActivityApplyInfo> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", activityApplyInfo.getId());
                        updateWrapper.set("status", "2");
                        //修改状态
                        activityApplyInfoMapper.update(null, updateWrapper);
                    }
                }
            });
        }
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<ActivityApplyInfo> qw = new QueryWrapper<>();
        qw.eq("del_flag", "0");
        String cancelUserName = query.getCancelUserName();
        if (StringUtils.isNotEmpty(cancelUserName)) {
            qw.like("cancel_user_name", cancelUserName);
        }
        if (null != query.getUserId()) {
            qw.eq("user_id", query.getUserId());
        }
        String activityTitle = query.getActivityTitle();
        if (StringUtils.isNotEmpty(activityTitle)) {
            qw.like("activity_title", activityTitle);
        }
        String status = query.getStatus();
        if (!StringUtils.isEmpty(status)) {
            qw.eq("status", status);
        }
        if (null != query.getActivityId()) {
            qw.eq("activity_id", query.getActivityId());
        }
        List<ActivityApplyInfo> activityApplyInfos = activityApplyInfoMapper.selectList(qw);
        if (CollectionUtils.isNotEmpty(activityApplyInfos)) {
            activityApplyInfos.forEach(activityApplyInfo -> {
                Optional.ofNullable(activityInfoMapper.selectById(activityApplyInfo.getActivityId()))
                        .ifPresent(activityInfo -> {
                            activityApplyInfo.setActivityTitle(activityInfo.getActivityTitle());
                            activityApplyInfo.setCoverUrl(activityInfo.getCoverUrl());
                            activityApplyInfo.setActivityDate(activityInfo.getActivityDate());
                            activityApplyInfo.setActivityAddress(activityInfo.getActivityAddress());
                            activityApplyInfo.setApplyStartTime(activityInfo.getApplyStartTime());
                            activityApplyInfo.setApplyEndTime(activityInfo.getApplyEndTime());

                            //获取报名人数
                            List<ActivityApplyInfo> list = activityApplyInfoMapper.selectList(Wrappers.<ActivityApplyInfo>lambdaQuery()
                                    .eq(ActivityApplyInfo::getActivityId, activityInfo.getId()).ne(ActivityApplyInfo::getStatus, "3"));
                            activityApplyInfo.setNum(String.valueOf(list.size()));
                            activityApplyInfo.setPersonCondition(activityInfo.getPersonCondition());
                        });
            });
        }
        return activityApplyInfos;
    }

    public static boolean isBeforeCurrentTime(String inputTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        try {
            Date date = sdf.parse(inputTime);
            return date.before(new Date());
        } catch (ParseException e) {
            throw new RuntimeException("时间格式错误", e);
        }
    }

    /**
     * 新增活动报名信息
     *
     * @param activityApplyInfo 活动报名信息
     * @return 结果
     */
    public int insert(ActivityApplyInfo activityApplyInfo) {
        activityApplyInfo.setDelFlag("0");
        activityApplyInfo.setCreateTime(LocalDateTime.now());
        return activityApplyInfoMapper.insert(activityApplyInfo);
    }

    /**
     * 批量新增活动报名信息
     *
     * @param activityApplyInfoSaveVo 活动报名信息
     * @return 结果
     */
    public int insertAll(ActivityApplyInfoSaveVo activityApplyInfoSaveVo) {
        int i = 0;
        if (null != activityApplyInfoSaveVo.getActivityId()) {
            ActivityInfo activityInfo = activityInfoMapper.selectById(activityApplyInfoSaveVo.getActivityId());
            if (CollectionUtils.isNotEmpty(activityApplyInfoSaveVo.getActivityApplyInfos())) {
                for (ActivityApplyInfo activityApplyInfo : activityApplyInfoSaveVo.getActivityApplyInfos()) {
                    activityApplyInfo.setCreateTime(LocalDateTime.now());
                    activityApplyInfo.setDelFlag("0");
                    activityApplyInfo.setActivityEndTime(activityApplyInfoSaveVo.getActivityEndTime());
                    activityApplyInfo.setActivityTitle(activityInfo.getActivityTitle());
                    activityApplyInfo.setActivityDate(activityInfo.getActivityDate());
                    activityApplyInfo.setActivityAddress(activityInfo.getActivityAddress());
                    activityApplyInfo.setApplyStartTime(activityInfo.getApplyStartTime());
                    activityApplyInfo.setActivityId(activityInfo.getId());
                    activityApplyInfo.setUserId(activityApplyInfoSaveVo.getUserId());
                    activityApplyInfo.setApplyEndTime(activityInfo.getApplyEndTime());
                    activityApplyInfo.setCancelCode(RandomUtil.randomString(10));
                    i = activityApplyInfoMapper.insert(activityApplyInfo);
                }
            }
        }
        return i;
    }

    /**
     * 修改活动报名信息
     *
     * @param activityApplyInfo 活动报名信息
     * @return 结果
     */
    public int update(ActivityApplyInfo activityApplyInfo) {
        return activityApplyInfoMapper.updateById(activityApplyInfo);
    }

    /**
     * 批量删除活动报名信息
     *
     * @param ids 需要删除的活动报名信息主键
     * @return 结果
     */
    public int deleteByIds(Long[] ids) {
        return activityApplyInfoMapper.updateDelFlagByIds(ids);
    }

    /**
     * 删除活动报名信息信息
     *
     * @param id 活动报名信息主键
     * @return 结果
     */
    public int deleteById(Long id) {
        Long[] ids = {id};
        return activityApplyInfoMapper.updateDelFlagByIds(ids);
    }
}
