package com.template.controller;


import com.alibaba.fastjson.JSON;
import com.template.api.AlumniImageControllerAPI;
import com.template.common.utils.WeiXiaoUtil;
import com.template.common.utils.paramUtils;
import com.template.model.enumModel.ePassType;
import com.template.model.pojo.*;
import com.template.model.request.insertImageRequest;
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.AlumniImageService;
import com.template.services.AlumniUserService;
import org.apache.commons.lang3.StringUtils;
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.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2024-11-25
 */
@RestController
public class AlumniImageController implements AlumniImageControllerAPI {
    @Autowired
    private WeiXiaoUtil weiXiaoUtil;
    @Autowired
    private AlumniImageService alumniImageService;
    @Autowired
    private AlumniUserService alumniUserService;
    @Autowired
    private AlumniAdminApplyService alumniAdminApplyService;

    private static Logger logger = LoggerFactory.getLogger(AlumniImageController.class);

    @Override
    public CommonResult queryImagePage(int currentPage, int pageCount, String userName, String orgName, Integer collegeId, Integer periodId, Integer majorId, Integer classId) {
        PageUtils<ImagePageVo> result = alumniImageService.imagePageDatas(currentPage, pageCount, userName, orgName, collegeId, periodId, majorId, classId);
        for (ImagePageVo ipv : result.getList()) {
            ipv.setImages(Arrays.asList(ipv.getImage().split(",")));
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult insertImage(insertImageRequest iir, Integer userId, BindingResult bindingResult) {
        if (iir == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        AlumniUser au = alumniUserService.queryDataById(userId);
        if (au == null) {
            return CommonResult.fail("操作人已失效，上传失败");
        }

        AlumniAdminApply aaa = alumniAdminApplyService.queryImageAdmin();
        if (aaa == null) {
            return CommonResult.fail("校友相册模块未设置管理员，无法上传图片");
        }

        AlumniImage ai = new AlumniImage();
        ai.setImage(StringUtils.join(iir.getImages(), ","));
        ai.setCategoryId(iir.getCategoryId());
        ai.setCategoryName(iir.getCategoryName());
        ai.setIsPass(ePassType.Approval.getValue());
        ai.setApplyUser(aaa.getAdmin());
        ai.setApplyUserName(aaa.getAdminName());

        int result = alumniImageService.insertAlumniImage(ai);
        if (result <= 0) {
            return CommonResult.fail("上传失败");
        }

        //发送微校通知
        //校友上传照片至相册后，系统生成通知发送给相册管理员：“
        // [上传人姓名]，相册分类为 [相册分类]。请及时对照片进行审核。”
        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 = au.getName() + "，相册分类为 " + iir.getCategoryName() + "。请及时对照片进行审核。";
            CommonResult sendMessage = weiXiaoUtil.sendNotice(cardnumbers, "校友相册审核", "校友相册审核", content, null);
            if (!sendMessage.getCode().equals("200")) {
                logger.info("微校通知发送失败，cardnumber：" + JSON.toJSON(cardnumbers) + "，Content：" + content + ",id" + result);
            }
        }

        return CommonResult.ok("上传成功");
    }

    @Override
    public CommonResult deleteImageById(int id) {
        int result = alumniImageService.deleteDataById(id);
        if (result <= 0) {
            return CommonResult.fail("删除失败");
        }

        return CommonResult.ok("删除成功");
    }

    @Override
    public CommonResult queryImageApplyPage(Integer userId, int currentPage, int pageCount, String userName, String orgName, Integer collegeId, Integer periodId, Integer majorId, Integer classId, Integer isPass, String startTime, String endTime) {
        PageUtils<ImageApplyPageVo> result = alumniImageService.imageApplyPageDatas(currentPage, userId, pageCount, userName, orgName, collegeId, periodId, majorId, classId, isPass, startTime, endTime);
        for (ImageApplyPageVo rg : result.getList()) {
            rg.setPassName(ePassType.stringOf(rg.getIsPass()));
            rg.setImages(Arrays.asList(rg.getImage().split(",")));
        }
        return CommonResult.ok(result);
    }

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

        AlumniImage ai = alumniImageService.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 = alumniImageService.updateAlumniImage(ai);
        if (result <= 0) {
            return CommonResult.fail("审核失败");
        }

        //发送微校通知
        //审核完成后系统生成通知发送给用户：“
        // [上传人姓名]，相册分类为 [相册分类]。已通过或已拒绝。”
        List<String> cardnumbers = new ArrayList<>();
        cardnumbers.add(cau.getCardNumber());
        String content = cau.getName() + "，相册分类为 " + ai.getCategoryName() + "。" + 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 queryMobileImagePage(Integer userId, int currentPage, int pageCount, String keyword, Integer categoryId) {
        PageUtils<ImageMobilePageVo> result = alumniImageService.imageMobilePageDatas(currentPage, pageCount, keyword, categoryId);
        for (ImageMobilePageVo imp : result.getList()) {
            imp.setImages(Arrays.asList(imp.getImage().split(",")));

            String collegeName = imp.getCollegeName() == null ? "" : imp.getCollegeName();
            String periodName = imp.getPeriodName() == null ? "" : "/" + imp.getPeriodName();
            String majorName = imp.getMajorName() == null ? "" : "/" + imp.getMajorName();
            String className = imp.getClassName() == null ? "" : "/" + imp.getClassName();
            imp.setSchoolInfo(collegeName + "" + periodName + "" + majorName + "/" + className);
            imp.setCategoryName("上传了" + imp.getImages().size() + "张照片至" + imp.getCategoryName());
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryMyImagePage(Integer userId, int currentPage, int pageCount, Integer isPass) {
        PageUtils<ImageMyPageVo> result = alumniImageService.imageMyPageDatas(currentPage, pageCount, userId, isPass);
        for (ImageMyPageVo imp : result.getList()) {
            imp.setImages(Arrays.asList(imp.getImage().split(",")));
            imp.setCategoryName("上传了" + imp.getImages().size() + "张照片至" + imp.getCategoryName());
        }
        return CommonResult.ok(result);
    }
}

