package com.template.controller;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.template.api.SmartSectionControllerAPI;
import com.template.common.utils.paramUtils;
import com.template.model.pojo.SmartExamtype;
import com.template.model.pojo.SmartSection;
import com.template.model.pojo.SmartSectionDetail;
import com.template.model.pojo.SmartUser;
import com.template.model.request.insertSectionRequest;
import com.template.model.request.sectionDetailRequest;
import com.template.model.request.updateSectionRequest;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.AffiliateUserVo;
import com.template.model.vo.ExamTypesVo;
import com.template.model.vo.SmartSectionPageVo;
import com.template.model.vo.UserVo;
import com.template.services.SmartExamtypeService;
import com.template.services.SmartSectionDetailService;
import com.template.services.SmartSectionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;

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

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-05-28
 */
@RestController
public class SmartSectionController implements SmartSectionControllerAPI {

    @Autowired
    private SmartSectionService smartSectionService;

    @Autowired
    private SmartExamtypeService smartExamtypeService;

    @Autowired
    private SmartSectionDetailService smartSectionDetailService;

    @Override
    public CommonResult insertSection(insertSectionRequest isr, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        SmartSection ss = new SmartSection();
        ss.setGradeId(isr.getGradeId());
        ss.setTermId(isr.getTermId());
        ss.setExamType(StringUtils.join(isr.getExamTypes(), ","));
        ss.setPassLine(isr.getPassLine());
        ss.setGoodLine(isr.getGoodLine());
        ss.setExcellentLine(isr.getExcellentLine());

        int result = smartSectionService.insertSmartSection(ss);
        if (result <= 0) {
            return CommonResult.fail("分段添加失败！");
        }

        if (isr.getDetails() != null && isr.getDetails().size() > 0) {
            List<SmartSectionDetail> ssds = new ArrayList<>();
            for (sectionDetailRequest sdr : isr.getDetails()) {
                SmartSectionDetail ssd = new SmartSectionDetail();
                ssd.setSectionId(result);
                ssd.setSubjectId(sdr.getSubjectId());
                ssd.setSubjectName(sdr.getSubjectName());
                ssd.setScore(sdr.getScore());
                ssds.add(ssd);
            }

            if (ssds != null && ssds.size() > 0) {
                boolean detailBatch = smartSectionDetailService.saveBatch(ssds);
                if (!detailBatch) {
                    return CommonResult.fail("分段添加失败！");
                }
            }
        }

        return CommonResult.ok("分段添加成功");
    }

    @Override
    public CommonResult updateSection(updateSectionRequest usr, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        SmartSection oldSection = smartSectionService.getSmartById(usr.getId());
        if (oldSection == null) {
            return CommonResult.fail("分段数据已失效，编辑失败");
        }

        oldSection.setGradeId(usr.getGradeId());
        oldSection.setTermId(usr.getTermId());
        oldSection.setExamType(StringUtils.join(usr.getExamTypes(), ","));
        oldSection.setPassLine(usr.getPassLine());
        oldSection.setGoodLine(usr.getGoodLine());
        oldSection.setExcellentLine(usr.getExcellentLine());
        int updateSection = smartSectionService.updateSmartSection(oldSection);
        if (updateSection <= 0) {
            return CommonResult.fail("分段编辑失败");
        }

        if (usr.getDetails() != null && usr.getDetails().size() > 0) {
            smartSectionDetailService.deletedDetailBySenctionId(usr.getId());

            List<SmartSectionDetail> ssds = new ArrayList<>();
            for (sectionDetailRequest sdr : usr.getDetails()) {
                SmartSectionDetail ssd = new SmartSectionDetail();
                ssd.setSectionId(oldSection.getId());
                ssd.setSubjectId(sdr.getSubjectId());
                ssd.setSubjectName(sdr.getSubjectName());
                ssd.setScore(sdr.getScore());
                ssds.add(ssd);
            }

            if (ssds != null && ssds.size() > 0) {
                boolean detailBatch = smartSectionDetailService.saveBatch(ssds);
                if (!detailBatch) {
                    return CommonResult.fail("分段编辑失败！");
                }
            }
        }

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

    @Override
    public CommonResult queryPageSmartSection(int currentPage, int pageCount) {
        PageUtils<SmartSectionPageVo> result = smartSectionService.querySmartSectionPages(currentPage, pageCount);

        if (result != null && result.getList() != null && result.getList().size() > 0) {
            List<String> examTypeIds = Arrays.asList(StringUtils.join(result.getList().stream().map(SmartSectionPageVo::getExamType).collect(Collectors.toList()), ",").split(","));
            List<SmartExamtype> examtypes = examTypeIds != null && examTypeIds.size() > 0 ? smartExamtypeService.getSmartByIds(examTypeIds) : new ArrayList<>();

            List<Integer> sectionIds = result.getList().stream().map(SmartSectionPageVo::getId).collect(Collectors.toList());

            List<SmartSectionDetail> details = smartSectionDetailService.getSmartByIds(sectionIds);

            for (SmartSectionPageVo data:result.getList()){
                List<ExamTypesVo> datas = new ArrayList<>();
                if (data.getExamType() != null) {
                    List<String> examtypeIds = Arrays.asList(data.getExamType().split(","));
                    for (String exam : examtypeIds) {
                        if (!ObjectUtils.isEmpty(exam)) {
                            Optional<SmartExamtype> examtype = examtypes.stream().filter(e -> e.getId().equals(Integer.valueOf(exam))).findFirst();
                            if (examtype != null && examtype.isPresent()) {
                                ExamTypesVo ev = new ExamTypesVo();
                                ev.setId(examtype.get().getId());
                                ev.setName(examtype.get().getName());
                                datas.add(ev);
                            }
                        }
                    }
                }
                data.setExamTypes(datas);
                List<SmartSectionDetail> ownerDetails = details.stream().filter(e -> e.getSectionId().equals(data.getId())).collect(Collectors.toList());
                if(ownerDetails != null && ownerDetails.size() > 0){
                    data.setDetails(ownerDetails);
                }
            }
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult deleteSmartSection(int id) {
        SmartSection data = smartSectionService.getSmartById(id);
        if(data == null){
            return CommonResult.fail("当前数据已失效，删除失败");
        }

        int result = smartSectionService.deleteSmartUserById(id);
        if(result <= 0){
            return CommonResult.fail("删除失败");
        }

        smartSectionDetailService.deletedDetailBySenctionId(id);

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


}

