package com.template.controller;


import com.alibaba.fastjson.JSON;
import com.template.api.AlumniActivityControllerAPI;
import com.template.common.utils.ExcelUtils;
import com.template.common.utils.TimeExchange;
import com.template.common.utils.WeiXiaoUtil;
import com.template.common.utils.paramUtils;
import com.template.model.enumModel.*;
import com.template.model.pojo.*;
import com.template.model.request.*;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.*;
import com.template.services.*;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2024-11-27
 */
@RestController
public class AlumniActivityController implements AlumniActivityControllerAPI {

    @Autowired
    private AlumniAdminApplyService alumniAdminApplyService;
    @Autowired
    private AlumniActivityService alumniActivityService;
    @Autowired
    private AlumniUserService alumniUserService;
    @Autowired
    private ActivityReportService activityReportService;
    @Autowired
    private ActivitySigninService activitySigninService;
    @Autowired
    private ActivityImageService activityImageService;
    @Autowired
    private WeiXiaoUtil weiXiaoUtil;
    private static Logger logger = LoggerFactory.getLogger(AlumniImageController.class);

    @Override
    public CommonResult queryScopeTypes() {
        List<ListDataVO> result = new ArrayList<>();
        for (int i = 1; i <= eScopeType.values().length; i++) {
            ListDataVO data = new ListDataVO();
            data.setId(i);
            data.setName(ePassType.stringOf(i));
            result.add(data);
        }

        return CommonResult.ok(result);

    }

