package jnpf.attendance.service.handle.notice;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import jnpf.attendance.antifreeze.UserAntifreeze;
import jnpf.attendance.mapper.AttendanceManagerPermissionMapper;
import jnpf.attendance.service.AttendanceGroupService;
import jnpf.constants.AttendanceConstant;
import jnpf.entity.AttendanceGroup;
import jnpf.enums.attendance.AttendanceNoticeEnum;
import jnpf.enums.attendance.NoticeModuleEnum;
import jnpf.enums.attendance.UserSettingEnum;
import jnpf.model.attendance.model.JumpUrl;
import jnpf.model.attendance.model.SystemNoticeStrategy;
import jnpf.model.attendance.model.UserChangModel;
import jnpf.model.attendance.model.UserChangeNoticeModel;
import jnpf.model.attendance.vo.AttendanceGroupAdminVo;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.util.DateUtil;
import jnpf.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static jnpf.constants.AttendanceConstant.*;
import static jnpf.enums.attendance.AttendanceNoticeEnum.*;
import static jnpf.enums.attendance.UserSettingEnum.*;

/**
 * 考勤组人员变动通知
 */
@Component(AttendanceConstant.JOIN_GROUP)
public class UserChangAttendanceNotice implements AttendanceNotice<UserChangModel, UserChangeNoticeModel> {
    @Autowired
    private UserAntifreeze userAntifreeze;

    @Resource
    private AttendanceNoticeHandler attendanceNoticeHandler;
    @Resource
    private AttendanceManagerPermissionMapper attendanceManagerPermissionMapper;
    @Autowired
    private AttendanceGroupService attendanceGroupService;

    @Override
    public Boolean isPass(UserChangeNoticeModel attendanceNoticeModel) {
        return Boolean.TRUE;
    }

    @Override
    public List<UserChangModel> generatingData(UserChangeNoticeModel attendanceNoticeModel) {
        List<UserChangModel> shiftChangModels = CollUtil.newArrayList();

        String tips = "";
        AttendanceGroup byId = null;
        List<String> realNames = null;
        if (Objects.equals(AttendanceNoticeEnum.REMOVE_USER_REMOVE_GROUP, attendanceNoticeModel.getAttendanceNoticeEnum())
                || Objects.equals(AttendanceNoticeEnum.REMOVE_USER, attendanceNoticeModel.getAttendanceNoticeEnum())) {
            tips = "请尽快联系管理员加入考勤组，以确保可以使用考勤打卡";
        } else {
            //获取管理员
            List<AttendanceGroupAdminVo> attendanceGroupAdminVos = attendanceManagerPermissionMapper.queryGroupUser(attendanceNoticeModel.getJoinGroupId());
            List<String> adminUserIds = attendanceGroupAdminVos.stream().map(AttendanceGroupAdminVo::getUserId).collect(Collectors.toList());
            byId = attendanceGroupService.getById(attendanceNoticeModel.getJoinGroupId());
            Assert.isFalse(Objects.isNull(byId), "变更考勤组通知，未查询到考勤组信息[{}]", attendanceNoticeModel.getJoinGroupId());
            List<PartUserInfoVo> allByIds = CollUtil.isEmpty(adminUserIds) ? CollUtil.newArrayList() : userAntifreeze.getAllByIds(adminUserIds, attendanceNoticeModel.getTenantId());
            realNames = allByIds.stream().map(PartUserInfoVo::getRealName).collect(Collectors.toList());
        }

        shiftChangModels.add(UserChangModel.builder()
                .type(attendanceNoticeModel.getAttendanceNoticeEnum().getCode())
                .administratorList(CollUtil.isEmpty(realNames) ? "" : StringUtil.join(realNames, "、"))
                .joinGroup(Objects.isNull(byId) ? "" : byId.getGroupName())
                .start(Objects.isNull(attendanceNoticeModel.getStart()) ? "" : DateUtil.dateToString(attendanceNoticeModel.getStart(), "yyyy年MM月dd日 HH:mm"))
                .reason(getReason(attendanceNoticeModel.getAttendanceNoticeEnum(), Objects.isNull(byId) ? "" : byId.getGroupName()))
                .tips(tips)
                .build());
        return shiftChangModels;
    }

