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 cn.hutool.core.util.ObjectUtil;
import com.yida.data.attendance.service.EduAttendanceConfigService;
import com.yida.data.attendance.service.NoticeService;
import com.yida.data.common.core.entity.apply.EduStudentApply;
import com.yida.data.common.core.entity.attendance.EduAttendanceConfig;
import com.yida.data.common.core.entity.attendance.EduAttendanceRecord;
import com.yida.data.common.core.entity.constant.AppConstant;
import com.yida.data.common.core.entity.constant.ApplyConstant;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.notice.app.AppNotice;
import com.yida.data.common.core.entity.notice.app.inside.PushMessage;
import com.yida.data.common.core.entity.notice.qywx.NewsSchoolNotice;
import com.yida.data.common.core.entity.notice.qywx.inside.Article;
import com.yida.data.common.core.entity.notice.qywx.inside.News;
import com.yida.data.common.core.entity.school.EduYidaAppAccount;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.EduApp;
import com.yida.data.common.core.entity.system.EduYidaApp;
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.AppUtil;
import com.yida.data.common.core.utils.WxUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.attendance.vo.AttendanceResVO;
import com.yida.data.school.feign.leave.RemoteLeaveRequestService;
import com.yida.data.school.feign.transaction.RemoteStudentApplyService;
import com.yida.data.user.feign.RemoteStudentService;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
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;

@Service
@Slf4j
@RefreshScope
public class NoticeServiceImpl implements NoticeService {

    @Resource
    private RemoteStudentService remoteStudentService;
    @Resource
    private CommonService commonService;
    @Resource
    private WxUtil wxUtil;
    @Value("${febs.pageUrl}")
    private String pageUrl;
    @Resource
    private RedisService redisService;
    @Resource
    private EduAttendanceConfigService eduAttendanceConfigService;

    @Resource
    private RemoteStudentApplyService remoteStudentApplyService;

    private static final String STUDENT_RECORD_DETAIL_URL = "/attendance/parents/home";
    private static final String PARENT_COLLECT_FAIL_URL = "/collection/parent/index.html";


