package com.srs.diagnostic.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.DateUtils;
import com.srs.diagnostic.domain.DiaReportItems;
import com.srs.diagnostic.domain.DiaReportStandards;
import com.srs.diagnostic.mapper.DiaReportStandardsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.diagnostic.mapper.DiaReportStudentCompletionMapper;
import com.srs.diagnostic.domain.DiaReportStudentCompletion;
import com.srs.diagnostic.service.IDiaReportStudentCompletionService;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import static com.srs.common.utils.DateUtils.getNowDate;
import static com.srs.common.utils.SecurityUtils.getUsername;

/**
 * 学生完成情况Service业务层处理
 *
 * @author LSD
 * @date 2025-06-19
 */
@Service
public class DiaReportStudentCompletionServiceImpl extends ServiceImpl<DiaReportStudentCompletionMapper, DiaReportStudentCompletion> implements IDiaReportStudentCompletionService {
    @Autowired
    private DiaReportStudentCompletionMapper diaReportStudentCompletionMapper;

    @Autowired
    private DiaReportStandardsMapper diaReportStandardsMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;


    @Override
    public AjaxResult stuEdit(List<DiaReportStudentCompletion> param){
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            List<DiaReportStudentCompletion> needInsert = new ArrayList<>();

            for(DiaReportStudentCompletion completion : param){
                QueryWrapper<DiaReportStudentCompletion> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("relId",completion.getRelId());
                queryWrapper.eq("itemId",completion.getItemId());
                queryWrapper.eq("stu_no",getUsername());
                DiaReportStudentCompletion oldCompletion = diaReportStudentCompletionMapper.selectOne(queryWrapper);
                if(oldCompletion != null){
                    UpdateWrapper<DiaReportStudentCompletion> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("completionId", oldCompletion.getCompletionId())
                            .set("completed", completion.getCompleted())
                            .set("reason", completion.getReason())
                            .set("improvement_measures", completion.getImprovementMeasures())
                            .set("update_time", getNowDate())
                            .set("update_by", getUsername());
                    int res = diaReportStudentCompletionMapper.update(null, updateWrapper);
                    if(res == 0){
                        throw new Exception("更新失败");
                    }
                }else{
                    completion.setStuNo(getUsername());
                    completion.setCreateBy(getUsername());
                    completion.setCreateTime(getNowDate());
                    needInsert.add(completion);
                }
            }

            if(!needInsert.isEmpty()){
                boolean res = this.saveBatch(needInsert);
                if(!res){
                    throw new Exception("保存失败");
                }
            }


            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public List<DiaReportItems> getStuItemByStuNo(String stuNo, Long deptId, Long relId , Long reportId){
        List<DiaReportItems> diaReportItems = diaReportStandardsMapper.getItemByReportId(reportId);
        if (diaReportItems == null || diaReportItems.isEmpty()) {
            return diaReportItems;
        }
        List<Long> itemIds = diaReportItems.stream()
                .map(DiaReportItems::getItemId)
                .collect(Collectors.toList());

        // 1. xgStandard (level 1)
        List<DiaReportStandards> level1List = diaReportStandardsMapper.selectList(
                new QueryWrapper<DiaReportStandards>()
                        .eq("relId", relId)
                        .eq("level", 1)
                        .in("itemId", itemIds)
        );
        Map<Long, DiaReportStandards> level1Map = level1List.stream()
                .collect(Collectors.toMap(DiaReportStandards::getItemId, Function.identity(), (a, b) -> a));

        // 2. xwStandard (level 2, with deptId)
        List<DiaReportStandards> level2List = diaReportStandardsMapper.selectStandardDeptBatch(
                relId, 2, deptId, itemIds
        );
        Map<Long, DiaReportStandards> level2Map = level2List.stream()
                .collect(Collectors.toMap(DiaReportStandards::getItemId, Function.identity(), (a, b) -> a));

        // 3. stuStandard (level 3, with stuNo)
        List<DiaReportStandards> level3List = diaReportStandardsMapper.selectList(
                new QueryWrapper<DiaReportStandards>()
                        .eq("relId", relId)
                        .eq("level", 3)
                        .eq("user_name", stuNo)
                        .in("itemId", itemIds)
        );
        Map<Long, DiaReportStandards> level3Map = level3List.stream()
                .collect(Collectors.toMap(DiaReportStandards::getItemId, Function.identity(), (a, b) -> a));

        // 4. 完成情况
        List<DiaReportStudentCompletion> completionList = diaReportStudentCompletionMapper.selectList(
                new QueryWrapper<DiaReportStudentCompletion>()
                        .eq("relId", relId)
                        .eq("stu_no", stuNo)
                        .in("itemId", itemIds)
        );
        Map<Long, DiaReportStudentCompletion> completionMap = completionList.stream()
                .collect(Collectors.toMap(DiaReportStudentCompletion::getItemId, Function.identity(), (a, b) -> a));

        // 组装
        for (DiaReportItems item : diaReportItems) {
            Long itemId = item.getItemId();
            if (level1Map.containsKey(itemId)) {
                item.xgStandard = level1Map.get(itemId).getStandardValue();
            }
            if (level2Map.containsKey(itemId)) {
                item.xwStandard = level2Map.get(itemId).getStandardValue();
            }
            if (level3Map.containsKey(itemId)) {
                item.stuStandard = level3Map.get(itemId).getStandardValue();
            }
            DiaReportStudentCompletion completion = completionMap.get(itemId);
            if (completion != null) {
                item.completed = completion.getCompleted() == null ? 0 : completion.getCompleted();
                item.reason = completion.getReason();
                item.improvementMeasures = completion.getImprovementMeasures();
            }
        }
        return diaReportItems;
    }



    @Override
    public List<DiaReportItems> getStuItemByReportId(Long deptId, Long relId , Long reportId){
        List<DiaReportItems> diaReportItems = diaReportStandardsMapper.getItemByReportId(reportId);
        diaReportItems.forEach(item->{

            QueryWrapper<DiaReportStandards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("relId",relId);
            queryWrapper.eq("itemId",item.getItemId());
            queryWrapper.eq("level","1");
            DiaReportStandards diaReportStandards = diaReportStandardsMapper.selectOne(queryWrapper);
            if(diaReportStandards!= null){
                item.xgStandard = diaReportStandards.getStandardValue();
            }

            DiaReportStandards searchQuery = new DiaReportStandards();
            searchQuery.setRelId(relId);
            searchQuery.setItemId(item.getItemId());
            searchQuery.setLevel(2);
            searchQuery.deptId = deptId;
            DiaReportStandards diaReportStandards1 = diaReportStandardsMapper.selectStandardDept(searchQuery);
            if(diaReportStandards1!= null){
                item.xwStandard = diaReportStandards1.getStandardValue();
            }

            QueryWrapper<DiaReportStandards> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("relId",relId);
            queryWrapper1.eq("itemId",item.getItemId());
            queryWrapper1.eq("level","3");
            queryWrapper1.eq("user_name",getUsername());
            DiaReportStandards diaReportStandards2 = diaReportStandardsMapper.selectOne(queryWrapper1);
            if(diaReportStandards2!= null){
                item.stuStandard = diaReportStandards2.getStandardValue();
            }

            QueryWrapper<DiaReportStudentCompletion> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("relId",relId);
            queryWrapper2.eq("itemId",item.getItemId());
            queryWrapper2.eq("stu_no",getUsername());
            DiaReportStudentCompletion diaReportStudentCompletion = diaReportStudentCompletionMapper.selectOne(queryWrapper2);
            if(diaReportStudentCompletion!= null){
                item.completed = diaReportStudentCompletion.getCompleted() == null ? 0 : diaReportStudentCompletion.getCompleted();
                item.reason = diaReportStudentCompletion.getReason();
                item.improvementMeasures = diaReportStudentCompletion.getImprovementMeasures();
            }
        });
        return diaReportItems;
    }

    /**
     * 查询学生完成情况
     *
     * @param completionId 学生完成情况主键
     * @return 学生完成情况
     */
    @Override
    public DiaReportStudentCompletion selectDiaReportStudentCompletionByCompletionId(Long completionId) {
        return diaReportStudentCompletionMapper.selectDiaReportStudentCompletionByCompletionId(completionId);
    }

    /**
     * 查询学生完成情况列表
     *
     * @param diaReportStudentCompletion 学生完成情况
     * @return 学生完成情况
     */
    @Override
    public List<DiaReportStudentCompletion> selectDiaReportStudentCompletionList(DiaReportStudentCompletion diaReportStudentCompletion) {
        return diaReportStudentCompletionMapper.selectDiaReportStudentCompletionList(diaReportStudentCompletion);
    }

    /**
     * 新增学生完成情况
     *
     * @param diaReportStudentCompletion 学生完成情况
     * @return 结果
     */
    @Override
    public int insertDiaReportStudentCompletion(DiaReportStudentCompletion diaReportStudentCompletion) {
        diaReportStudentCompletion.setCreateTime(getNowDate());
        return diaReportStudentCompletionMapper.insertDiaReportStudentCompletion(diaReportStudentCompletion);
    }

    /**
     * 修改学生完成情况
     *
     * @param diaReportStudentCompletion 学生完成情况
     * @return 结果
     */
    @Override
    public int updateDiaReportStudentCompletion(DiaReportStudentCompletion diaReportStudentCompletion) {
        diaReportStudentCompletion.setUpdateTime(getNowDate());
        return diaReportStudentCompletionMapper.updateDiaReportStudentCompletion(diaReportStudentCompletion);
    }

    /**
     * 批量删除学生完成情况
     *
     * @param completionIds 需要删除的学生完成情况主键
     * @return 结果
     */
    @Override
    public int deleteDiaReportStudentCompletionByCompletionIds(Long[] completionIds) {
        return diaReportStudentCompletionMapper.deleteDiaReportStudentCompletionByCompletionIds(completionIds);
    }

    /**
     * 删除学生完成情况信息
     *
     * @param completionId 学生完成情况主键
     * @return 结果
     */
    @Override
    public int deleteDiaReportStudentCompletionByCompletionId(Long completionId) {
        return diaReportStudentCompletionMapper.deleteDiaReportStudentCompletionByCompletionId(completionId);
    }
}