    /**
     * @param attendanceNoticeEnum
     * @param groupName
     * @return
     */
    private String getReason(AttendanceNoticeEnum attendanceNoticeEnum, String groupName) {
        if (Objects.equals(attendanceNoticeEnum, AttendanceNoticeEnum.JOIN_GROUP)) {
            return "";
        }
        if (Objects.equals(attendanceNoticeEnum, AttendanceNoticeEnum.GROUP_CHANGE_REMOVE_JOIN_GROUP)) {
            return "原考勤组已解散，已加入新考勤组！";
        }
        if (Objects.equals(attendanceNoticeEnum, AttendanceNoticeEnum.REMOVE_USER_REMOVE_GROUP)) {
            return "原考勤组已解散";
        }
        if (Objects.equals(attendanceNoticeEnum, AttendanceNoticeEnum.REMOVE_USER)) {
            return "已从考勤组中移除";
        }
        if (Objects.equals(attendanceNoticeEnum, AttendanceNoticeEnum.GROUP_CHANGE_PROMOTION)) {
            return String.format("晋升已产生，已加入【%s】", groupName);
        }
        if (Objects.equals(attendanceNoticeEnum, AttendanceNoticeEnum.GROUP_CHANGE_TRANSFER_POSITION)) {
            return String.format("调岗已产生，已加入【%s】", groupName);
        }
        if (Objects.equals(attendanceNoticeEnum, AttendanceNoticeEnum.GROUP_CHANGE_SECONDMENT)) {
            return String.format("借调申请已通过，借调至【%s】", groupName);
        }
        return "";
    }

    @Override
    public List<String> getRecipient(UserChangeNoticeModel attendanceNoticeModel) {
        UserSettingEnum userSettingEnum = AttendanceNoticeEnum.JOIN_GROUP.equals(attendanceNoticeModel.getAttendanceNoticeEnum()) || REMOVE_USER.equals(attendanceNoticeModel.getAttendanceNoticeEnum()) || AttendanceNoticeEnum.REMOVE_USER_REMOVE_GROUP.equals(attendanceNoticeModel.getAttendanceNoticeEnum()) ? ATTENDANCE_SETTING_ATTENDANCE_GROUP_JOIN_LEAVE_REMINDER : ATTENDANCE_SETTING_ATTENDANCE_GROUP_CHANGE_REMINDER;
        return attendanceNoticeHandler.getUserIdsForFilterStatus(attendanceNoticeModel.getUserIds(), UserSettingEnum.ATTENDANCE_SETTING_MESSAGE_RECEIVE, userSettingEnum);
    }