    @Override
    public void sendAttendanceNotice(AttendanceResVO result) {
        // 时间差异常  不进行推送
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime deviceTime = result.getRecord().getCreateTime();
//        if (now.isBefore(deviceTime)) {
//            return;
//        }
        Duration duration = LocalDateTimeUtil.between(deviceTime, now);
        // 时间差大于30分钟 不推送
        if (duration.toMinutes() > 30L) {
            log.info("时间差过大，不推送通行消息,当前时间:[{}],设备时间:[{}],recordId:[{}]", now, deviceTime, result.getRecord().getId());
            return;
        }

        //判断学生是否购买服务
        EduAttendanceConfig config =
            (EduAttendanceConfig) redisService.hget(CachePrefixConstant.ATTENDANCE_CONFIG,
                result.getRecord().getSchoolId().toString());
        if (config == null) {
            config = eduAttendanceConfigService.getConfig(result.getRecord().getSchoolId());
            redisService.hset(CachePrefixConstant.ATTENDANCE_CONFIG, result.getRecord().getSchoolId().toString(), config);
        }

        if (ObjectUtil.equal("1", config.getPushState())) { //启用缴费才推送进出记录
            //查询学生是否缴费
            if (!remoteStudentApplyService.hasApply(result.getStudent().getId(), ApplyConstant.ATTENDANCE).getData()) {
                return;
            }
        }

        EduStudent student = result.getStudent();
        //查询学校信息
        Dept school = commonService.getDept(student.getSchoolId());
        List<EduParent> parentList = student.getParents();
        if (CollUtil.isNotEmpty(parentList)) {
            EduAttendanceRecord record = result.getRecord();
            if (CollUtil.isNotEmpty(parentList)) {
                // 推微信消息
                if (school.getSchoolType().contains(Dept.TYPE_QYWX)) {
                    // 从redis获取应用数据
                    EduApp app = commonService.getAppByCodeAndSchool(AppConstant.ATTENDANCE_PARENT, null,
                        student.getSchoolId());
                    String token = wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret());
                    StringBuilder detailUrl = new StringBuilder();
                    Map<String, String> params = new HashMap<>();
                    params.put("corpId", app.getWxCorpId());
                    params.put("type", "1");
                    params.put("id", student.getId().toString());
                    params.put("aid", record.getId().toString());
                    params.put("date", LocalDateTimeUtil.format(record.getCreateTime(), "yyyy-MM-dd"));
                    detailUrl.append(pageUrl).append(STUDENT_RECORD_DETAIL_URL)
                        .append("?appId=").append(app.getWxCorpId())
                        .append("&type=1")
                        .append("&loginType=0")
                        .append("&id=").append(student.getId().toString())
                        .append("&aid=").append(record.getId().toString())
                        .append("&date=").append(LocalDateTimeUtil.format(record.getCreateTime(), "yyyy" +
                        "-MM-dd"));

                    NewsSchoolNotice newsSchoolNotice = new NewsSchoolNotice();
                    newsSchoolNotice.setAgentid(app.getWxAgentId());
                    Article article = new Article();
                    article.setPicurl(record.getPicUrl());
                    article.setUrl(detailUrl.toString());
                    article.setTitle("平安校园通知");
                    newsSchoolNotice.setNews(new News(Collections.singletonList(article)));
                    for (EduParent parent : parentList) {
                        String wxId = parent.getWxId();
                        article.setDescription(String.format("尊敬的%s%s，%s在%s时间通过%s通道%s%s。【%s】",
                            student.getStuName(),
                            parent.getParentType(),
                            student.getStuName(),
                            LocalDateTimeUtil.format(record.getCreateTime(), "yyyy-MM-dd HH:mm:ss"),
                            record.getDeviceName(),
                            "0".equals(record.getScope().toString()) ? "进入" : "离开",
                            "0".equals(record.getZone().toString()) ? "学校" : "宿舍",
                            student.getSchoolName()
                        ));
                        newsSchoolNotice.setTo_parent_userid(Collections.singletonList(wxId));
                        wxUtil.pushSchoolNotice(token, newsSchoolNotice);
                    }
                    log.info("push msg:{}", newsSchoolNotice);
                }
                // 推app消息
                if (school.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
                    // 从redis获取应用数据
                    EduYidaApp yidaApp = commonService.getYidaApp(student.getSchoolId());
                    EduYidaAppAccount account = commonService.getYidaAppAccount(student.getSchoolId(), 0);
                    StringBuilder detailUrl = new StringBuilder();
                    detailUrl.append(pageUrl).append(STUDENT_RECORD_DETAIL_URL)
                        .append("?appId=").append(school.getDeptId())
                        .append("&type=1")
                        .append("&loginType=2")
                        .append("&id=").append(student.getId().toString())
                        .append("&aid=").append(record.getId().toString())
                        .append("&date=").append(LocalDateTimeUtil.format(record.getCreateTime(), "yyyy" +
                        "-MM-dd"));
                    AppNotice appNotice = new AppNotice();
                    PushMessage msg = new PushMessage();
                    msg.setTitle("平安校园通知");
                    msg.setHtmlUrl(detailUrl.toString());
                    msg.setImgUrl(record.getPicUrl());
                    msg.setAccountId(account.getYidaAppAccountId());
                    msg.setMsgType(PushMessage.ARTICLE);
                    msg.setServiceId(account.getYidaAppAccountId());
                    appNotice.setMsgList(Collections.singletonList(msg));
                    for (EduParent parent : parentList) {
                        msg.setContent(String.format("尊敬的%s%s，%s在%s时间通过%s通道%s%s。【%s】",
                            student.getStuName(),
                            parent.getParentType(),
                            student.getStuName(),
                            LocalDateTimeUtil.format(record.getCreateTime(), "yyyy-MM-dd HH:mm:ss"),
                            record.getDeviceName(),
                            "0".equals(record.getScope().toString()) ? "进入" : "离开",
                            "0".equals(record.getZone().toString()) ? "学校" : "宿舍",
                            school.getDeptName()
                        ));
                        appNotice.setUserIds(Collections.singletonList(parent.getYidaAppUserId()));
                        appNotice.setPushMessage(new PushMessage(school.getDeptName() + "智慧校园",
                            account.getYidaAppAccountId()));
                        AppUtil.sendMsg(appNotice, yidaApp);
                    }
                    log.info("push attendance yida msg:{}", appNotice);
                }
            }
        }
    }

    @Override
    public void sendCollectFailNotice(String picUrl, Long userId, Integer type) {
        Dept school = null;
        EduApp app;
        // 学生和职工的通知样式不同

        NewsSchoolNotice newsSchoolNotice = new NewsSchoolNotice();

        Article article = new Article();
        article.setTitle("人脸审核不通过");

        newsSchoolNotice.setNews(new News(Collections.singletonList(article)));

        if (type == 0) {
            EduStudent student = remoteStudentService.getStudentNoPermission(userId).getData();
            school = commonService.getDept(student.getSchoolId());
            app = commonService.getAppByCodeAndSchool(AppConstant.COLLECT_PARENT, null, school.getDeptId());
            String token = wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret());
            article.setPicurl(picUrl);
            newsSchoolNotice.setAgentid(app.getWxAgentId());
            // 跳转链接
            String url = pageUrl + PARENT_COLLECT_FAIL_URL + "?studentId=" + student.getId() + "&corpId=" +
                app.getWxCorpId();
            article.setUrl(url);
            article.setDescription("点击图片重新采集");
            newsSchoolNotice.setTo_student_userid(Collections.singletonList(student.getWxId()));
            // 每个家长发送消息
            wxUtil.pushSchoolNotice(token, newsSchoolNotice);
        }
    }
}
