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

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.attendance.mapper.EduAttendanceNotArriveMapper;
import com.yida.data.attendance.service.EduAttendanceConfigService;
import com.yida.data.attendance.service.EduAttendanceNotArriveService;
import com.yida.data.common.core.entity.attendance.EduAttendanceConfig;
import com.yida.data.common.core.entity.attendance.EduAttendanceNotArrive;
import com.yida.data.common.core.entity.constant.AppConstant;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.notice.qywx.TextSchoolNotice;
import com.yida.data.common.core.entity.notice.qywx.inside.Text;
import com.yida.data.common.core.entity.system.EduApp;
import com.yida.data.common.core.entity.user.EduParent;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.utils.WxUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.user.feign.RemoteStudentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
@RefreshScope
public class EduAttendanceNotArriveServiceImpl extends ServiceImpl<EduAttendanceNotArriveMapper,
    EduAttendanceNotArrive> implements EduAttendanceNotArriveService {

    private static final String NOTICE_URL = "/attendance/url";
    private final EduAttendanceConfigService eduAttendanceConfigService;
    private final RemoteStudentService remoteStudentService;
    private final RedisService redisService;
    private final CommonService commonService;
    private final WxUtil wxUtil;
    @Value("${febs.pageUrl}")
    private String pageUrl;

    @Override
    public void pushNotArriveMsg() {
        List<EduAttendanceNotArrive> notArriveList = list();
        if (CollUtil.isNotEmpty(notArriveList)) {
            for (EduAttendanceNotArrive notArrive : notArriveList) {
                LocalDateTime now = LocalDateTime.now();
                EduAttendanceConfig config = eduAttendanceConfigService.getConfig(notArrive.getSchoolId());
                // 推送间隔
                Integer interval = notArrive.getType() == 0 ? config.getSchoolPushInterval() :
                    config.getDormitoryPushInterval();
                // 未推送或已超过推送间隔
                if (notArrive.getPushTime() == null || LocalDateTimeUtil.between(notArrive.getPushTime(),
                    now).toMinutes() >= interval) {
                    // 推送包含家长
                    if (notArrive.getPushObj() == 0 || notArrive.getPushObj() == 2) {
                        EduStudent student = (EduStudent) redisService.hget(CachePrefixConstant.STUDENT_DATA,
                            notArrive.getStudentId().toString());
                        if (student == null) {
                            student = remoteStudentService.getStudentNoPermission(notArrive.getStudentId()).getData();
                        }
                        if (student != null && CollUtil.isNotEmpty(student.getParents())) {
                            for (EduParent parent : student.getParents()) {
                                //构建消息
//                                String msg = String.format("【平安校园警告】尊敬的%s%s，截止%s，%s" +
//                                        "并未进入学校，请您尽快确认学生位置，确保学生的人身安全。<a href=\"%s\">请点击此处确认消息</a>",
                                String msg = String.format("【平安校园警告】尊敬的%s%s，截止%s，%s" +
                                                "并未进入学校，请您尽快确认学生位置，确保学生的人身安全。",
                                    notArrive.getStudentName(), parent.getParentType(),
                                    LocalDateTimeUtil.format(now, "yyyy年MM月dd日HH时mm分ss秒"),
                                    notArrive.getStudentName());
                                // 发送通知消息
                                EduApp app = commonService.getAppByCodeAndSchool(AppConstant.ATTENDANCE_PARENT, null,
                                    notArrive.getSchoolId());
                                TextSchoolNotice notice = new TextSchoolNotice();
                                notice.setTo_parent_userid(Collections.singletonList(parent.getWxId()));
                                notice.setText(new Text(msg));
                                wxUtil.pushSchoolNotice(wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret()),
                                    notice);
                                notArrive.setPushTime(now);
                            }
                        }
                    }
                }
            }

            // 更新推送
            updateBatchById(notArriveList);
        }
    }


}
