package cn.teammodel.test;

import cn.teammodel.common.PK;
import cn.teammodel.model.dto.admin.teacher.IdCodePair;
import cn.teammodel.model.entity.teacher.PtTeacherInfo;
import cn.teammodel.model.vo.admin.GpTeacherVo;
import cn.teammodel.repository.PtTeacherRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class AsyncTeacherService {
    private static final Logger log = LoggerFactory.getLogger(AsyncTeacherService.class);

    @Autowired
    private PtTeacherRepository ptTeacherRepository;

    @Transactional(rollbackFor = Exception.class)
    public void asyncSavePtTeacherInfos(List<GpTeacherVo> teachersList) {
        try {
            if (teachersList.isEmpty()) {
                return; // 处理空输入，避免后续NPE
            }
            String schoolCode = teachersList.get(0).getCode();

            // 加载现有教师数据（假设已按学校码过滤）
            Map<String, PtTeacherInfo> existingTeachers = loadExistingTeachers(teachersList);
//
//            // 收集传入教师ID集合
//            Set<String> incomingIds = teachersList.stream()
//                    .map(GpTeacherVo::getId)
//                    .filter(Objects::nonNull)
//                    .collect(Collectors.toSet());
//
//            // 直接使用existingTeachers获取待停用教师
//            List<PtTeacherInfo> toDeactivate = existingTeachers.values().stream()
//                    .filter(pt -> !incomingIds.contains(pt.getId()) && pt.getId() != null)
//                    .filter(pt -> !"pt".equals(pt.getSource())) // 提前过滤无需处理的记录
//                    .peek(pt -> {
//                        pt.setState(2);
//                        pt.setVersion(pt.getVersion() + 1);
//                    })
//                    .collect(Collectors.toList());
//
//            // 批量停用
//            if (!toDeactivate.isEmpty()) {
//                ptTeacherRepository.saveAll(toDeactivate);
//                // toDeactivate.forEach(pt -> PT_TEACHER_CACHE.put(pt.getCode(), pt));
//            }

            // 处理更新（合并过滤与转换操作）
            List<PtTeacherInfo> updates = teachersList.stream()
                    .filter(t -> t.getId() != null)
                    .map(t -> convertToPtTeacherInfo(t, existingTeachers))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            if (!updates.isEmpty()) {
                ptTeacherRepository.saveAll(updates);
                // updates.forEach(pt -> PT_TEACHER_CACHE.put(pt.getCode(), pt));
            }
        } catch (Exception e) {
            log.error("Async save teacher info failed", e);
        }
    }

    private Map<String, PtTeacherInfo> loadExistingTeachers(List<GpTeacherVo> teachersList) {
        List<IdCodePair> idAndCode = teachersList.stream()
                .filter(t -> t.getId() != null)
                .map(t -> new IdCodePair(t.getId(),  "PtTeacher-" + t.getCode()))
                .collect(Collectors.toList());

        List<PtTeacherInfo> existingList = ptTeacherRepository.findByIdCodePairs(idAndCode);

        return existingList.stream()
                .collect(Collectors.toMap(
                        PtTeacherInfo::getId,
                        Function.identity()
                ));
    }

    private PtTeacherInfo convertToPtTeacherInfo(GpTeacherVo teacher, Map<String, PtTeacherInfo> existingTeachers) {

        String code = "PtTeacher-" + teacher.getCode();
        PtTeacherInfo existing = existingTeachers.get(teacher.getId());
        // 如果数据库无记录，直接创建新对象
        if (existing == null) {
            return createNewPtTeacherInfo(teacher, code);
        }
        // 检查字段是否有变化
//        boolean isChanged = !Objects.equals(existing.getName(), teacher.getName())
//                || !Objects.equals(existing.getPicture(), teacher.getPicture()) ||
//                !Objects.equals(existing.getEmail(), teacher.getEmail()) ||
//                !Objects.equals(existing.getPhone(), teacher.getPhone()) ||
//                !Objects.equals(existing.getSubjectIds(), teacher.getSubjectIds()) ||
//                !Objects.equals(existing.getRoles(), teacher.getRoles()) ||
//                !Objects.equals(existing.getStatus(), teacher.getStatus()) ||
//                !Objects.equals(existing.getJob(), teacher.getJob()) ||
//                !Objects.equals(existing.getPeriodId(), teacher.getPeriodId())
//                ;
        boolean isChanged = false;

        // 无变化则返回null，表示无需更新
        if (!isChanged) {

            return null;
        }

        PtTeacherInfo updated = new PtTeacherInfo();
        BeanUtils.copyProperties(existing, updated);
        updated.setName(teacher.getName());
        updated.setPhone(teacher.getPhone());
        updated.setPicture(teacher.getPicture());
        updated.setEmail(teacher.getEmail());
        updated.setPeriodId(teacher.getPeriodId());
        updated.setSubjectIds(teacher.getSubjectIds());
        updated.setRoles(teacher.getRoles());
        updated.setStatus(teacher.getStatus());
        updated.setJob(teacher.getJob());
        updated.setVersion(getNextVersion(updated.getId(), updated.getCode()));
        return updated;

    }

    private Integer getNextVersion(String id,String code) {
        PtTeacherInfo existingPtTeacherInfo = ptTeacherRepository.findByIdAndCode(id,code);
        if (existingPtTeacherInfo != null) {
            return existingPtTeacherInfo.getVersion() + 1;
        }
        return 1;
    }

    private PtTeacherInfo createNewPtTeacherInfo(GpTeacherVo teacher, String code) {
        PtTeacherInfo ptTeacherInfo = new PtTeacherInfo();

        // 固定值
        ptTeacherInfo.setPk("PtTeacher");
        ptTeacherInfo.setTtl(-1);

        // 基础信息映射
        ptTeacherInfo.setId(teacher.getId());
        ptTeacherInfo.setCode(code);
        ptTeacherInfo.setName(teacher.getName());
        ptTeacherInfo.setPhone(teacher.getPhone() != null ? teacher.getPhone() : ""); // 空值处理
        ptTeacherInfo.setEmail(teacher.getEmail() != null ? teacher.getEmail() : "");
        ptTeacherInfo.setPicture(teacher.getPicture());
        ptTeacherInfo.setJob(teacher.getJob());
        ptTeacherInfo.setSchool(teacher.getCode());
        ptTeacherInfo.setJoinTime(0L);
        ptTeacherInfo.setState(1);
        ptTeacherInfo.setVersion(1);
        ptTeacherInfo.setAge(teacher.getAge() != null ? teacher.getAge() : 0);
        ptTeacherInfo.setTeachingAge(teacher.getTeachingAge() != null ? teacher.getTeachingAge() : 0);
        ptTeacherInfo.setStatus(teacher.getStatus() != null ? teacher.getStatus() : "");


        // 学科与角色信息
        ptTeacherInfo.setSubjectIds(teacher.getSubjectIds() != null ? teacher.getSubjectIds() : Collections.emptyList());
        ptTeacherInfo.setSubjectNames(teacher.getSubjectNames() != null ? teacher.getSubjectNames() : Collections.emptyList());
        ptTeacherInfo.setRoles(teacher.getRoles() != null ? teacher.getRoles() : Collections.emptyList());
        //只是针对管理员权限的内容
        if (teacher.getRoles() != null && teacher.getRoles().contains("admin")) {
            ptTeacherInfo.setIdentity(Collections.singletonList("admin"));
        } else {
            ptTeacherInfo.setIdentity(Collections.singletonList("teacher"));
        }



        // 其他业务字段
        ptTeacherInfo.setDegree(teacher.getDegree() != null ? teacher.getDegree() : "");
        ptTeacherInfo.setGender(teacher.getGender() != null ? teacher.getGender() : "U"); // 未知性别默认值
        ptTeacherInfo.setGrade(teacher.getGrade() != null ? teacher.getGrade() : Collections.emptyList());
        ptTeacherInfo.setGradeName(teacher.getGradeName() != null ? teacher.getGradeName() : Collections.emptyList());
        ptTeacherInfo.setPeriodId(teacher.getPeriodId() != null ? teacher.getPeriodId() : "");
        ptTeacherInfo.setTitle(teacher.getTitle() != null ? teacher.getTitle() : "");
        ptTeacherInfo.setSource("ies");

        // 版本号初始化
        ptTeacherInfo.setVersion(1);

        return ptTeacherInfo;
    }
}
