package cn.iocoder.yudao.module.system.job;

import cn.hutool.core.date.ChineseDate;
import cn.iocoder.yudao.framework.common.util.corp.CorpMsgUtil;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.bpm.enums.message.BpmMessageEnum;
import cn.iocoder.yudao.module.system.api.bpm.vo.MessgeUserRespVO;
import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApi;
import cn.iocoder.yudao.module.system.api.notify.convert.message.UserMessageConvert;
import cn.iocoder.yudao.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.yudao.module.system.api.wechat.dto.CorpSendMessage;
import cn.iocoder.yudao.module.system.api.wechat.dto.CorpWechatTextcard;
import cn.iocoder.yudao.module.system.api.wechat.dto.WechatMessageSaveReq;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.ByodRegistrationRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ByodRegistrationDrugDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyContractDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.sys.BusinessParamsConfigDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ByodRegistrationDrugMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ByodRegistrationMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyContractMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.sys.BusinessParamsConfigMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.module.system.enums.common.BooleanEnum;
import cn.iocoder.yudao.module.system.enums.notice.NotieBusinessTypeEnum;
import cn.iocoder.yudao.module.system.enums.notice.NotifyPriorityEnum;
import cn.iocoder.yudao.module.system.enums.notice.NotifyTypeEnum;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

import static cn.iocoder.yudao.module.system.enums.NoticeConstants.*;

/**
 * @Author: jinyd
 * @CreateTime: 2025/2/18  10:20
 * @Description:
 * @Version: 4.0
 */

@Component
public class BusinessConfigJob implements JobHandler {

    private final static Logger logger = LoggerFactory.getLogger(SleepDeviceJob.class);

    @Autowired
    private BusinessParamsConfigMapper businessParamsConfigMapper;

    @Autowired
    private ByodRegistrationMapper byodRegistrationMapper;
    @Autowired
    private ByodRegistrationDrugMapper registrationDrugMapper;

    @Autowired
    private NotifyMessageSendApi notifyMessageSendApi;

    @Autowired
    private ElderlyContractMapper contractMapper;

    @Autowired
    private ElderlyInfoMapper elderlyInfoMapper;

    @Autowired
    private AdminUserMapper userMapper;

