package com.template.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.template.api.AlumniClubControllerAPI;
import com.template.common.utils.ExcelUtils;
import com.template.common.utils.TimeExchange;
import com.template.common.utils.paramUtils;
import com.template.model.enumModel.ePassType;
import com.template.model.enumModel.eTopType;
import com.template.model.enumModel.ejoinType;
import com.template.model.pojo.AlumniClub;
import com.template.model.pojo.AlumniClubApply;
import com.template.model.pojo.AlumniUser;
import com.template.model.request.alumniClubExcelRequest;
import com.template.model.request.clubTopupRequest;
import com.template.model.request.insertClubRequest;
import com.template.model.request.updateClubRequest;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.*;
import com.template.services.AlumniClubApplyService;
import com.template.services.AlumniClubService;
import com.template.services.AlumniUserService;
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.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

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

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2024-11-20
 */
@RestController
public class AlumniClubController implements AlumniClubControllerAPI {

    @Autowired
    private AlumniClubApplyService alumniClubApplyService;
    @Autowired
    private AlumniClubService alumniClubService;
    @Autowired
    private AlumniUserService alumniUserService;
    private static Logger logger = LoggerFactory.getLogger(AlumniClubController.class);

    @Override
    public CommonResult insertClubData(insertClubRequest icr, BindingResult bindingResult) {
        if (icr == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        AlumniClub ac = new AlumniClub();
        ac.setName(icr.getName());
        ac.setNumber(icr.getNumber());
        ac.setIsTop(icr.getIsTop() != null ? icr.getIsTop() : eTopType.UnTop.getValue());
        ac.setCategoryId(icr.getCategoryId());
        ac.setCategoryName(icr.getCategoryName());
        if (org.springframework.util.StringUtils.hasText(icr.getDescription())) {
            ac.setDescription(icr.getDescription());
        }
        if (org.springframework.util.StringUtils.hasText(icr.getContact())) {
            ac.setContact(icr.getContact());
        }

        ac.setAdmin(StringUtils.join(icr.getAdmins().stream().map(UserVo::getId).collect(Collectors.toList()), ","));
        ac.setAdminName(StringUtils.join(icr.getAdmins().stream().map(UserVo::getName).collect(Collectors.toList()), ","));

        int result = alumniClubService.insertAlumniClub(ac);
        if (result <= 0) {
            return CommonResult.fail("创建失败");
        }

        return CommonResult.ok("创建成功");
    }

    @Override
    public CommonResult updateClubData(updateClubRequest ucr, BindingResult bindingResult) {
        if (ucr == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        AlumniClub ac = alumniClubService.queryDataById(ucr.getId());
        if (ac == null) {
            return CommonResult.fail("数据已失效，更新失败");
        }

        ac.setNumber(ucr.getNumber());
        ac.setIsTop(ucr.getIsTop() != null ? ucr.getIsTop() : ac.getIsTop());
        ac.setName(org.springframework.util.StringUtils.hasText(ucr.getName()) ? ucr.getName() : ac.getName());
        ac.setCategoryId(ucr.getCategoryId() != null ? ucr.getCategoryId() : ac.getCategoryId());
        ac.setCategoryName(org.springframework.util.StringUtils.hasText(ucr.getCategoryName()) ? ucr.getCategoryName() : ac.getCategoryName());
        ac.setDescription(org.springframework.util.StringUtils.hasText(ucr.getDescription()) ? ucr.getDescription() : ac.getDescription());
        ac.setContact(org.springframework.util.StringUtils.hasText(ucr.getContact()) ? ucr.getContact() : ac.getContact());
        ac.setAdmin(StringUtils.join(ucr.getAdmins().stream().map(UserVo::getId).collect(Collectors.toList()), ","));
        ac.setAdminName(StringUtils.join(ucr.getAdmins().stream().map(UserVo::getName).collect(Collectors.toList()), ","));

        int result = alumniClubService.updateAlumniClub(ac);
        if (result <= 0) {
            return CommonResult.fail("更新失败");
        }

        return CommonResult.ok("更新成功");
    }

    @Override
    public CommonResult queryClubPage(int currentPage, int pageCount, String name, String userName, String startTime, String endTime, Integer categoryId) {
        PageUtils<AlumniClub> result = alumniClubService.queryPageList(currentPage, pageCount, name, userName, startTime, endTime, categoryId);
        if (result.getList() != null && result.getList().size() > 0) {
            List<String> adminIds = result.getList().stream().map(AlumniClub::getAdmin).collect(Collectors.toList());
            String adminStr = StringUtils.join(adminIds, ",");
            List<String> affiliates = Arrays.asList(adminStr.trim().split(",")).stream().distinct().collect(Collectors.toList());
            if (affiliates != null && affiliates.size() > 0) {
                List<AlumniUser> users = alumniUserService.queryDataByIds(affiliates);
                if (users != null && users.size() > 0) {
                    for (AlumniClub ac : result.getList()) {
                        List<UserVo> uvs = new ArrayList<>();
                        if (org.springframework.util.StringUtils.hasText(ac.getAdmin())) {
                            List<String> admins = Arrays.asList(ac.getAdmin().trim().split(","));
                            for (String admin : admins) {
                                Optional<AlumniUser> oau = users.stream().filter(e -> e.getId().intValue() == Integer.valueOf(admin).intValue()).findFirst();
                                if (oau != null && oau.isPresent()) {
                                    UserVo uv = new UserVo();
                                    uv.setId(oau.get().getId());
                                    uv.setName(oau.get().getName());
                                    uv.setCardNumber(oau.get().getCardNumber());
                                    uvs.add(uv);
                                }
                            }
                        }
                        ac.setAdmins(uvs);
                    }
                }
            }
        }

        return CommonResult.ok(result);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult clubTopup(clubTopupRequest ctr, BindingResult bindingResult) throws Exception {

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

        AlumniClub ac = alumniClubService.queryDataById(ctr.getId());
        if (ac == null) {
            return CommonResult.fail("数据已失效，无法进行置顶操作");
        }

        try {
            //将其他置顶数据取消置顶
            List<AlumniClub> acs = alumniClubService.findTopClubs();
            if (acs != null && acs.size() > 0) {
                for (AlumniClub acData : acs) {
                    acData.setIsTop(eTopType.UnTop.getValue());
                }
                boolean insertBatch = alumniClubService.updateBatchById(acs);
                if (!insertBatch) {
                    logger.info("组织更新失败，置顶失败！");
                    throw new Exception("组织更新失败，置顶失败！");
                }
            }

            ac.setIsTop(ctr.getIsTop());
            int result = alumniClubService.updateAlumniClub(ac);
            if (result <= 0) {
                logger.info("组织更新失败，置顶失败！");
                throw new Exception("组织更新失败，置顶失败！");
            }
        } catch (Exception e) {
            logger.info("组织置顶异常信息：" + e.getMessage());
            throw new Exception("组织置顶失败！");
        }
        return CommonResult.ok("置顶成功");
    }

    @Override
    public CommonResult getAlumniClubExcel(alumniClubExcelRequest 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("创建时间");

        List<ClubExcelVo> result = alumniClubService.queryDataList(acer.getName(), acer.getUserName(), acer.getStartTime(), acer.getEndTime(), acer.getCategoryId());
        if (result != null && result.size() > 0) {
            int i = 0;
            for (ClubExcelVo cev : result) {
                Row dataRow = sheet.createRow(i + 1);
                dataRow.createCell(0).setCellValue(i + 1);
                dataRow.createCell(1).setCellValue(cev.getName());
                dataRow.createCell(2).setCellValue(cev.getCategoryName());
                dataRow.createCell(3).setCellValue(cev.getNumber() + "人");
                dataRow.createCell(4).setCellValue(cev.getAdminName());
                dataRow.createCell(5).setCellValue(cev.getCreateUser());
                dataRow.createCell(6).setCellValue(cev.getCreateTime());
            }
            i++;
        }

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

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

    @Override
    public CommonResult queryHomeClub(Integer userId) {
        AlumniUser au = alumniUserService.queryDataById(userId);
        if (au == null) {
            return CommonResult.fail("用户数据已失效，无法查看组织数据");
        }
        HomeClubVo result = new HomeClubVo();
        List<AlumniClub> topClubs = alumniClubService.findTopClubs();
        if (topClubs != null && topClubs.size() > 0) {
            AlumniClub topData = topClubs.get(0);
            result.setId(topData.getId());
            result.setName(topData.getName());
            result.setDescription(topData.getDescription());
            result.setContact(topData.getContact());
            result.setCreateTime(TimeExchange.chineseDateShortTime(topData.getCreateTime()) + "成立");
            //查看当前登陆人是否已加入 未加入 或 申请中
            if (au.getOrgId() != null && au.getOrgId().intValue() ==topData.getId().intValue()) {
                result.setIsJoin(ejoinType.Join.getValue());
            }else{
                List<AlumniClubApply> existApply = alumniClubApplyService.queryClubApplys(userId);
                if(existApply != null && existApply.size() > 0){
                    Optional<AlumniClubApply> oExist = existApply.stream().filter(e -> e.getClubId().intValue() == topData.getId().intValue()).findFirst();
                    if(oExist !=null && oExist.isPresent()){
                        if(oExist.get().getIsPass().intValue() == ePassType.Approval.getValue()){
                            result.setIsJoin(ejoinType.Apply.getValue());
                        }else if(oExist.get().getIsPass().intValue() == ePassType.Passed.getValue()){
                            result.setIsJoin(ejoinType.Join.getValue());
                        }
                    }
                }else{
                    result.setIsJoin(ejoinType.Unjoin.getValue());
                }
            }
        }
        List<OtherClubVo> resultDetails = alumniClubService.CategoryCountDatas();
        result.setOtherClub(resultDetails);
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryClubByCategoryId(int currentPage, int pageCount,Integer userId, int categoryId, String keyword) {
        PageUtils<AlumniClub> result = alumniClubService.queryPageByCategory(currentPage, pageCount, categoryId, keyword);

        IPage<ClubListDataVO> userData = new Page<>();
        PageUtils<ClubListDataVO> finallResult = new PageUtils<ClubListDataVO>(userData);
        List<ClubListDataVO> datas = new ArrayList<>();
        List<AlumniClubApply> existApply = alumniClubApplyService.queryClubApplys(userId);
        for (AlumniClub ac : result.getList()) {
            ClubListDataVO data = new ClubListDataVO();
            data.setId(ac.getId());
            data.setName(ac.getName());
            data.setDescription(ac.getDescription());
            data.setContact(ac.getContact());

            if(existApply != null && existApply.size() > 0){
                Optional<AlumniClubApply> oExist = existApply.stream().filter(e -> e.getClubId().intValue() == ac.getId().intValue()).findFirst();
                if(oExist !=null && oExist.isPresent()){
                    if(oExist.get().getIsPass().intValue() == ePassType.Approval.getValue()){
                        data.setIsJoin(ejoinType.Apply.getValue());
                    }else if(oExist.get().getIsPass().intValue() == ePassType.Passed.getValue()){
                        data.setIsJoin(ejoinType.Join.getValue());
                    }
                }
            }else{
                data.setIsJoin(ejoinType.Unjoin.getValue());
            }

            datas.add(data);
        }

        finallResult.setList(datas);
        finallResult.setTotalPage(result.getTotalPage());
        finallResult.setPageSize(result.getPageSize());
        finallResult.setCurrentPage(result.getCurrentPage());
        finallResult.setTotalCount(result.getTotalCount());
        return CommonResult.ok(finallResult);
    }

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

        return CommonResult.ok(result);
    }

}

