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

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.entity.applyForm.CoreApprovalRemind;
import com.yida.data.common.core.entity.constant.AppConstant;
import com.yida.data.common.core.entity.constant.NoticeTypeConstant;
import com.yida.data.common.core.entity.notice.qywx.TemplateCardStaffNotice;
import com.yida.data.common.core.entity.notice.qywx.TextSchoolNotice;
import com.yida.data.common.core.entity.notice.qywx.inside.TemplateCardNotice;
import com.yida.data.common.core.entity.notice.qywx.inside.Text;
import com.yida.data.common.core.entity.notice.qywx.inside.templateCard.CardAction;
import com.yida.data.common.core.entity.notice.qywx.inside.templateCard.HorizontalContent;
import com.yida.data.common.core.entity.notice.qywx.inside.templateCard.Jump;
import com.yida.data.common.core.entity.notice.qywx.inside.templateCard.MainTitle;
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.user.EduStudent;
import com.yida.data.common.core.enums.EnableStatusEnum;
import com.yida.data.common.core.enums.leave.ApprovalResultEnum;
import com.yida.data.common.core.utils.WxUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.customForm.dto.apply.SendParentNoticeDTO;
import com.yida.data.customForm.dto.apply.SendStaffNoticeDTO;
import com.yida.data.form.apply.service.CoreApprovalRemindService;
import com.yida.data.form.apply.service.SendNoticeService;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 发送消息 Service
 *
 * @author ZYJ
 * @date 2023/11/30
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class SendNoticeServiceImpl implements SendNoticeService {

    private final CoreApprovalRemindService coreApprovalRemindService;

    private final RemoteStudentService remoteStudentService;

    private final WxUtil wxUtil;
    private final CommonService commonService;

    @Value("${febs.parentFormNoticeUrl}")
    private String parentFormNoticeUrl;

    @Value("${febs.teacherFormNoticeUrl}")
    private String teacherFormNoticeUrl;

    @Override
    public void sendStaffNotice(SendStaffNoticeDTO dto, Integer isFirst) {
        // 需要判断是否要推送消息
        CoreApprovalRemind approvalRemind = coreApprovalRemindService.getOne(Wrappers.lambdaQuery(new CoreApprovalRemind())
                .eq(CoreApprovalRemind::getDeptId, dto.getSchoolId()));
        if (Objects.nonNull(approvalRemind)
                && EnableStatusEnum.ENABLE_STATUS.getStatus().equals(approvalRemind.getApprovalRemindStatus())) {
            // 企业微信推送消息
            if (dto.getSchoolType().contains(Dept.TYPE_QYWX)) {
                // 查询推送消息的应用信息
                EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT_SELECT, null,
                        dto.getSchoolId());
                String accessToken = wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret());
                // 跳转职工审核页面
                String url = String
                        .format("%s?corpId=%s&schoolId=%s&userType=%s&formId=%s&fillUserId=%s&userId=%s&currentUserStatus=%s", teacherFormNoticeUrl,
                                app.getWxCorpId(),
                                dto.getSchoolId(), 0, dto.getFormId(), dto.getFillUserId(), dto.getUserId(), 0);
                log.error("申请表单职工url: {}", url);
                // 模板卡片消息--文本通知型
                TemplateCardNotice templateCardNotice = new TemplateCardNotice();
                templateCardNotice.setCard_type(NoticeTypeConstant.TEMPLATE_NOTICE_TYPE_TEXT);
                templateCardNotice.setMain_title(MainTitle.builder().title("学生申请提醒").build());

                // 是否为初次审核
                if (isFirst == 1) {
                    // 初次审核
                    templateCardNotice
                            .setSub_title_text(String.format("尊敬的%s老师，%S同学于%S提交的申请信息，等待您的审批!",
                                    dto.getStaffName(), dto.getUserName(),
                                    LocalDateTimeUtil.format(dto.getCreateTime(), "yyyy-MM-dd HH:mm:ss")));
                } else {
                    // 非初次审核
                    templateCardNotice
                            .setSub_title_text(String.format("尊敬的%s老师，你好！%S老师【%S】已同意%S同学于%S提交的申请信息，等待您的审批!",
                                    dto.getStaffName(), dto.getPreStaffName(), dto.getPreStaffRoleName(), dto.getUserName(),
                                    LocalDateTimeUtil.format(dto.getCreateTime(), "yyyy-MM-dd HH:mm:ss")));
                }

                List<HorizontalContent> horizontalContentList = new ArrayList<>();
                horizontalContentList
                        .add(HorizontalContent.builder().keyname("班级").value(dto.getUserDeptName()).build());
                horizontalContentList
                        .add(HorizontalContent.builder().keyname("学生").value(dto.getUserName()).build());

                horizontalContentList.add(HorizontalContent.builder().keyname("申请时间")
                        .value(LocalDateTimeUtil.format(dto.getCreateTime(), "yyyy-MM-dd HH:mm")).build());
                templateCardNotice.setHorizontal_content_list(horizontalContentList);
                templateCardNotice.setCard_action(CardAction.builder().type(1).url(url).build());
                templateCardNotice
                        .setJump_list(Collections.singletonList(Jump.builder().type(1).title("点击查看详情并处理").url(url).build()));

                TemplateCardStaffNotice templateCardStaffNotice = new TemplateCardStaffNotice();
                templateCardStaffNotice.setTouser(dto.getStaffWxId());
                templateCardStaffNotice.setAgentid(app.getWxAgentId());
                templateCardStaffNotice.setTemplate_card(templateCardNotice);
                // 发送企业微信通知
                wxUtil.pushStaffNotice(accessToken, templateCardStaffNotice);
            }
        }
    }

    @Override
    public void sendParentNotice(SendParentNoticeDTO dto) {
        // 学校信息
        Dept school = dto.getSchool();
        // 学生信息
        EduStudent student = dto.getStudent();

        // 需要判断是否要推送消息
        CoreApprovalRemind approvalRemind = coreApprovalRemindService.getOne(Wrappers.lambdaQuery(new CoreApprovalRemind())
                .eq(CoreApprovalRemind::getDeptId, school.getDeptId()));
        if (Objects.nonNull(approvalRemind)
                && EnableStatusEnum.ENABLE_STATUS.getStatus().equals(approvalRemind.getApprovalResultStatus())) {
            // 企业微信推送消息
            if (school.getSchoolType().contains(Dept.TYPE_QYWX)) {
                TextSchoolNotice textSchoolNotice = new TextSchoolNotice();
                // 查询推送消息的应用信息
                EduApp appByCodeAndSchool = commonService.getAppByCodeAndSchool(AppConstant.INDEX_PARENT, null, school.getDeptId());
                // 查询家长id集合
                List<String> parentId = remoteStudentService.findParentWxId(Collections.singletonList(student.getId())).getData();
                Text text = new Text();
                textSchoolNotice.setText(text);
                textSchoolNotice.setAgentid(appByCodeAndSchool.getWxAgentId());
                // 跳转学生填报详情页面
                String url = String
                        .format("%s?corpId=%s&schoolId=%s&userType=%s&formId=%s&fillUserId=%s&userId=%s", parentFormNoticeUrl,
                                appByCodeAndSchool.getWxCorpId(),
                                school.getDeptId(), 1, dto.getFormId(), dto.getFillUserId(), dto.getStudent().getId());

                String msg = ObjectUtil.equals(ApprovalResultEnum.AUDIT_PASS.getResult(), dto.getExamineStatus()) ? "已通过" : "未通过";
                text.setContent(
                        "<a href='" + url + "'>" + student.getStuName() + "同学于" +
                                LocalDateTimeUtil.format(dto.getCreateTime(), "yyyy-MM-dd HH:mm:ss")
                                + "的申请" + msg + "，点击可查看详情" + "</a>");
                textSchoolNotice.setTo_parent_userid(parentId);
                // 发送信息
                String accessToken = wxUtil.getAccessToken(appByCodeAndSchool.getWxCorpId(), appByCodeAndSchool.getWxSecret());
                wxUtil.pushSchoolNotice(accessToken, textSchoolNotice);
            }

        }
    }
}
