package com.yida.data.form.apply.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.entity.applyForm.*;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.enums.SchoolNatureEnum;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.enums.ApprovalRoleTypeEnum;
import com.yida.data.common.core.enums.AuditStatusEnum;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.service.CommonService;
import com.yida.data.customForm.dto.apply.ApplyFormDataInputDTO;
import com.yida.data.customForm.dto.apply.SendStaffNoticeDTO;
import com.yida.data.form.apply.mapper.ApplyFormDataMapper;
import com.yida.data.form.apply.mapper.CoreApplyFormApprovalProcessMapper;
import com.yida.data.form.apply.service.*;
import com.yida.data.user.feign.RemoteStaffService;
import com.yida.data.user.feign.RemoteStudentService;
import com.yida.data.user.feign.RemoteTeacherService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 申请类表单填报数据 Service
 *
 * @author ZYJ
 * @date 2023/11/16
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class ApplyFormDataServiceImpl implements ApplyFormDataService {

    private final SendNoticeService sendNoticeService;
    private final CoreApplyFormFillUserService coreApplyFormFillUserService;
    private final CoreApprovalProcessUserService coreApprovalProcessUserService;
    private final CoreApplyFormFillUserApprovalProcessService coreApplyFormFillUserApprovalProcessService;
    private final CoreApplyFormFillUserApprovalProcessRecordService coreApplyFormFillUserApprovalProcessRecordService;

    private final ApplyFormDataMapper applyFormDataMapper;
    private final CoreApplyFormApprovalProcessMapper coreApplyFormApprovalProcessMapper;

    private final RemoteStaffService remoteStaffService;
    private final RemoteTeacherService remoteTeacherService;
    private final RemoteStudentService remoteStudentService;

    private final RedisService redisService;
    private final CommonService commonService;

    @Override
    public void saveFormData(ApplyFormDataInputDTO dto, CoreApplyForm applyForm) {

        // 查询学生
        EduStudent student = (EduStudent) redisService
                .hget(CachePrefixConstant.STUDENT_DATA, dto.getUserId().toString());
        if (Objects.isNull(student)) {
            student = remoteStudentService.getStudentNoPermission(dto.getUserId()).getData();
            if (student == null) {
                throw new FebsException("学生信息错误，请联系管理员");
            } else {
                redisService.hset(CachePrefixConstant.STUDENT_DATA, dto.getUserId().toString(), student);
            }
        }
        // 查询学校信息
        Dept school = commonService.getDept(applyForm.getSchoolId());
        // 封装消息发送对象
        SendStaffNoticeDTO sendStaffNoticeDTO = new SendStaffNoticeDTO();
        sendStaffNoticeDTO.setSchoolId(applyForm.getSchoolId());
        sendStaffNoticeDTO.setSchoolType(school.getSchoolType());
        sendStaffNoticeDTO.setCreateTime(LocalDateTime.now());
        sendStaffNoticeDTO.setUserName(student.getStuName());
        sendStaffNoticeDTO.setUserDeptName(
                String.join("/", student.getCampusName(), student.getGradeName(), student.getClassName()));
        sendStaffNoticeDTO.setFormId(dto.getFormId());
        sendStaffNoticeDTO.setUserId(student.getId());
        // 查询数据表字段
        List<String> filedList = applyFormDataMapper.findApplyFormFiled(applyForm.getTableName());
        // 填报信息处理
        JSONObject jsonObject = JSONUtil.parseObj(dto.getJsonDataString());
        // 字段集合
        List<String> parameterList = new ArrayList<>();
        Map<String, Object> parameterMap = new HashMap<>();
        // 处理保存sql语句
        String baseSql = "insert into " + applyForm.getTableName() + "(";
        filedList.forEach(filed -> {
            parameterList.add("#{parameterMap." + filed + "}");
            parameterMap.put(filed, jsonObject.get(filed));
        });
        // 处理其余字段
        parameterMap.put("create_date", new Date());
        parameterMap.put("user_id", dto.getUserId());
        parameterMap.put("examine_status", "0");
        // 数据主键id
        parameterMap.put("id", null);
        String finalSql = baseSql + String.join(",", filedList) + ") values (" + String.join(",", parameterList) + ")";
        // 保存数据
        applyFormDataMapper.saveFormData(finalSql, parameterMap);
        // 处涉及多次填报，添加填报数据主键id
        CoreApplyFormFillUser fillUser = CoreApplyFormFillUser.builder()
                .schoolId(student.getSchoolId())
                .applyFormId(applyForm.getId())
                .applyFormDataId((Long) parameterMap.get("id"))
                .userId(dto.getUserId())
                .userName(student.getStuName())
                .build();
        // 保存填报记录数据
        coreApplyFormFillUserService.save(fillUser);

        sendStaffNoticeDTO.setFillUserId(fillUser.getId());
        // 查询表单对应的审核流程
        List<CoreApprovalProcess> approvalProcessList = coreApplyFormApprovalProcessMapper.selectApplyFormApprovalProcess(applyForm.getId());
        for (int i = 0; i < approvalProcessList.size(); i++) {
            CoreApprovalProcess approvalProcess = approvalProcessList.get(i);
            // 保存填报用户对应的流程
            CoreApplyFormFillUserApprovalProcess fillUserApprovalProcess = new CoreApplyFormFillUserApprovalProcess();
            fillUserApprovalProcess.setApplyFormId(applyForm.getId());
            fillUserApprovalProcess.setFillUserId(fillUser.getId());
            fillUserApprovalProcess.setProcessId(approvalProcess.getId());
            fillUserApprovalProcess.setProcessName(approvalProcess.getApprovalProcessName());
            fillUserApprovalProcess.setApprovalType(approvalProcess.getApprovalType());
            fillUserApprovalProcess.setApprovalUserType(approvalProcess.getApprovalUserType());
            fillUserApprovalProcess.setSort(i);
            coreApplyFormFillUserApprovalProcessService.save(fillUserApprovalProcess);
            // 查询审核流程人员信息
            List<CoreApprovalProcessUser> processUserList = coreApprovalProcessUserService.list(Wrappers.lambdaQuery(new CoreApprovalProcessUser())
                    .eq(CoreApprovalProcessUser::getProcessId, approvalProcess.getId()));
            for (CoreApprovalProcessUser processUser : processUserList) {
                // 职工审核
                if (Objects.nonNull(processUser.getStaffId())) {
                    EduStaff staff = remoteStaffService.getStaff(processUser.getStaffId()).getData();
                    // 保存具体人员的审核记录
                    CoreApplyFormFillUserApprovalProcessRecord fillUserApprovalProcessRecord = new CoreApplyFormFillUserApprovalProcessRecord();
                    fillUserApprovalProcessRecord.setSchoolId(applyForm.getSchoolId());
                    fillUserApprovalProcessRecord.setApplyFormId(applyForm.getId());
                    fillUserApprovalProcessRecord.setFillUserId(fillUser.getId());
                    fillUserApprovalProcessRecord.setUserProcessId(fillUserApprovalProcess.getId());
                    fillUserApprovalProcessRecord.setApprovalId(processUser.getStaffId());
                    fillUserApprovalProcessRecord.setApprovalName(staff.getName());
                    fillUserApprovalProcessRecord.setSort(i);
                    coreApplyFormFillUserApprovalProcessRecordService.save(fillUserApprovalProcessRecord);
                    // 发送审核信息
                    if (i == 0) {
                        sendStaffNoticeDTO.setStaffWxId(staff.getWxId());
                        sendStaffNoticeDTO.setStaffName(staff.getName());
                        sendNoticeService.sendStaffNotice(sendStaffNoticeDTO, 1);
                    }
                } else if (Objects.nonNull(processUser.getStaffRoleId())) {
                    // 角色审核
                    // 审核人员信息
                    List<EduStaff> approvalUserList = new ArrayList<>();
                    // 班主任
                    if (ApprovalRoleTypeEnum.CLASS_TEACHER_TYPE.getType().equals(processUser.getStaffRoleId())) {
                        // 查询学生班主任
                        approvalUserList = remoteTeacherService.listTeacherByDeptId(student.getClassId(), "3").getData();
                    } else {
                        // 高校系主任/K12年级主任
                        if (student.getSchoolId() == 10593) {
                            // 技师学院单独处理
                            approvalUserList = remoteTeacherService.listTeacherByDeptId(student.getCampusId(), "1")
                                    .getData();
                        } else {
                            Dept dept = commonService.getDept(student.getSchoolId());
                            // 学校性质
                            if (ObjectUtil.equals(SchoolNatureEnum.UNI_TYPE.getValue(),
                                    dept.getSchoolNature())) {
                                // 高校
                                approvalUserList = remoteTeacherService.listTeacherByDeptId(student.getSectionId(), "5")
                                        .getData();
                            } else {
                                // K12
                                approvalUserList = remoteTeacherService.listTeacherByDeptId(student.getGradeId(), "2")
                                        .getData();
                            }
                        }
                    }
                    if (CollUtil.isNotEmpty(approvalUserList)) {
                        for (EduStaff eduStaff : approvalUserList) {
                            // 保存具体人员的审核记录
                            CoreApplyFormFillUserApprovalProcessRecord fillUserApprovalProcessRecord = new CoreApplyFormFillUserApprovalProcessRecord();
                            fillUserApprovalProcessRecord.setSchoolId(applyForm.getSchoolId());
                            fillUserApprovalProcessRecord.setApplyFormId(applyForm.getId());
                            fillUserApprovalProcessRecord.setFillUserId(fillUser.getId());
                            fillUserApprovalProcessRecord.setUserProcessId(fillUserApprovalProcess.getId());
                            fillUserApprovalProcessRecord.setApprovalId(eduStaff.getId());
                            fillUserApprovalProcessRecord.setApprovalName(eduStaff.getName());
                            fillUserApprovalProcessRecord.setSort(i);
                            coreApplyFormFillUserApprovalProcessRecordService.save(fillUserApprovalProcessRecord);

                            // 发送审核信息
                            if (i == 0) {
                                sendStaffNoticeDTO.setStaffWxId(eduStaff.getWxId());
                                sendStaffNoticeDTO.setStaffName(eduStaff.getName());
                                sendNoticeService.sendStaffNotice(sendStaffNoticeDTO, 1);
                            }
                        }
                    }
                }
            }
        }
    }
}