    @Override
    @TenantJob
    public String execute(String jsonParam) {

//        Gson gson = new Gson();
//        JsonObject jsonObject = gson.fromJson(jsonParam, JsonObject.class);
//        JsonElement orgTypeElement = jsonObject.get("orgType");
//        Long orgType = orgTypeElement.getAsLong();

        Long tenantId = TenantContextHolder.getTenantId();
        System.out.println("tenantId = " + tenantId);

        if(!tenantId.equals(195l)) {
            return "";
        }

        List<BusinessParamsConfigDO> businessParamsConfigDOS = businessParamsConfigMapper.selectListByName(tenantId,
                SELF_MEDICATION_WARNING_NAME, SELF_MEDICATION_EXPIRE_NAME, ELDERLY_CONTRACT_EXPIRE_NAME, ELDER_BIRTHDAY_NAME);


        for (int i = 0; i < businessParamsConfigDOS.size(); i++) {
            BusinessParamsConfigDO businessParamsConfigDO = businessParamsConfigDOS.get(i);
            LocalDate now = LocalDate.now();
            List<MessgeUserRespVO> userList = userMapper.getMessageList();
            if (SELF_MEDICATION_WARNING_NAME.equals(businessParamsConfigDO.getConfigName()) ||
                    SELF_MEDICATION_EXPIRE_NAME.equals(businessParamsConfigDO.getConfigName())) {

                List<ByodRegistrationRespVO> list = byodRegistrationMapper.getByodRegistrationList();
                list.forEach(byodRegistrationRespVO -> {
                    Boolean messageFlag = Boolean.FALSE;
                    List<ByodRegistrationDrugDO> byodRegistrationDrugDOS = registrationDrugMapper.selectList(new LambdaQueryWrapperX<ByodRegistrationDrugDO>()
                            .eq(ByodRegistrationDrugDO::getByodRegistrationId, byodRegistrationRespVO.getId()));
                    LocalDate date= null;
                    for (int j = 0; j < byodRegistrationDrugDOS.size(); j++) {
                        ByodRegistrationDrugDO byodRegistrationDrugDO = byodRegistrationDrugDOS.get(j);
                        Integer plusDays = null;

                        if (SELF_MEDICATION_WARNING_NAME.equals(businessParamsConfigDO.getConfigName())) {
                            plusDays = - Integer.parseInt(businessParamsConfigDO.getValue());
                            LocalDate reminderDate = null;
                            if (null != byodRegistrationDrugDO.getExpectedUsableTime()) {
                                reminderDate = byodRegistrationDrugDO.getExpectedUsableTime().plusDays(plusDays);
                            } else {
                                reminderDate = LocalDate.parse("1990-01-01");
                            }
                            if (now.isEqual(reminderDate)) {
                                messageFlag = Boolean.TRUE;
                            }
                            date = byodRegistrationDrugDO.getExpectedUsableTime();
                        }
                        if (SELF_MEDICATION_EXPIRE_NAME.equals(businessParamsConfigDO.getConfigName())) {
                            plusDays = - Integer.parseInt(businessParamsConfigDO.getValue());
                            LocalDate reminderDate = byodRegistrationDrugDO.getExpireTime().plusDays(plusDays);
                            if (now.isEqual(reminderDate)) {
                                messageFlag = Boolean.TRUE;
                            }
                            date = byodRegistrationDrugDO.getExpireTime();
                        }
                        if (!messageFlag) return;
                    }
                    if (messageFlag) {
                        Long elderId = byodRegistrationRespVO.getElderId();
                        String elderName = byodRegistrationRespVO.getElderName();
                        Map<String, Object> templateParams = new HashMap<>();
                        templateParams.put("elderName", elderName);
                        templateParams.put("date", date.toString());
                        String templateCode = "";
                        String url = "";
                        if (SELF_MEDICATION_WARNING_NAME.equals(businessParamsConfigDO.getConfigName())) {
                            url = String.format(SELF_MEDICATION_WARNING_URL, byodRegistrationRespVO.getId(), tenantId);
                            templateCode = BpmMessageEnum.SELF_MEDICATION_WARNING_HANDLE.getTemplateCode();
                        }
                        if (SELF_MEDICATION_EXPIRE_NAME.equals(businessParamsConfigDO.getConfigName())) {
                            url = String.format(SELF_MEDICATION_EXPIRE_URL, byodRegistrationRespVO.getId(), tenantId);
                            templateCode = BpmMessageEnum.SELF_MEDICATION_EXPIRE_HANDLE.getTemplateCode();
                        }

                        for (int k = 0; k < userList.size(); k++) {
                            MessgeUserRespVO messgeUserRespVO = userList.get(k);
                            NotifySendSingleToUserReqDTO checkInHandleReqdto = UserMessageConvert.INSTANCE.messageConvert(messgeUserRespVO.getId(),
                                    elderId.toString(), null, url, templateCode, templateParams,
                                    NotieBusinessTypeEnum.ORDINARY.getValue(), NotifyTypeEnum.NOTIFY_READ.getValue(),
                                    NotifyPriorityEnum.HIGH.getValue(), 0, messgeUserRespVO.getTenantId());
                            String title = CorpMsgUtil.TITLE_TODO;
                            CorpSendMessage corpSendMessage = new CorpSendMessage();
                            WechatMessageSaveReq wechatMessageSaveReq = new WechatMessageSaveReq();
                            CorpWechatTextcard corpTextCard = new CorpWechatTextcard();
                            corpTextCard.setTitle(title);
                            corpTextCard.setBtntxt(CorpMsgUtil.BTNTXT_DETAIL_NOTICE);
                            corpTextCard.setUrl("");
                            corpSendMessage.setTextcard(corpTextCard);
                            corpSendMessage.setContentType(1);
                            wechatMessageSaveReq.setTitle(title);
                            wechatMessageSaveReq.setPkMessage2("");
                            wechatMessageSaveReq.setApplyTime(DateUtils.localDateTimeToStr(LocalDateTime.now()));
                            corpSendMessage.setTouser(messgeUserRespVO.getCorpUserId());
                            wechatMessageSaveReq.setCorpUserId(messgeUserRespVO.getCorpUserId());
                            wechatMessageSaveReq.setStartTenantId(messgeUserRespVO.getTenantId());
                            wechatMessageSaveReq.setTenantName(messgeUserRespVO.getAbbreviation());
                            wechatMessageSaveReq.setPkMessage(elderId.toString());
                            wechatMessageSaveReq.setTypeName(businessParamsConfigDO.getConfigName());
                            corpSendMessage.setWechatMessageSaveReq(wechatMessageSaveReq);
                            notifyMessageSendApi.sendMessageAndCorpMessage(checkInHandleReqdto, corpSendMessage);
                        }

                    }

                });
            }
            if (ELDERLY_CONTRACT_EXPIRE_NAME.equals(businessParamsConfigDO.getConfigName())) {
                List<ElderlyContractDO> list = contractMapper.selectMessageList();
                list.forEach(elderlyContractDO -> {
                    Integer plusDays = - Integer.parseInt(businessParamsConfigDO.getValue());
                    LocalDate reminderDate = null;
                    LocalDate expireTime = null;


                    if (null != elderlyContractDO.getExpireTime()) {
                        // Date 转 LocalDate
                        expireTime = elderlyContractDO.getExpireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                        reminderDate = expireTime.plusDays(plusDays);
                    } else {
                        reminderDate = LocalDate.parse("1990-01-01");
                    }
                    if (!now.isEqual(reminderDate)) return;
                    Long elderId = elderlyContractDO.getElderId();
                    String elderName = elderlyContractDO.getElderName();
                    Map<String, Object> templateParams = new HashMap<>();
                    templateParams.put("elderName", elderName);
                    templateParams.put("date", expireTime);
                    String templateCode = BpmMessageEnum.ELDERLY_CONTRACT_EXPIRE_HANDLE.getTemplateCode();
                    String url = ELDERLY_CONTRACT_EXPIRE_URL;
                    for (int k = 0; k < userList.size(); k++) {
                        MessgeUserRespVO messgeUserRespVO = userList.get(k);
                        NotifySendSingleToUserReqDTO checkInHandleReqdto = UserMessageConvert.INSTANCE.messageConvert(messgeUserRespVO.getId(),
                                elderId.toString(), null, url, templateCode, templateParams,
                                NotieBusinessTypeEnum.ORDINARY.getValue(), NotifyTypeEnum.NOTIFY_READ.getValue(),
                                NotifyPriorityEnum.HIGH.getValue(), 0, messgeUserRespVO.getTenantId());
                        String title = CorpMsgUtil.TITLE_TODO;
                        CorpSendMessage corpSendMessage = new CorpSendMessage();
                        WechatMessageSaveReq wechatMessageSaveReq = new WechatMessageSaveReq();
                        CorpWechatTextcard corpTextCard = new CorpWechatTextcard();
                        corpTextCard.setTitle(title);
                        corpTextCard.setBtntxt(CorpMsgUtil.BTNTXT_DETAIL_NOTICE);
                        corpTextCard.setUrl("");
                        corpSendMessage.setTextcard(corpTextCard);
                        corpSendMessage.setContentType(1);
                        wechatMessageSaveReq.setTitle(title);
                        wechatMessageSaveReq.setPkMessage2("");
                        wechatMessageSaveReq.setApplyTime(DateUtils.localDateTimeToStr(LocalDateTime.now()));
                        corpSendMessage.setTouser(messgeUserRespVO.getCorpUserId());
                        wechatMessageSaveReq.setCorpUserId(messgeUserRespVO.getCorpUserId());
                        wechatMessageSaveReq.setStartTenantId(messgeUserRespVO.getTenantId());
                        wechatMessageSaveReq.setTenantName(messgeUserRespVO.getAbbreviation());
                        wechatMessageSaveReq.setPkMessage(elderId.toString());
                        wechatMessageSaveReq.setTypeName(businessParamsConfigDO.getConfigName());
                        corpSendMessage.setWechatMessageSaveReq(wechatMessageSaveReq);
                        notifyMessageSendApi.sendMessageAndCorpMessage(checkInHandleReqdto, corpSendMessage);
                    }
                });
            }
            if (ELDER_BIRTHDAY_NAME.equals(businessParamsConfigDO.getConfigName())) {
                Integer plusDays = Integer.parseInt(businessParamsConfigDO.getValue());
                LocalDate nowReminderDate = now.plusDays(plusDays);
                List<ElderlyInfoDO> gregorianCalendarElderList = elderlyInfoMapper.selectList(new LambdaQueryWrapperX<ElderlyInfoDO>()
                        .eq(ElderlyInfoDO::getBirthdayCareDate, nowReminderDate)
                        .eq(ElderlyInfoDO::getIsLunarCalendar, BooleanEnum.FALSE.getValue())
                        .isNotNull(ElderlyInfoDO::getBirthdayCareDate));

                //农历生日
                List<ElderlyInfoDO> chineseCalendarElderList = elderlyInfoMapper.selectList(new LambdaQueryWrapperX<ElderlyInfoDO>()
                        .eq(ElderlyInfoDO::getIsLunarCalendar, BooleanEnum.TRUE.getValue())
                        .isNotNull(ElderlyInfoDO::getChineseCalendar));

                for (ElderlyInfoDO elderlyInfoDO : chineseCalendarElderList) {
                    String chineseCalendar = elderlyInfoDO.getChineseCalendar();
                    String[] split = chineseCalendar.replaceAll("(?<=^|-)0+", "").split("-");
                    ChineseDate chineseDate = new ChineseDate(now.getYear(), Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                    //公历日期
                    LocalDate localDate = chineseDate.getGregorianDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    if (nowReminderDate.isEqual(localDate)) {
                        elderlyInfoDO.setBirthdayCareDate(localDate);
                        gregorianCalendarElderList.add(elderlyInfoDO);
                    }
                }
                gregorianCalendarElderList.forEach(elderlyInfoDO -> {
                    Long elderId = elderlyInfoDO.getId();
                    String elderName = elderlyInfoDO.getElderName();
                    LocalDate birthdayCareDate = elderlyInfoDO.getBirthdayCareDate();
                    Map<String, Object> templateParams = new HashMap<>();
                    templateParams.put("elderName", elderName);
                    templateParams.put("date", birthdayCareDate.toString());
                    String templateCode = BpmMessageEnum.ELDER_BIRTHDAY_HANDLE.getTemplateCode();
                    String url = ELDER_BIRTHDAY_URL;
                    for (int k = 0; k < userList.size(); k++) {
                        MessgeUserRespVO messgeUserRespVO = userList.get(k);
                        NotifySendSingleToUserReqDTO checkInHandleReqdto = UserMessageConvert.INSTANCE.messageConvert(messgeUserRespVO.getId(),
                                elderId.toString(), null, url, templateCode, templateParams,
                                NotieBusinessTypeEnum.ORDINARY.getValue(), NotifyTypeEnum.NOTIFY_READ.getValue(),
                                NotifyPriorityEnum.HIGH.getValue(), 0, messgeUserRespVO.getTenantId());
                        String title = CorpMsgUtil.TITLE_TODO;
                        CorpSendMessage corpSendMessage = new CorpSendMessage();
                        WechatMessageSaveReq wechatMessageSaveReq = new WechatMessageSaveReq();
                        CorpWechatTextcard corpTextCard = new CorpWechatTextcard();
                        corpTextCard.setTitle(title);
                        corpTextCard.setBtntxt(CorpMsgUtil.BTNTXT_DETAIL_NOTICE);
                        corpTextCard.setUrl("");
                        corpSendMessage.setTextcard(corpTextCard);
                        corpSendMessage.setContentType(1);
                        wechatMessageSaveReq.setTitle(title);
                        wechatMessageSaveReq.setPkMessage2("");
                        wechatMessageSaveReq.setApplyTime(DateUtils.localDateTimeToStr(LocalDateTime.now()));
                        corpSendMessage.setTouser(messgeUserRespVO.getCorpUserId());
                        wechatMessageSaveReq.setCorpUserId(messgeUserRespVO.getCorpUserId());
                        wechatMessageSaveReq.setStartTenantId(messgeUserRespVO.getTenantId());
                        wechatMessageSaveReq.setTenantName(messgeUserRespVO.getAbbreviation());
                        wechatMessageSaveReq.setPkMessage(elderId.toString());
                        wechatMessageSaveReq.setTypeName(businessParamsConfigDO.getConfigName());
                        corpSendMessage.setWechatMessageSaveReq(wechatMessageSaveReq);
                        notifyMessageSendApi.sendMessageAndCorpMessage(checkInHandleReqdto, corpSendMessage);
                    }
                });
            }


        }
        return "";
    }
}