    @Override
    public SystemNoticeStrategy setSystemNoticeStrategy(UserChangeNoticeModel attendanceNoticeModel, String noticeId) {
        ArrayList<JumpUrl> objects = CollUtil.newArrayList();
        String title = ATTENDANCE_NOTICE_GROUP_CHANGE_TITLE;
        if (AttendanceNoticeEnum.JOIN_GROUP.equals(attendanceNoticeModel.getAttendanceNoticeEnum())) {
            title = ATTENDANCE_NOTICE_JOIN_GROUP_CHANGE_TITLE;
            objects.add(JumpUrl.builder().url(ATTENDANCE_NOTICE_RULE_URL).urlName(ATTENDANCE_NOTICE_DETAIL_BUTTON_NAME).color(COLOR_BLACK).build());
            objects.add(JumpUrl.builder().url(ATTENDANCE_NOTICE_CLICK_URL).urlName(ATTENDANCE_NOTICE_TO_CLICK).color(COLOR_BLUE).build());
        } else if (REMOVE_USER.equals(attendanceNoticeModel.getAttendanceNoticeEnum())) {
            title = ATTENDANCE_NOTICE_REMOVE_USER_TITLE;
            objects.add(JumpUrl.builder().url(String.format(ATTENDANCE_NOTICE_GROUP_CHANGES_URL, noticeId)).urlName(ATTENDANCE_NOTICE_DETAIL_BUTTON_NAME).color(COLOR_BLACK).build());
        } else if (REMOVE_USER_REMOVE_GROUP.equals(attendanceNoticeModel.getAttendanceNoticeEnum())) {
            title = ATTENDANCE_NOTICE_REMOVE_USER_TITLE;
            objects.add(JumpUrl.builder().url(String.format(ATTENDANCE_NOTICE_GROUP_CHANGES_URL, noticeId)).urlName(ATTENDANCE_NOTICE_DETAIL_BUTTON_NAME).color(COLOR_BLACK).build());
        } else {
            objects.add(JumpUrl.builder().url(ATTENDANCE_NOTICE_RULE_URL).urlName(ATTENDANCE_NOTICE_DETAIL_BUTTON_NAME).color(COLOR_BLACK).build());
            objects.add(JumpUrl.builder().url(ATTENDANCE_NOTICE_CLICK_URL).urlName(ATTENDANCE_NOTICE_TO_CLICK).color(COLOR_BLUE).build());
        }
        return SystemNoticeStrategy.builder()
                .title(title)
                .noticeModuleEnum(NoticeModuleEnum.KQZ_BD)
                .jumpUrls(objects)
                .build();
    }

    @Override
    public String getContext(List<UserChangModel> data) {
        if (CollUtil.isEmpty(data)) {
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer();
        UserChangModel shiftChangModel = data.stream().findFirst().orElse(null);
        if (StringUtil.isNotEmpty(shiftChangModel.getReason())) {
            stringBuffer.append("变动原因：").append(shiftChangModel.getReason()).append("</br>");
        }
        if (AttendanceNoticeEnum.JOIN_GROUP.getCode().equals(shiftChangModel.getType())) {
            stringBuffer.append("加入考勤组：").append(shiftChangModel.getJoinGroup()).append("</br>");
            stringBuffer.append("考勤组管理员：").append(StringUtil.isNotEmpty(shiftChangModel.getAdministratorList()) ? shiftChangModel.getAdministratorList() : "暂无管理员").append("</br>");
        }
        if (AttendanceNoticeEnum.GROUP_CHANGE_REMOVE_JOIN_GROUP.getCode().equals(shiftChangModel.getType())) {
            stringBuffer.append("新考勤组：").append(shiftChangModel.getJoinGroup()).append("</br>");
            stringBuffer.append("考勤组管理员：").append(StringUtil.isNotEmpty(shiftChangModel.getAdministratorList()) ? shiftChangModel.getAdministratorList() : "暂无管理员").append("</br>");
        }
        if (AttendanceNoticeEnum.GROUP_CHANGE_SECONDMENT.getCode().equals(shiftChangModel.getType())) {
            stringBuffer.append("开始时间：").append(shiftChangModel.getStart()).append("</br>");
        }
        if (AttendanceNoticeEnum.GROUP_CHANGE_TRANSFER_POSITION.getCode().equals(shiftChangModel.getType())
                || AttendanceNoticeEnum.GROUP_CHANGE_PROMOTION.getCode().equals(shiftChangModel.getType())) {
            stringBuffer.append("考勤组管理员：").append(StringUtil.isNotEmpty(shiftChangModel.getAdministratorList()) ? shiftChangModel.getAdministratorList() : "暂无管理员").append("</br>");
        }
        if (StringUtil.isNotEmpty(shiftChangModel.getTips())) {
            stringBuffer.append(shiftChangModel.getTips());
        }
        return stringBuffer.toString();
    }

}