    @Override
    public CommonResult queryIsImage() {
        List<ListDataVO> result = new ArrayList<>();
        for (int i = 1; i <= eIsImage.values().length; i++) {
            ListDataVO data = new ListDataVO();
            data.setId(i);
            data.setName(ePassType.stringOf(i));
            result.add(data);
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult insertActivity(Integer userId, insertActivityRequest iar, BindingResult bindingResult) throws Exception {
        if (iar == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        AlumniUser operater = alumniUserService.queryDataById(userId);
        if (operater == null) {
            return CommonResult.fail("当前操作人身份已失效，新增失败");
        }

        //查看管理员是否已设置
        AlumniAdminApply aaa = alumniAdminApplyService.queryActivityAdmin();
        if (aaa == null) {
            return CommonResult.fail("校友活动模块未设置管理员，无法新增活动");
        }

        //region 时间校验
        //活动时间和报名时间都不能出现开始时间大于结束时间的情况，并且报名时间必须在活动时间内
        if (!TimeExchange.CompareDate(iar.getStartTime(), iar.getEndTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("活动开始时间不能大于活动结束时间");
        }
        if (!TimeExchange.CompareDate(iar.getSignsTime(), iar.getSigneTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("报名开始时间不能大于报名结束时间");
        }
        if (!TimeExchange.CompareDate(iar.getSigneTime(), iar.getStartTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("报名时间必须在活动时间之前");
        }
        //endregion

        AlumniActivity aa = new AlumniActivity();
        aa.setOrgId(iar.getOrgId());
        aa.setOrgName(iar.getOrgName());
        aa.setTheme(iar.getTheme());
        aa.setThemeDetail(iar.getThemeDetail());
        aa.setStartTime(TimeExchange.StringToDate(iar.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
        aa.setEndTime(TimeExchange.StringToDate(iar.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        aa.setPoster(iar.getPoster());
        aa.setAddress(iar.getAddress());
        aa.setLng(iar.getLng());
        aa.setLat(iar.getLat());
        aa.setDescribes(iar.getDescribes());
        aa.setSignsTime(TimeExchange.StringToDate(iar.getSignsTime(), "yyyy-MM-dd HH:mm:ss"));
        aa.setSigneTime(TimeExchange.StringToDate(iar.getSigneTime(), "yyyy-MM-dd HH:mm:ss"));
        aa.setTotalNumber(iar.getTotalNumber());
        aa.setScope(iar.getScope());
        aa.setPhone(iar.getPhone());
        aa.setIsImage(iar.getIsImage());
        aa.setApplyUser(aaa.getAdmin());
        aa.setApplyUserAdmin(aaa.getAdminName());
        //如果是管理员的数据不用审
        if (operater.getRoleId() != null && (operater.getRoleId().intValue() == eRoleType.Super.getValue() || operater.getRoleId().intValue() == eRoleType.Admin.getValue())) {
            aa.setIsPass(ePassType.Passed.getValue());
            aa.setPassTime(new Date());
        } else {
            aa.setIsPass(ePassType.Approval.getValue());
        }

        int result = alumniActivityService.insertAlumniActivity(aa);
        if (result <= 0) {
            return CommonResult.fail("新增活动失败");
        }

        //发送微校通知
        //用户提交母校代言申请后，通知显示给母校代言管理员：“
        // [申请人姓名]，母校代言申请已提交，请及时对照片进行审核。
        if (aa.getIsPass().intValue() == ePassType.Approval.getValue()) {
            List<AlumniUser> users = alumniUserService.queryDataByIds(Arrays.asList(aaa.getAdmin().split(",")));
            List<String> cardnumbers = new ArrayList<>();
            for (AlumniUser user : users) {
                if (org.springframework.util.StringUtils.hasText(user.getCardNumber())) {
                    cardnumbers.add(user.getCardNumber());
                }
            }
            if (cardnumbers != null && cardnumbers.size() > 0) {
                String content = operater.getName() + "，活动申请已提交，请及时对" + aa.getTheme() + "进行审核。";
                CommonResult sendMessage = weiXiaoUtil.sendNotice(cardnumbers, "活动申请审核", "活动申请审核", content, null);
                if (!sendMessage.getCode().equals("200")) {
                    logger.info("微校通知发送失败，cardnumber：" + JSON.toJSON(cardnumbers) + "，Content：" + content);
                }
            }
        }


        return CommonResult.ok("新增活动成功");
    }

    @Override
    public CommonResult updateActivity(updateActivityRequest uar, BindingResult bindingResult) throws Exception {
        if (uar == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        AlumniActivity oldData = alumniActivityService.queryDataById(uar.getId());
        if (oldData == null) {
            return CommonResult.fail("数据已失效，编辑失败");
        }

        //待审核数据才能被编辑
        if (oldData.getIsPass().intValue() != ePassType.Approval.getValue()) {
            return CommonResult.fail("该数据已完成审核，无法编辑，可重新发起");
        }

        oldData.setOrgId(uar.getOrgId());
        oldData.setOrgName(uar.getOrgName());
        oldData.setTheme(uar.getTheme());
        oldData.setThemeDetail(uar.getThemeDetail());
        oldData.setStartTime(TimeExchange.StringToDate(uar.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
        oldData.setEndTime(TimeExchange.StringToDate(uar.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        oldData.setPoster(uar.getPoster());
        oldData.setAddress(uar.getAddress());
        oldData.setLng(uar.getLng());
        oldData.setLat(uar.getLat());
        oldData.setDescribes(uar.getDescribes());
        oldData.setSignsTime(TimeExchange.StringToDate(uar.getSignsTime(), "yyyy-MM-dd HH:mm:ss"));
        oldData.setSigneTime(TimeExchange.StringToDate(uar.getSigneTime(), "yyyy-MM-dd HH:mm:ss"));
        oldData.setTotalNumber(uar.getTotalNumber());
        oldData.setScope(uar.getScope());
        oldData.setPhone(uar.getPhone());
        oldData.setIsImage(uar.getIsImage());

        int result = alumniActivityService.updateAlumniActivity(oldData);
        if (result <= 0) {
            return CommonResult.fail("编辑失败");
        }

        return CommonResult.ok("编辑成功");
    }

    @Override
    public CommonResult deleteActivityById(int id) {
        AlumniActivity oldData = alumniActivityService.queryDataById(id);
        if (oldData == null) {
            return CommonResult.fail("数据已失效，删除失败");
        }
        int result = alumniActivityService.deleteDataById(id);
        if (result <= 0) {
            return CommonResult.fail("删除失败");
        }
        return CommonResult.ok("删除成功");
    }

    @Override
    public CommonResult reloadActivityById(int id) {
        AlumniActivity oldData = alumniActivityService.queryDataById(id);
        if (oldData == null) {
            return CommonResult.fail("数据已失效，重新发起失败");
        }

        oldData.setIsPass(ePassType.Reload.getValue());

        int updateResult = alumniActivityService.updateAlumniActivity(oldData);
        if (updateResult <= 0) {
            return CommonResult.fail("重新发起失败");
        }

        ReloadActivityVo result = new ReloadActivityVo();
        result.setOrgId(oldData.getOrgId());
        result.setOrgName(oldData.getOrgName());
        result.setTheme(oldData.getTheme());
        result.setThemeDetail(oldData.getThemeDetail());
        result.setStartTime(TimeExchange.DateToString(oldData.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
        result.setEndTime(TimeExchange.DateToString(oldData.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        result.setPoster(oldData.getPoster());
        result.setAddress(oldData.getAddress());
        result.setLng(oldData.getLng());
        result.setLat(oldData.getLat());
        result.setDescribes(oldData.getDescribes());
        result.setSignsTime(TimeExchange.DateToString(oldData.getSignsTime(), "yyyy-MM-dd HH:mm:ss"));
        result.setSigneTime(TimeExchange.DateToString(oldData.getSigneTime(), "yyyy-MM-dd HH:mm:ss"));
        result.setTotalNumber(oldData.getTotalNumber());
        result.setScope(oldData.getScope());
        result.setPhone(oldData.getPhone());
        result.setIsImage(oldData.getIsImage());

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryStatus() {
        List<ListDataVO> result = new ArrayList<>();
        for (int i = 1; i <= eStatusType.values().length; i++) {
            ListDataVO data = new ListDataVO();
            data.setId(i);
            data.setName(ePassType.stringOf(i));
            result.add(data);
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryActivityPages(int currentPage, int pageCount, String userName, Integer collegeId, Integer periodId, Integer majorId, Integer classId, String orgName, String theme, Integer statuId, String createStartTime, String createEndTime, String startTime, String endTime, String signsTime, String signeTime) throws ParseException {
        String statuStr = null;
        String nowDate = TimeExchange.getTime();
        if (statuId.intValue() == eStatusType.Unstart.getValue()) {//未开始
            statuStr = "and aa.start_time > '" + nowDate + "'";
        } else if (statuId.intValue() == eStatusType.Inprogress.getValue()) {//进行中

            statuStr = "and aa.start_time < '" + nowDate + "' and aa.end_time > '" + nowDate + "'";
        } else if(statuId.intValue() == eStatusType.Ended.getValue()){//已结束
            statuStr = "and aa.end_time < '" + nowDate + "'";
        }
        PageUtils<AlumniActivityPageVo> result = alumniActivityService.queryActivityPages(currentPage, pageCount, userName, collegeId, periodId, majorId, classId, orgName, theme, statuStr, createStartTime, createEndTime, startTime, endTime, signsTime, signeTime);
        for (AlumniActivityPageVo aapv : result.getList()) {
            //未开始：活动时间的开始时间大于当前时间
            //进行中：活动时间的开始时间小于当前时间，并且结束时间大于当前时间
            //已结束：活动时间的结束时间小于当前时间
            if (!TimeExchange.CompareDate(TimeExchange.DateToString(aapv.getStartTime(), "yyyy-MM-dd HH:mm:ss"), nowDate, "yyyy-MM-dd HH:mm:ss")) {
                aapv.setStatuName("未开始");
            } else if (TimeExchange.CompareDate(TimeExchange.DateToString(aapv.getStartTime(), "yyyy-MM-dd HH:mm:ss"), nowDate, "yyyy-MM-dd HH:mm:ss")
                    && !TimeExchange.CompareDate(TimeExchange.DateToString(aapv.getEndTime(), "yyyy-MM-dd HH:mm:ss"), nowDate, "yyyy-MM-dd HH:mm:ss")) {
                aapv.setStatuName("进行中");
            } else {
                aapv.setStatuName("已结束");
            }
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult getAlumniActivityExcel(alumniActivityExcelRequest aaer, HttpServletResponse response, BindingResult bindingResult) throws ParseException {
        if (aaer == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }


        //导出
        Workbook workbook = new XSSFWorkbook();

        //region 活动管理汇总
        Sheet sheet = workbook.createSheet("活动管理汇总表");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("序号");
        headerRow.createCell(1).setCellValue("发起人");
        headerRow.createCell(2).setCellValue("学院");
        headerRow.createCell(3).setCellValue("学段");
        headerRow.createCell(4).setCellValue("专业");
        headerRow.createCell(5).setCellValue("班级");
        headerRow.createCell(6).setCellValue("所属组织");
        headerRow.createCell(7).setCellValue("活动主题");
        headerRow.createCell(8).setCellValue("活动开始时间");
        headerRow.createCell(9).setCellValue("活动结束时间");
        headerRow.createCell(10).setCellValue("报名开始时间");
        headerRow.createCell(11).setCellValue("报名结束时间");
        headerRow.createCell(12).setCellValue("状态");
        headerRow.createCell(13).setCellValue("已报名");
        headerRow.createCell(14).setCellValue("已签到");
        headerRow.createCell(15).setCellValue("创建时间");


        String statuStr = null;
        String nowDate = TimeExchange.getTime();
        if (aaer.getStatuId().intValue() == eStatusType.Unstart.getValue()) {//未开始
            statuStr = "and aa.start_time > '" + nowDate + "'";
        } else if (aaer.getStatuId().intValue() == eStatusType.Inprogress.getValue()) {//进行中

            statuStr = "and aa.start_time < '" + nowDate + "' and aa.end_time > '" + nowDate + "'";
        } else  if(aaer.getStatuId().intValue() == eStatusType.Ended.getValue()){//已结束
            statuStr = "and aa.end_time < '" + nowDate + "'";
        }
        PageUtils<AlumniActivityPageVo> result = alumniActivityService.queryActivityPages(1, 3000, aaer.getUserName(), aaer.getCollegeId()
                , aaer.getPeriodId(), aaer.getMajorId(), aaer.getClassId(), aaer.getOrgName(), aaer.getTheme(), statuStr,
                aaer.getCreateStartTime(), aaer.getCreateEndTime(), aaer.getStartTime(), aaer.getEndTime(), aaer.getSignsTime(), aaer.getSigneTime());
        for (AlumniActivityPageVo aapv : result.getList()) {
            //未开始：活动时间的开始时间大于当前时间
            //进行中：活动时间的开始时间小于当前时间，并且结束时间大于当前时间
            //已结束：活动时间的结束时间小于当前时间
            if (!TimeExchange.CompareDate(TimeExchange.DateToString(aapv.getStartTime(), "yyyy-MM-dd HH:mm:ss"), nowDate, "yyyy-MM-dd HH:mm:ss")) {
                aapv.setStatuName("未开始");
            } else if (TimeExchange.CompareDate(TimeExchange.DateToString(aapv.getStartTime(), "yyyy-MM-dd HH:mm:ss"), nowDate, "yyyy-MM-dd HH:mm:ss")
                    && !TimeExchange.CompareDate(TimeExchange.DateToString(aapv.getEndTime(), "yyyy-MM-dd HH:mm:ss"), nowDate, "yyyy-MM-dd HH:mm:ss")) {
                aapv.setStatuName("进行中");
            } else {
                aapv.setStatuName("已结束");
            }
        }


        if (result != null && result.getList().size() > 0) {
            int i = 0;
            for (AlumniActivityPageVo acv : result.getList()) {
                Row dataRow = sheet.createRow(i + 1);
                dataRow.createCell(0).setCellValue(i + 1);//序号
                dataRow.createCell(1).setCellValue(acv.getName());//发起人
                dataRow.createCell(2).setCellValue(acv.getCollegeName());//学院
                dataRow.createCell(3).setCellValue(acv.getPeriodName());//学段
                dataRow.createCell(4).setCellValue(acv.getPeriodName());//专业
                dataRow.createCell(5).setCellValue(acv.getClassName());//班级
                dataRow.createCell(6).setCellValue(acv.getOrgName());//所属组织
                dataRow.createCell(7).setCellValue(acv.getTheme());//活动主题
                dataRow.createCell(8).setCellValue(TimeExchange.chineseDateTime(acv.getStartTime()));//活动开始时间
                dataRow.createCell(9).setCellValue(TimeExchange.chineseDateTime(acv.getEndTime()));//活动结束时间
                dataRow.createCell(10).setCellValue(TimeExchange.chineseDateTime(acv.getSignsTime()));//报名开始时间
                dataRow.createCell(11).setCellValue(TimeExchange.chineseDateTime(acv.getSigneTime()));//报名结束时间
                dataRow.createCell(12).setCellValue(acv.getStatuName());//状态
                dataRow.createCell(13).setCellValue((acv.getReportNumber() == null ? 0 : acv.getReportNumber()) + "人");//已报名
                dataRow.createCell(14).setCellValue((acv.getSigninNumber() == null ? 0 : acv.getSigninNumber()) + "人");//已签到
                dataRow.createCell(15).setCellValue(TimeExchange.chineseDateTime(acv.getCreateTime()));//创建时间
            }
            i++;
        }
        //endregion
        //region 活动管理明细
        Sheet sheetOne = workbook.createSheet("活动管理明细表");
        Row headerRowOne = sheetOne.createRow(0);
        headerRowOne.createCell(0).setCellValue("序号");
        headerRowOne.createCell(1).setCellValue("活动主题");
        headerRowOne.createCell(2).setCellValue("参加人");
        headerRowOne.createCell(3).setCellValue("学院");
        headerRowOne.createCell(4).setCellValue("学段");
        headerRowOne.createCell(5).setCellValue("专业");
        headerRowOne.createCell(6).setCellValue("班级");
        headerRowOne.createCell(7).setCellValue("报名时间");
        headerRowOne.createCell(8).setCellValue("签到时间");

        List<ActivityDetailExcelVo> resultOne = new ArrayList<>();
        if (result != null && result.getList().size() > 0) {
            List<Integer> activityIds = result.getList().stream().map(AlumniActivityPageVo::getId).collect(Collectors.toList());
            resultOne = activityReportService.activityDetailByActivityIds(activityIds);
            if (resultOne != null && resultOne.size() > 0) {
                int i = 0;
                for (ActivityDetailExcelVo acv : resultOne) {
                    Row dataRowOne = sheet.createRow(i + 1);
                    dataRowOne.createCell(0).setCellValue(i + 1);//序号
                    dataRowOne.createCell(1).setCellValue(acv.getTheme());//活动主题
                    dataRowOne.createCell(2).setCellValue(acv.getName());//参加人
                    dataRowOne.createCell(3).setCellValue(acv.getCollegeName());//学院
                    dataRowOne.createCell(4).setCellValue(acv.getPeriodName());//学段
                    dataRowOne.createCell(5).setCellValue(acv.getMajorName());//专业
                    dataRowOne.createCell(6).setCellValue(acv.getClassName());//班级
                    dataRowOne.createCell(7).setCellValue(TimeExchange.chineseDateTime(acv.getReportTime()));//报名时间
                    dataRowOne.createCell(8).setCellValue(TimeExchange.chineseDateTime(acv.getSigninTime()));//签到时间
                }
                i++;
            }
        }
        //endregion

        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "活动管理.xlsx", response);

        return CommonResult.ok("导出成功");
    }

    @Override
    public CommonResult queryDetailInfoById(int id) {
        AlumniActivity result = alumniActivityService.queryDataById(id);
        if (result == null) {
            return CommonResult.fail("数据已失效，获取详情失败");
        }

        List<UserVo> reportUsers = activityReportService.queryReportDatasByActivityId(result.getId());
        List<UserVo> signinUsers = activitySigninService.querySigninDatasByActivityId(result.getId());
        result.setReportDatas(reportUsers != null && reportUsers.size() > 0 ? reportUsers : new ArrayList<>());
        result.setSigninDatas(signinUsers != null && signinUsers.size() > 0 ? signinUsers : new ArrayList<>());

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult activityReportById(Integer userId, int id) throws ParseException {
        AlumniUser operater = alumniUserService.queryDataById(userId);
        if (operater == null) {
            return CommonResult.fail("操作人员已失效，报名失败");
        }

        AlumniActivity activity = alumniActivityService.queryDataById(id);
        if (activity == null) {
            return CommonResult.fail("活动数据已失效，报名失败");
        }

        if (activity.getIsPass().intValue() != ePassType.Passed.getValue()) {
            return CommonResult.fail("未通过审核的活动，无法进行报名操作");
        }

        //报名开始时间大于当前时间 说明报名未开始
        if (!TimeExchange.CompareDate(TimeExchange.DateToString(activity.getSignsTime(), "yyyy-MM-dd HH:mm:ss"), TimeExchange.getTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("报名未开始，无法进行报名操作");
        }

        //报名结束时间小于当前时间 说明报名结束
        if (TimeExchange.CompareDate(TimeExchange.DateToString(activity.getSigneTime(), "yyyy-MM-dd HH:mm:ss"), TimeExchange.getTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("报名已截至，报名失败");
        }

        int reportCount = activityReportService.queryActivityReportNumber(id);
        if (reportCount >= activity.getTotalNumber().intValue()) {
            return CommonResult.fail("报名人数已满，报名失败");
        }

        ActivityReport ar = new ActivityReport();
        ar.setActivityId(id);
        ar.setUserId(userId);

        int result = activityReportService.insertActivityReport(ar);
        if (result <= 0) {
            return CommonResult.fail("报名失败");
        }

        return CommonResult.ok("报名成功");
    }

    @Override
    public CommonResult activitySigninById(Integer userId, int id) throws ParseException {
        AlumniUser operater = alumniUserService.queryDataById(userId);
        if (operater == null) {
            return CommonResult.fail("操作人员已失效，签到失败");
        }

        AlumniActivity activity = alumniActivityService.queryDataById(id);
        if (activity == null) {
            return CommonResult.fail("活动数据已失效，签到失败");
        }

        if (activity.getIsPass().intValue() != ePassType.Passed.getValue()) {
            return CommonResult.fail("未通过审核的活动，无法进行签到操作");
        }
        //活动开始时间大于当前时间 说明活动未开始
        if (!TimeExchange.CompareDate(TimeExchange.DateToString(activity.getStartTime(), "yyyy-MM-dd HH:mm:ss"), TimeExchange.getTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("活动未开始，无法签到");
        }

        //活动结束时间小于当前时间 说明签到结束
        if (TimeExchange.CompareDate(TimeExchange.DateToString(activity.getEndTime(), "yyyy-MM-dd HH:mm:ss"), TimeExchange.getTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("活动已结束，签到失败");
        }

        List<UserVo> reportUsers = activityReportService.queryReportDatasByActivityId(id);
        if (reportUsers != null && reportUsers.size() > 0) {
            long existReport = reportUsers.stream().filter(e -> e.getId().intValue() == operater.getId().intValue()).count();
            if (existReport <= 0) {
                return CommonResult.fail("暂未报名，无法签到");
            }
        } else {
            return CommonResult.fail("暂未报名，无法签到");
        }

        ActivitySignin as = new ActivitySignin();
        as.setActivityId(id);
        as.setUserId(userId);

        int result = activitySigninService.insertActivitySignin(as);
        if (result <= 0) {
            return CommonResult.fail("签到失败");
        }

        return CommonResult.ok("签到成功");
    }

    @Override
    public CommonResult queryMyActivityPages(int currentPage, int pageCount, Integer userId, Integer isPass) {
        PageUtils<AlumniMyActivityPageVo> result = alumniActivityService.queryMyActivityPages(currentPage, pageCount, userId, isPass);
        for (AlumniMyActivityPageVo aapv : result.getList()) {
            aapv.setPassName(ePassType.stringOf(aapv.getIsPass()));
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryMyJoinActivityPages(int currentPage, int pageCount, Integer userId) throws ParseException {
        String nowDate = TimeExchange.getTime();
        PageUtils<AlumniMyJoinActivityPageVo> result = activityReportService.queryMyJoinActivityPages(currentPage, pageCount, userId);
        for (AlumniMyJoinActivityPageVo aapv : result.getList()) {
            //未开始：活动时间的开始时间大于当前时间
            //进行中：活动时间的开始时间小于当前时间，并且结束时间大于当前时间
            //已结束：活动时间的结束时间小于当前时间
            if (!TimeExchange.CompareDate(TimeExchange.DateToString(aapv.getStartTime(), "yyyy-MM-dd HH:mm:ss"), nowDate, "yyyy-MM-dd HH:mm:ss")) {
                aapv.setStatuId(eStatusType.Unstart.getValue());
                aapv.setStatuName("活动未开始");
            } else if (TimeExchange.CompareDate(TimeExchange.DateToString(aapv.getStartTime(), "yyyy-MM-dd HH:mm:ss"), nowDate, "yyyy-MM-dd HH:mm:ss")
                    && !TimeExchange.CompareDate(TimeExchange.DateToString(aapv.getEndTime(), "yyyy-MM-dd HH:mm:ss"), nowDate, "yyyy-MM-dd HH:mm:ss")) {
                aapv.setStatuId(eStatusType.Inprogress.getValue());
                aapv.setStatuName("活动进行中");
            } else {
                aapv.setStatuId(eStatusType.Ended.getValue());
                aapv.setStatuName("活动已结束");
            }
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult confirmReleaseImage(Integer userId, confirmReleaseRequest crr, BindingResult bindingResult) throws Exception {
        AlumniUser operater = alumniUserService.queryDataById(userId);
        if (operater == null) {
            return CommonResult.fail("当前操作人身份已失效，新增失败");
        }

        //查看管理员是否已设置
        AlumniAdminApply aaa = alumniAdminApplyService.queryActivityAdmin();
        if (aaa == null) {
            return CommonResult.fail("校友活动模块未设置管理员，无法发布照片");
        }


        AlumniActivity aa = alumniActivityService.queryDataById(crr.getId());
        if (aa == null) {
            return CommonResult.fail("活动数据已失效，无法发布照片");
        }

        if (aa.getIsImage().intValue() == eIsImage.Not.getValue()) {
            return CommonResult.fail("未开启上传活动照片设置，无法发布照片");
        }

        ActivityImage ai = new ActivityImage();
        ai.setActivityId(crr.getId());
        String image = StringUtils.join(crr.getImages(), ",");
        ai.setImage(image);
        ai.setApplyUser(aaa.getAdmin());
        ai.setApplyUserName(aaa.getAdminName());
        //如果是管理员的数据不用审
        if (operater.getRoleId() != null && (operater.getRoleId().intValue() == eRoleType.Super.getValue() || operater.getRoleId().intValue() == eRoleType.Admin.getValue())) {
            ai.setIsPass(ePassType.Passed.getValue());
            ai.setPassTime(new Date());
        } else {
            ai.setIsPass(ePassType.Approval.getValue());
        }

        int result = activityImageService.insertActivityImage(ai);
        if (result <= 0) {
            return CommonResult.fail("确认发布失败");
        }

        return CommonResult.ok("确认发布成功");
    }

    @Override
    public CommonResult queryMyUploadPage(int currentPage, int pageCount, Integer userId, int isPass) {
        PageUtils<ActivityImage> result = activityImageService.queryActivityImagePages(currentPage, pageCount, userId, isPass);
        for (ActivityImage rg : result.getList()) {
            rg.setImages(Arrays.asList(rg.getImage().split(",")));
            rg.setPassName(ePassType.stringOf(rg.getIsPass()));
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryUploadApplyPage(int currentPage, int pageCount, Integer userId) {
        PageUtils<ActivityImageApplyVo> result = activityImageService.activityImagePageDatas(currentPage, pageCount, userId);
        for (ActivityImageApplyVo rg : result.getList()) {
            rg.setImages(Arrays.asList(rg.getImage().split(",")));
            rg.setPassName(ePassType.stringOf(rg.getIsPass()));
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult toExamineActivityImage(Integer userId, Integer id, Integer isPass, String passValue) throws Exception {
        if (isPass.intValue() == ePassType.Rejected.getValue() && !org.springframework.util.StringUtils.hasText(passValue)) {
            return CommonResult.fail("审批意见必填");
        }


        AlumniUser au = alumniUserService.queryDataById(userId);
        if (au == null) {
            return CommonResult.fail("当前操作人已失效，无法进行审核操作");
        }

        ActivityImage ai = activityImageService.queryDataById(id);
        if (ai == null) {
            return CommonResult.fail("校友相册审核数据已失效，无法进行审核操作");
        }

        AlumniUser cau = alumniUserService.queryDataById(Integer.valueOf(ai.getCreateUser()));
        if (cau == null) {
            return CommonResult.fail("申请人已失效，无法审核");
        }

        if (ai.getIsPass().intValue() != ePassType.Approval.getValue()) {
            return CommonResult.fail("只有待审核数据能被审核");
        }

        List<String> userIds = Arrays.asList(ai.getApplyUser().split(","));
        if (userIds != null && userIds.size() > 0) {
            if (!userIds.contains(String.valueOf(userId))) {
                return CommonResult.fail("当前操作人无法操作此审核单");
            }
        } else {
            return CommonResult.fail("当前操作人无法操作此审核单");
        }


        ai.setIsPass(isPass);
        ai.setPassValue(passValue);

        int result = activityImageService.updateActivityImage(ai);
        if (result <= 0) {
            return CommonResult.fail("审核失败");
        }

        //发送微校通知
        //审核完成后系统生成通知发送给用户：“
        // [上传人姓名]，母校代言。已通过或已拒绝。”
//        List<String> cardnumbers= new ArrayList<>();
//        cardnumbers.add(cau.getCardNumber());
//        String content = cau.getName()+"，活动照片。"+ePassType.stringOf(ai.getIsPass());
//        CommonResult sendMessage = weiXiaoUtil.sendNotice(cardnumbers, "活动照片审核结果", "活动照片审核结果", content, null);
//        if (!sendMessage.getCode().equals("200")) {
//            logger.info("微校通知发送失败，cardnumber："+ JSON.toJSON(cardnumbers)+"，Content："+content+"，id"+id);
//        }
        return CommonResult.ok("审核成功");
    }

    @Override
    public CommonResult queryMobileDetailInfoById(int id) {
        AlumniActivity result = alumniActivityService.queryDataById(id);
        if (result == null) {
            return CommonResult.fail("数据已失效，获取详情失败");
        }

        List<String> imageStrs = new ArrayList<>();
        List<ActivityImage> images = activityImageService.queryActivityImages(id);
        if (images != null && images.size() > 0) {
            for (ActivityImage ai : images) {
                if (org.springframework.util.StringUtils.hasText(ai.getImage())) {
                    imageStrs.addAll(Arrays.asList(ai.getImage().split(",")));
                }
            }
        }

        List<UserVo> reportUsers = activityReportService.queryReportDatasByActivityId(result.getId());
        List<UserVo> signinUsers = activitySigninService.querySigninDatasByActivityId(result.getId());
        result.setReportDatas(reportUsers != null && reportUsers.size() > 0 ? reportUsers : new ArrayList<>());
        result.setSigninDatas(signinUsers != null && signinUsers.size() > 0 ? signinUsers : new ArrayList<>());
        result.setImages(imageStrs);

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryActivityApplyPages(int currentPage, int pageCount, Integer userId, String userName, Integer collegeId, Integer periodId, Integer majorId, Integer classId, String orgName, String theme, Integer isPass, String createStartTime, String createEndTime, String startTime, String endTime, String signsTime, String signeTime) throws ParseException {
        PageUtils<AlumniActivityApplyPageVo> result = alumniActivityService.queryActivityApplyPages(currentPage, pageCount, userId, userName, collegeId, periodId, majorId, classId, orgName, theme, isPass, createStartTime, createEndTime, startTime, endTime, signsTime, signeTime);
        for (AlumniActivityApplyPageVo aapv : result.getList()) {
            aapv.setPassName(ePassType.stringOf(aapv.getIsPass()));
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult toExamineActivity(Integer userId, Integer id, Integer isPass, String passValue) throws Exception {
        if (isPass.intValue() == ePassType.Rejected.getValue() && !org.springframework.util.StringUtils.hasText(passValue)) {
            return CommonResult.fail("审批意见必填");
        }

        AlumniUser au = alumniUserService.queryDataById(userId);
        if (au == null) {
            return CommonResult.fail("当前操作人已失效，无法进行审核操作");
        }

        AlumniActivity aa = alumniActivityService.queryDataById(id);
        if (aa == null) {
            return CommonResult.fail("活动数据已失效，无法进行审核操作");
        }
        if (aa.getIsPass().intValue() != ePassType.Approval.getValue()) {
            return CommonResult.fail("只有待审核数据能被审核");
        }

        AlumniUser cau = alumniUserService.queryDataById(Integer.valueOf(aa.getCreateUser()));
        if (cau == null) {
            return CommonResult.fail("申请人已失效，无法审核");
        }

        //查看当前操作人是否在
        List<String> userIds = Arrays.asList(aa.getApplyUser().split(","));
        if (userIds != null && userIds.size() > 0) {
            if (!userIds.contains(String.valueOf(userId))) {
                return CommonResult.fail("当前操作人无法操作此审核单");
            }
        } else {
            return CommonResult.fail("当前操作人无法操作此审核单");
        }

        aa.setIsPass(isPass);
        aa.setPassTime(new Date());

        int result = alumniActivityService.insertAlumniActivity(aa);
        if (result <= 0) {
            return CommonResult.fail("审核失败");
        }

        //发送微校通知
        //审核完成后系统生成通知发送给用户：“
        // [上传人姓名]，母校代言。已通过或已拒绝。”
        List<String> cardnumbers = new ArrayList<>();
        cardnumbers.add(cau.getCardNumber());
        String content = cau.getName() + "，" + aa.getTheme() + "活动。" + ePassType.stringOf(aa.getIsPass());
        CommonResult sendMessage = weiXiaoUtil.sendNotice(cardnumbers, "活动审核结果", "活动审核结果", content, null);
        if (!sendMessage.getCode().equals("200")) {
            logger.info("微校通知发送失败，cardnumber：" + JSON.toJSON(cardnumbers) + "，Content：" + content + "，id" + id);
        }


        return CommonResult.ok("审核成功");
    }

    @Override
    public CommonResult getActivityApplyExcel(Integer userId, activityApplyExcelRequest aaer, HttpServletResponse response, BindingResult bindingResult) throws ParseException {
        if (aaer == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        //导出
        Workbook workbook = new XSSFWorkbook();

        //region 活动管理汇总
        Sheet sheet = workbook.createSheet("活动审核表");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("序号");
        headerRow.createCell(1).setCellValue("发起人");
        headerRow.createCell(2).setCellValue("学院");
        headerRow.createCell(3).setCellValue("学段");
        headerRow.createCell(4).setCellValue("专业");
        headerRow.createCell(5).setCellValue("班级");
        headerRow.createCell(6).setCellValue("所属组织");
        headerRow.createCell(7).setCellValue("活动主题");
        headerRow.createCell(8).setCellValue("活动开始时间");
        headerRow.createCell(9).setCellValue("报名开始时间");
        headerRow.createCell(10).setCellValue("已报名");
        headerRow.createCell(11).setCellValue("已签到");
        headerRow.createCell(12).setCellValue("状态");
        headerRow.createCell(13).setCellValue("审核人");
        headerRow.createCell(14).setCellValue("审核时间");
        headerRow.createCell(15).setCellValue("创建时间");


        PageUtils<AlumniActivityApplyPageVo> result = alumniActivityService.queryActivityApplyPages(1, 3000, userId, aaer.getUserName(),
                aaer.getCollegeId(), aaer.getPeriodId(), aaer.getMajorId(), aaer.getClassId(), aaer.getOrgName(),
                aaer.getTheme(), aaer.getIsPass(), aaer.getCreateStartTime(), aaer.getCreateEndTime(),
                aaer.getStartTime(), aaer.getEndTime(), aaer.getSignsTime(), aaer.getSigneTime());
        for (AlumniActivityApplyPageVo aapv : result.getList()) {
            aapv.setPassName(ePassType.stringOf(aapv.getIsPass()));
        }

        if (result != null && result.getList().size() > 0) {
            int i = 0;
            for (AlumniActivityApplyPageVo acv : result.getList()) {
                Row dataRow = sheet.createRow(i + 1);
                dataRow.createCell(0).setCellValue(i + 1);//序号
                dataRow.createCell(1).setCellValue(acv.getName());//发起人
                dataRow.createCell(2).setCellValue(acv.getCollegeName());//学院
                dataRow.createCell(3).setCellValue(acv.getPeriodName());//学段
                dataRow.createCell(4).setCellValue(acv.getPeriodName());//专业
                dataRow.createCell(5).setCellValue(acv.getClassName());//班级
                dataRow.createCell(6).setCellValue(acv.getOrgName());//所属组织
                dataRow.createCell(7).setCellValue(acv.getTheme());//活动主题
                dataRow.createCell(8).setCellValue(TimeExchange.DateToString(acv.getStartTime(), "yyyy-MM-dd HH:mm:ss"));//活动开始时间
                dataRow.createCell(9).setCellValue(TimeExchange.DateToString(acv.getSignsTime(), "yyyy-MM-dd HH:mm:ss"));//报名开始时间
                dataRow.createCell(10).setCellValue((acv.getReportNumber() == null ? 0 : acv.getReportNumber()) + "人");//已报名
                dataRow.createCell(11).setCellValue((acv.getSigninNumber() == null ? 0 : acv.getSigninNumber()) + "人");//已签到
                dataRow.createCell(12).setCellValue(acv.getPassName());//状态
                dataRow.createCell(13).setCellValue(acv.getApplyUserAdmin());//审核人
                dataRow.createCell(14).setCellValue(acv.getPassTime() != null ? TimeExchange.DateToString(acv.getPassTime(), "yyyy-MM-dd HH:mm:ss") : "");//审核时间
                dataRow.createCell(15).setCellValue(TimeExchange.DateToString(acv.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));//创建时间
            }
            i++;
        }
        //endregion

        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "活动审核.xlsx", response);

        return CommonResult.ok("导出成功");
    }

    @Override
    public CommonResult initiateActivity(Integer userId, insertActivityRequest iar, BindingResult bindingResult) throws Exception {
        if (iar == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        AlumniUser operater = alumniUserService.queryDataById(userId);
        if (operater == null) {
            return CommonResult.fail("当前操作人身份已失效，发起失败");
        }

        //查看管理员是否已设置
        AlumniAdminApply aaa = alumniAdminApplyService.queryActivityAdmin();
        if (aaa == null) {
            return CommonResult.fail("校友活动模块未设置管理员，无法发起活动");
        }

        //region 时间校验
        //报名截止时间（需在活动时间之前）
        //活动时间和报名时间都不能出现开始时间大于结束时间的情况，并且报名时间必须在活动时间之前
        //活动时间和报名时间都不能出现开始时间大于结束时间的情况，并且报名时间必须在活动时间之前
        if (!TimeExchange.CompareDate(iar.getStartTime(), iar.getEndTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("活动开始时间不能大于活动结束时间");
        }
        if (!TimeExchange.CompareDate(iar.getSignsTime(), iar.getSigneTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("报名开始时间不能大于报名结束时间");
        }
        if (!TimeExchange.CompareDate(iar.getSigneTime(), iar.getStartTime(), "yyyy-MM-dd HH:mm:ss")) {
            return CommonResult.fail("报名时间必须在活动时间之前");
        }


        //endregion

        AlumniActivity aa = new AlumniActivity();
        aa.setOrgId(iar.getOrgId());
        aa.setOrgName(iar.getOrgName());
        aa.setTheme(iar.getTheme());
        aa.setThemeDetail(iar.getThemeDetail());
        aa.setStartTime(TimeExchange.StringToDate(iar.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
        aa.setEndTime(TimeExchange.StringToDate(iar.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        aa.setPoster(iar.getPoster());
        aa.setAddress(iar.getAddress());
        aa.setLng(iar.getLng());
        aa.setLat(iar.getLat());
        aa.setDescribes(iar.getDescribes());
        aa.setSignsTime(TimeExchange.StringToDate(iar.getSignsTime(), "yyyy-MM-dd HH:mm:ss"));
        aa.setSigneTime(TimeExchange.StringToDate(iar.getSigneTime(), "yyyy-MM-dd HH:mm:ss"));
        aa.setTotalNumber(iar.getTotalNumber());
        aa.setScope(iar.getScope());
        aa.setPhone(iar.getPhone());
        aa.setIsImage(iar.getIsImage());
        aa.setApplyUser(aaa.getAdmin());
        aa.setApplyUserAdmin(aaa.getAdminName());
        //如果是管理员的数据不用审
        if (operater.getRoleId() != null && (operater.getRoleId().intValue() == eRoleType.Super.getValue() || operater.getRoleId().intValue() == eRoleType.Admin.getValue())) {
            aa.setIsPass(ePassType.Passed.getValue());
            aa.setPassTime(new Date());
        } else {
            aa.setIsPass(ePassType.Approval.getValue());
        }

        int result = alumniActivityService.insertAlumniActivity(aa);
        if (result <= 0) {
            return CommonResult.fail("发起活动失败");
        }

        //发送微校通知
        //用户提交母校代言申请后，通知显示给母校代言管理员：“
        // [申请人姓名]，母校代言申请已提交，请及时对照片进行审核。
        if (aa.getIsPass().intValue() == ePassType.Approval.getValue()) {
            List<AlumniUser> users = alumniUserService.queryDataByIds(Arrays.asList(aaa.getAdmin().split(",")));
            List<String> cardnumbers = new ArrayList<>();
            for (AlumniUser user : users) {
                if (org.springframework.util.StringUtils.hasText(user.getCardNumber())) {
                    cardnumbers.add(user.getCardNumber());
                }
            }
            if (cardnumbers != null && cardnumbers.size() > 0) {
                String content = operater.getName() + "，活动申请已提交，请及时对" + aa.getTheme() + "进行审核。";
                CommonResult sendMessage = weiXiaoUtil.sendNotice(cardnumbers, "活动申请审核", "活动申请审核", content, null);
                if (!sendMessage.getCode().equals("200")) {
                    logger.info("微校通知发送失败，cardnumber：" + JSON.toJSON(cardnumbers) + "，Content：" + content);
                }
            }
        }

        return CommonResult.ok("发起活动成功");
    }
}

