package com.template.controller;


import com.alibaba.fastjson.JSON;
import com.template.api.AlumniClubApplyControllerAPI;
import com.template.common.utils.ExcelUtils;
import com.template.common.utils.WeiXiaoUtil;
import com.template.common.utils.paramUtils;
import com.template.model.enumModel.ePassType;
import com.template.model.pojo.AlumniClub;
import com.template.model.pojo.AlumniClubApply;
import com.template.model.pojo.AlumniUser;
import com.template.model.request.alumniClubApplyExcelRequest;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.ApplyClubVo;
import com.template.model.vo.ClubExcelVo;
import com.template.services.AlumniClubApplyService;
import com.template.services.AlumniClubService;
import com.template.services.AlumniUserService;
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.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
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.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2024-11-22
 */
@RestController
public class AlumniClubApplyController implements AlumniClubApplyControllerAPI {
    @Autowired
    private WeiXiaoUtil weiXiaoUtil;
    @Autowired
    private AlumniClubService alumniClubService;
    @Autowired
    private AlumniUserService alumniUserService;
    @Autowired
    private AlumniClubApplyService alumniClubApplyService;
    private static Logger logger = LoggerFactory.getLogger(AlumniClubApplyController.class);

    @Override
    public CommonResult joinClubApply(Integer userId, Integer id) {
        AlumniUser au = alumniUserService.queryDataById(userId);
        if (au == null) {
            return CommonResult.fail("当前操作人已失效，无法加入");
        }

        //向其他组织发起过数据就不允许再发起
        List<AlumniClubApply> existApply = alumniClubApplyService.queryClubApplys(userId);
        if(existApply != null && existApply.size() > 0){
            return CommonResult.fail("已存在组织加入申请记录，无法加入多个组织");
        }

        AlumniClub ac = alumniClubService.queryDataById(id);
        if (ac == null) {
            return CommonResult.fail("组织数据已失效，无法加入");
        }

        //人数是否超过组织规定的人数上限
        int member = alumniClubApplyService.queryClubMember(id);
        if (member >= ac.getNumber().intValue()) {
            return CommonResult.fail("该组织人数上限已满，无法加入");
        }

        AlumniClubApply acp = new AlumniClubApply();
        acp.setName(ac.getName());
        acp.setClubId(ac.getId());
        acp.setApplyUser(ac.getAdmin());
        acp.setApplyUserName(ac.getAdminName());
        acp.setIsPass(ePassType.Approval.getValue());

        int result = alumniClubApplyService.insertAlumniClubApply(acp);
        if (result <= 0) {
            return CommonResult.fail("入会失败");
        }

        //发送微校通知
        //校友申请加入组织后，通知显示给组织管理员：“
        // [申请人姓名]，已申请加入‘[申请组织]’，请尽快审核。”
        List<AlumniUser> users= alumniUserService.queryDataByIds(Arrays.asList(ac.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 = au.getName()+"，已申请加入 "+ac.getName()+"，请尽快审核。";
            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 queryClubProcessPage(Integer userId, int currentPage, int pageCount, String name, String userName, Integer isPass, Integer collegeId, Integer periodId, Integer majorId, Integer classId, String startTime, String endTime, Integer categoryId) {

        PageUtils<ApplyClubVo> result = alumniClubApplyService.queryClubApplys(userId, currentPage, pageCount, name, userName, isPass, collegeId, periodId, majorId, classId, startTime, endTime, categoryId);
        for (ApplyClubVo acv : result.getList()) {
            acv.setPassTime(acv.getIsPass().intValue() == ePassType.Approval.getValue() ? null : acv.getPassTime());
            acv.setPassName(ePassType.stringOf(acv.getIsPass()));
        }
        return CommonResult.ok(result);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult toExamineClub(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("当前操作人已失效，无法进行审核操作");
        }

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

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

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

        AlumniClub ac = alumniClubService.queryDataById(aca.getClubId());
        if (ac == null) {
            return CommonResult.fail("组织数据已失效，无法进行审核操作");
        }

        if (isPass.intValue() == ePassType.Passed.getValue()) {
            //人数是否超过组织规定的人数上限
            int member = alumniClubApplyService.queryClubMember(id);
            if (member >= ac.getNumber().intValue()) {
                return CommonResult.fail("该组织人数上限已满，无法加入");
            }

            au.setOrgId(ac.getId());
            au.setOrgName(ac.getName());
        }
        aca.setIsPass(isPass);
        aca.setPassValue(passValue);

        try {
            int result = alumniClubApplyService.updateAlumniClubApply(aca);
            if (result <= 0) {
                logger.info("审核更新失败，审核失败！");
                throw new Exception("审核更新失败，审核失败！");
            }
            int updateUser = alumniUserService.updateAlumniUser(au);
            if (updateUser <= 0) {
                logger.info("用户更新失败，审核失败！");
                throw new Exception("用户更新失败，审核失败！");
            }
        } catch (Exception e) {
            logger.info("入会审核组织异常信息：" + e.getMessage());
            throw new Exception("入会审核失败！");
        }

        //发送微校通知
        //审核完成后系统生成通知发送给用户：“
        // [申请人姓名]，申请加入组织名称 [组织名称]。已通过或已拒绝”。
        List<String> cardnumbers= new ArrayList<>();
        cardnumbers.add(cau.getCardNumber());
        String content = cau.getName()+"，申请加入组织名称 "+ac.getName()+"。"+ePassType.stringOf(aca.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 queryClubProcessExcel(Integer userId, alumniClubApplyExcelRequest acer, HttpServletResponse response, BindingResult bindingResult) {

        if (acer == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }


        //导出
        Workbook workbook = new XSSFWorkbook();
        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("创建时间");


        List<ApplyClubVo> result = alumniClubApplyService.queryClubExcelApplys(userId, acer.getName(), acer.getUserName(), acer.getIsPass(), acer.getCollegeId(), acer.getPeriodId(), acer.getMajorId(), acer.getClassId(), acer.getStartTime(), acer.getEndTime());


        if (result != null && result.size() > 0) {
            int i = 0;
            for (ApplyClubVo acv : result) {
                acv.setPassTime(acv.getIsPass().intValue() == ePassType.Approval.getValue() ? null : acv.getPassTime());
                acv.setPassName(ePassType.stringOf(acv.getIsPass()));
                Row dataRow = sheet.createRow(i + 1);
                dataRow.createCell(0).setCellValue(i + 1);
                dataRow.createCell(1).setCellValue(acv.getApplyName());
                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.getName());
                dataRow.createCell(7).setCellValue(acv.getApplyUserName());
                dataRow.createCell(8).setCellValue(acv.getName());
                dataRow.createCell(9).setCellValue(acv.getPassTime());
                dataRow.createCell(10).setCellValue(acv.getCreateTime());
            }
            i++;
        }

        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "校友组织入会审核管理.xlsx", response);

        return CommonResult.ok(result);
    }
}

