package com.template.controller;


import com.alibaba.fastjson.JSON;
import com.template.api.AlumniEndorseControllerAPI;
import com.template.common.utils.*;
import com.template.model.enumModel.*;
import com.template.model.pojo.AlumniAdminApply;
import com.template.model.pojo.AlumniEndorse;
import com.template.model.pojo.AlumniImage;
import com.template.model.pojo.AlumniUser;
import com.template.model.request.alumniEndorseApplyExcelRequest;
import com.template.model.request.alumniEndorseExcelRequest;
import com.template.model.request.initiateEndorseRequest;
import com.template.model.request.insertEndorseRequest;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.*;
import com.template.services.AlumniAdminApplyService;
import com.template.services.AlumniEndorseService;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
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;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2024-11-29
 */
@RestController
public class AlumniEndorseController implements AlumniEndorseControllerAPI {

    @Autowired
    private WeiXiaoUtil weiXiaoUtil;
    @Autowired
    private AlumniUserService alumniUserService;
    @Autowired
    private AlumniEndorseService alumniEndorseService;
    @Autowired
    private AlumniAdminApplyService alumniAdminApplyService;
    private static Logger logger = LoggerFactory.getLogger(AlumniEndorseController.class);

    @Override
    public CommonResult insertEndorseData(insertEndorseRequest ier, Integer userId, BindingResult bindingResult) {
        if (ier == 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.queryEndorseAdmin();
        if (aaa == null) {
            return CommonResult.fail("校友活动模块未设置管理员，无法新增活动");
        }

        AlumniUser result = alumniUserService.queryDataByCardNumber(ier.getCardNumber());
        if (result == null) {
            return CommonResult.fail("系统中不存在此用户，无法发起母校代言操作");
        }

        AlumniEndorse ae = new AlumniEndorse();
        ae.setDataNo(StrUtils.getUUIDBits(16));
        ae.setCardNumber(result.getCardNumber());
        ae.setName(ier.getName());
        ae.setUserId(result.getId());
        ae.setImage(ier.getImage());
        ae.setDescript(ier.getDescript());
        ae.setApplyUser(aaa.getAdmin());
        ae.setApplyUserName(aaa.getAdminName());
        ae.setPreferredMethod(operater.getRoleId() != null && operater.getRoleId().intValue() > 0 ? ePreferredMethod.College.getValue() : ePreferredMethod.Self.getValue());
        //如果是管理员的数据不用审
        if (operater.getRoleId() != null && (operater.getRoleId().intValue() == eRoleType.Super.getValue() || operater.getRoleId().intValue() == eRoleType.Admin.getValue())) {
            ae.setIsPass(ePassType.Passed.getValue());
            ae.setPassTime(new Date());
        } else {
            ae.setIsPass(ePassType.Approval.getValue());
        }

        int insertResult = alumniEndorseService.insertAlumniEndorse(ae);
        if (insertResult <= 0) {
            return CommonResult.fail("新增失败");
        }

        //发送微校通知
        //用户提交母校代言申请后，通知显示给母校代言管理员：“
        // [申请人姓名]，母校代言申请已提交，请及时对照片进行审核。
        if(ae.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()+"，母校代言申请已提交，请及时对照片进行审核。";
                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 queryEndorsePage(int currentPage, int pageCount, String keyword, Integer collegeId, Integer periodId, Integer majorId, Integer classId, String startTime, String endTime) {
        PageUtils<AlumniEndorsePageVo> result = alumniEndorseService.alumniEndorsePageDatas(currentPage, pageCount, collegeId, periodId, majorId, classId, startTime, endTime, keyword);
        for (AlumniEndorsePageVo aepv : result.getList()) {
            aepv.setPreferredMethodName(ePreferredMethod.stringOf(aepv.getPreferredMethod().intValue()));
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult getAlumniEndorseExcel(alumniEndorseExcelRequest aeer, HttpServletResponse response, BindingResult bindingResult) {
        if (aeer == 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("创建时间");

        PageUtils<AlumniEndorsePageVo> result = alumniEndorseService.alumniEndorsePageDatas(1, 3000,
                aeer.getCollegeId(), aeer.getPeriodId(), aeer.getMajorId(), aeer.getClassId(), aeer.getStartTime(), aeer.getEndTime(), aeer.getKeyword());
        for (AlumniEndorsePageVo aepv : result.getList()) {
            aepv.setPreferredMethodName(ePreferredMethod.stringOf(aepv.getPreferredMethod().intValue()));
        }

        if (result != null && result.getList().size() > 0) {
            int i = 0;
            for (AlumniEndorsePageVo aepv : result.getList()) {
                Row dataRow = sheet.createRow(i + 1);
                dataRow.createCell(0).setCellValue(i + 1);//序号
                dataRow.createCell(1).setCellValue(aepv.getDataNo());//编号
                dataRow.createCell(2).setCellValue(aepv.getName());//姓名
                dataRow.createCell(3).setCellValue(aepv.getCardNumber());//微卡
                dataRow.createCell(4).setCellValue(aepv.getPhone());//手机
                dataRow.createCell(5).setCellValue(aepv.getCollegeName());//学院
                dataRow.createCell(6).setCellValue(aepv.getPeriodName());//学段
                dataRow.createCell(7).setCellValue(aepv.getMajorName());//专业
                dataRow.createCell(8).setCellValue(aepv.getClassName());//班级
                dataRow.createCell(9).setCellValue(aepv.getPreferredMethodName());//上榜方式
                dataRow.createCell(10).setCellValue(aepv.getDescript());//人物简介
                dataRow.createCell(11).setCellValue(aepv.getCreateTime());//创建时间
            }
            i++;
        }
        //endregion

        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "母校代言.xlsx", response);

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

    @Override
    public CommonResult deleteEndorseById(int id) {
        AlumniEndorse ae = alumniEndorseService.queryDataById(id);
        if (ae == null) {
            return CommonResult.fail("母校代言数据已失效，无法删除");
        }

        int result = alumniEndorseService.deleteDataById(id);
        if (result <= 0) {
            return CommonResult.fail("删除失败");
        }
        return CommonResult.ok("删除成功");
    }

    @Override
    public CommonResult queryEndorseApplyPage(int currentPage, int pageCount, Integer userId, String keyword, String name, Integer isPass, Integer collegeId, Integer periodId, Integer majorId, Integer classId, String startTime, String endTime) {

        PageUtils<AlumniEndorseApplyPageVo> result = alumniEndorseService.alumniEndorsePageApplyDatas(currentPage, pageCount, userId, collegeId, periodId, majorId, classId, startTime, endTime, keyword, name, isPass);
        for (AlumniEndorseApplyPageVo aepv : result.getList()) {
            aepv.setPreferredMethodName(ePreferredMethod.stringOf(aepv.getPreferredMethod().intValue()));
            aepv.setPassName(ePassType.stringOf(aepv.getIsPass()));
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult getAlumniEndorseApplyExcel(alumniEndorseApplyExcelRequest aeaer, Integer userId, HttpServletResponse response, BindingResult bindingResult) throws ParseException {
        if (aeaer == 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("创建时间");

        PageUtils<AlumniEndorseApplyPageVo> result = alumniEndorseService.alumniEndorsePageApplyDatas(1, 3000, userId, aeaer.getCollegeId(),
                aeaer.getPeriodId(), aeaer.getMajorId(), aeaer.getClassId(), aeaer.getStartTime(), aeaer.getEndTime(), aeaer.getKeyword(), aeaer.getName(), aeaer.getIsPass());
        for (AlumniEndorseApplyPageVo aepv : result.getList()) {
            aepv.setPreferredMethodName(ePreferredMethod.stringOf(aepv.getPreferredMethod().intValue()));
            aepv.setPassName(ePassType.stringOf(aepv.getIsPass()));
        }

        if (result != null && result.getList().size() > 0) {
            int i = 0;
            for (AlumniEndorseApplyPageVo aepv : result.getList()) {
                Row dataRow = sheet.createRow(i + 1);
                dataRow.createCell(0).setCellValue(i + 1);//序号
                dataRow.createCell(1).setCellValue(aepv.getDataNo());//编号
                dataRow.createCell(2).setCellValue(aepv.getName());//姓名
                dataRow.createCell(3).setCellValue(aepv.getCardNumber());//微卡
                dataRow.createCell(4).setCellValue(aepv.getPhone());//手机
                dataRow.createCell(5).setCellValue(aepv.getCollegeName());//学院
                dataRow.createCell(6).setCellValue(aepv.getPeriodName());//学段
                dataRow.createCell(7).setCellValue(aepv.getMajorName());//专业
                dataRow.createCell(8).setCellValue(aepv.getClassName());//班级
                dataRow.createCell(9).setCellValue(aepv.getPreferredMethodName());//上榜方式
                dataRow.createCell(10).setCellValue(aepv.getDescript());//人物简介
                dataRow.createCell(11).setCellValue(aepv.getPassName());//审核时间
                dataRow.createCell(12).setCellValue(aepv.getCreateTime());//创建时间
            }
            i++;
        }
        //endregion

        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "母校代言审核.xlsx", response);

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

    @Override
    public CommonResult toExamineEndorse(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("当前操作人已失效，无法进行审核操作");
        }

        AlumniEndorse ai = alumniEndorseService.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 = alumniEndorseService.updateAlumniEndorse(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 queryMobileEndorsePage(int currentPage, int pageCount, String keyword) {
        PageUtils<MoblieEndorsePageVo> result = alumniEndorseService.mobileEndorsePageDatas(currentPage, pageCount, keyword);
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryEndorseById(int id) {
        AlumniEndorse result = alumniEndorseService.queryDataById(id);
        if (result == null) {
            return CommonResult.fail("数据已失效，查看详情失败");
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult initiateApplication(initiateEndorseRequest ier, Integer userId, BindingResult bindingResult) {
        if (ier == 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.queryEndorseAdmin();
        if (aaa == null) {
            return CommonResult.fail("校友活动模块未设置管理员，无法新增活动");
        }

        AlumniUser result = alumniUserService.queryDataById(userId);
        if (result == null) {
            return CommonResult.fail("系统中不存在此用户，无法发起母校代言操作");
        }

        AlumniEndorse ae = new AlumniEndorse();
        ae.setDataNo(StrUtils.getUUIDBits(16));
        ae.setCardNumber(result.getCardNumber());
        ae.setName(result.getName());
        ae.setUserId(result.getId());
        ae.setImage(ier.getImage());
        ae.setDescript(ier.getDescript());
        ae.setApplyUser(aaa.getAdmin());
        ae.setApplyUserName(aaa.getAdminName());
        if(ier.getPreferredMethod() == null){
            ae.setPreferredMethod(operater.getRoleId() != null && operater.getRoleId().intValue() > 0 ? ePreferredMethod.College.getValue() : ePreferredMethod.Self.getValue());
        }else{
            ae.setPreferredMethod(ier.getPreferredMethod());
        }

        //如果是管理员的数据不用审
        if (operater.getRoleId() != null && (operater.getRoleId().intValue() == eRoleType.Super.getValue() || operater.getRoleId().intValue() == eRoleType.Admin.getValue())) {
            ae.setIsPass(ePassType.Passed.getValue());
            ae.setPassTime(new Date());
        } else {
            ae.setIsPass(ePassType.Approval.getValue());
        }

        int insertResult = alumniEndorseService.insertAlumniEndorse(ae);
        if (insertResult <= 0) {
            return CommonResult.fail("新增失败");
        }

        //发送微校通知
        //用户提交母校代言申请后，通知显示给母校代言管理员：“
        // [申请人姓名]，母校代言申请已提交，请及时对照片进行审核。
        if(ae.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()+"，母校代言申请已提交，请及时对照片进行审核。";
                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 applicationRecord(int currentPage, int pageCount, Integer userId,int weekType) {
        PageUtils<ApplicationRecordPageVo> result = alumniEndorseService.applicationRecordDatas(currentPage, pageCount, userId, weekType);

        for (ApplicationRecordPageVo arpv : result.getList()) {
            arpv.setPreferredMethodName(ePreferredMethod.stringOf(arpv.getPreferredMethod().intValue()));
            arpv.setPassName(ePassType.stringOf(arpv.getIsPass()));
        }

        return CommonResult.ok(result);
    }

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

        return CommonResult.ok(result);
    }


}

