package com.yida.data.user.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.entity.user.EduUserDept;
import com.yida.data.common.core.entity.user.EduUserFace;
import com.yida.data.common.core.utils.DaHuaUtil;
import com.yida.data.system.feign.RemoteDeptService;
import com.yida.data.user.mapper.EduStudentMapper;
import com.yida.data.user.service.DaHuaSyncService;
import com.yida.data.user.service.EduUserDeptService;
import com.yida.data.user.service.EduUserFaceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 企业微信同步service
 *
 * @author ZYJ
 * @date 2022/9/16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DaHuaSyncServiceImpl implements DaHuaSyncService {

    private final EduUserDeptService eduUserDeptService;
    private final EduUserFaceService eduUserFaceService;

    private final EduStudentMapper eduStudentMapper;

    private final RemoteDeptService remoteDeptService;

    private final RedisService redisService;

    public static final String DA_HUA_USER_REDIS_KEY = "dahua:user:map:";

    @Override
    public void syncSchoolDaHuaStudent(Long schoolId) {
        log.info("大华=============开始同步学生数据");
        Dept school = remoteDeptService.getInfoByIdNoPermission(schoolId).getData();
        if (Objects.nonNull(school)) {
            // 查询学生列表数据
            List<EduStudent> studentList = eduStudentMapper.selectList(Wrappers.lambdaQuery(new EduStudent())
                    .eq(EduStudent::getSchoolId, school.getDeptId()));
            if (CollUtil.isNotEmpty(studentList)) {
                log.info("[{}], schoolId:[{}]开始同步学生数据=>[{}]", school.getDeptName(), school.getDeptId(), studentList.size());
                for (EduStudent eduStudent : studentList) {
                    try {
                        log.info("同步的学生数据: {}", eduStudent);
                        Object o = redisService.hget(DA_HUA_USER_REDIS_KEY, String.valueOf(eduStudent.getId()));
                        if (Objects.nonNull(o)) {
                            continue;
                        }
                        // 人脸信息
                        EduUserFace userFace = eduUserFaceService.getOne(Wrappers.lambdaQuery(new EduUserFace())
                                .eq(EduUserFace::getUserId, eduStudent.getId())
                                .eq(EduUserFace::getUserType, 0));
                        // 班级
                        EduUserDept clazz = eduUserDeptService.getById(eduStudent.getClassId());
                        // 年级
                        EduUserDept grade = eduUserDeptService.getById(eduStudent.getGradeId());

                        // 排除错误部门数据
                        EduUserDept section = null;
                        EduUserDept campus = null;
                        if (grade.getParentId() != -school.getDeptId()) {
                            section = eduUserDeptService.getById(grade.getParentId());
                            campus = eduUserDeptService.getById(section.getParentId());
                        }
                        if (Objects.nonNull(section)) {
                            if (Objects.nonNull(eduStudent.getDahuaId())) {
                                DaHuaUtil.updateUser(eduStudent.getDahuaId(), eduStudent.getStuName(),
                                        eduStudent.getDahuaCode(), 0, 1,
                                        school.getDahuaId(), campus.getDaHuaId(), section.getDaHuaId(),
                                        grade.getDaHuaId(), clazz.getDaHuaId(),
                                        Objects.nonNull(userFace) ? userFace.getPicPath() : ""
                                );
                            } else {
                                String cardNum = DaHuaUtil.generateCardNum();
                                eduStudent.setDahuaCode(eduStudent.getStuNumber().length() > 20
                                        ? DaHuaUtil.generateCode()
                                        : eduStudent.getStuNumber());
                                eduStudent.setDahuaId(
                                        DaHuaUtil.addUser(eduStudent.getStuName(), eduStudent.getDahuaCode(),
                                                0, 1, cardNum,
                                                school.getDahuaId(), campus.getDaHuaId(), section.getDaHuaId(),
                                                grade.getDaHuaId(), clazz.getDaHuaId(),
                                                Objects.nonNull(userFace) ? userFace.getPicPath() : ""
                                        )
                                );
                            }
                            eduStudentMapper.updateById(eduStudent);
                            redisService.hset(DA_HUA_USER_REDIS_KEY, String.valueOf(eduStudent.getId()), 1);
                        }
                    } catch (Exception e) {
                        log.error("大华同步学生数据失败, 学生信息: {}", eduStudent, e);
                        break;
                    }
                }
            }
        }
        log.info("大华=============同步学生数据结束");
    }

    @Override
    public void syncSchoolDaHuaDept(Long schoolId) {
        log.info("大华=============开始同步家校部门数据");
        try {
            Dept school = remoteDeptService.getInfoByIdNoPermission(schoolId).getData();
            if (Objects.nonNull(school)) {
                // 查询校区数据
                List<EduUserDept> campusList = eduUserDeptService.findChildByParent(-school.getDeptId());
                saveDaHuaDept(school.getDahuaId(), campusList);
            }
        } catch (Exception e) {
            log.error("大华=============同步家校部门数据失败", e);
        }
        log.info("大华=============同步家校部门数据结束");
    }

    /**
     * 保存大华部门数据
     *
     * @param parentDaHuaId 父级大华id
     * @param userDeptList  家校部门集合
     * @author ZYJ
     * @date 2022/10/13 17:19
     */
    private void saveDaHuaDept(String parentDaHuaId, List<EduUserDept> userDeptList) {

        if (CollUtil.isNotEmpty(userDeptList)) {
            for (EduUserDept userDept : userDeptList) {
                log.info("处理的家校部门数据: {}", userDept);
                // 处理校区数据
                if (StringUtils.isNotBlank(userDept.getDaHuaId())) {
                    // 修改
                    DaHuaUtil.updateDept(userDept.getDaHuaId(), parentDaHuaId, userDept.getDeptName());
                } else {
                    // 新增
                    userDept.setDaHuaId(DaHuaUtil.addDept(parentDaHuaId, userDept.getDeptName()).getStr("id"));
                    eduUserDeptService.saveOrUpdate(userDept);
                }
                // 查询子级部门
                List<EduUserDept> childDeptList = eduUserDeptService.findChildByParent(userDept.getDeptId());
                saveDaHuaDept(userDept.getDaHuaId(), childDeptList);
            }
        }
    }
}
