package com.bonus.material.warning;

import cn.hutool.json.JSONObject;
import com.ah.sbd.SmsTool;
import com.ah.sbd.utils.param.BatchSmsByContentParam;
import com.ah.sbd.utils.param.SmsParam;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.constant.BmConfigItems;
import com.bonus.common.biz.domain.lease.LeaseApplyInfo;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.material.back.domain.BackApplyInfo;
import com.bonus.material.back.service.IBackApplyInfoService;
import com.bonus.material.warningAnalysis.domain.UseMaintenanceWarningBean;
import com.bonus.material.warningAnalysis.mapper.UseMaintenanceWarningMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 任务定时推送相关人员任务控制器
 * @author ma_sh
 */
@Component
@Slf4j
public class ScheduledCheckWarning {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Resource
    private UseMaintenanceWarningMapper mapper;

    @Resource
    private ScheduledTaskRegistrar scheduledTaskRegistrar;

    /**
     * 定时任务执行频率，每周三/五天上午9点执行一次
     */
    private String cronExpression = "0 0 9 ? * WED,FRI";


    /**
     * 初始化定时任务
     */
    @PostConstruct
    public void init() {
        cronExpression = getCronFromDatabase();
        updateCronTask();
    }

    /**
     * 更新定时任务
     */
    private void updateCronTask() {
        scheduledTaskRegistrar.getScheduler().schedule(() -> {
            taskWithFixedRate();
        }, new CronTrigger(cronExpression));
    }

    /**
     * 从数据库中获取 cron 表达式
     * @return
     */
    private String getCronFromDatabase() {
        // 这里假设从数据库中获取 cron 表达式
        //return "0 */1 * * * ?";
        return "0 0 9 ? * WED,FRI";
    }

    /**
     * 定时任务执行频率，每周三/五天上午9点执行一次安全工器具预警短信推送，
     * 临检30天推送所在工程（项目经理、总工、材料员），频率为每周五进行推送；
     * 临检15天推送工程所在分公司（施工管理科副科长、分公司分管领导），每周三、五进行推送。
     * 每三天的上午9点执行
     */
    public void taskWithFixedRate() {
        log.info("开始执行安全工器具预警短信推送任务");
        //查询各个工程预警的设备总数，分别推送给各工程负责人

//截止当天XX工程，速差器、安全带等X件工器具已临检检验有效期30天，请尽快退回机具（物流）分公司复检，明细请登录机具管理系统查看
         List<UseMaintenanceWarningBean> monthList = mapper.getWarningLastMonthList(new UseMaintenanceWarningBean());
// 发送短信
        try {

            if(monthList !=null && monthList.size()>0){
                for (UseMaintenanceWarningBean bean : monthList) {
                    //根据皖送平台工程id查询项目经理、总工，获取手机号
                    UseMaintenanceWarningBean projectManager = mapper.getProjectManager(bean);
                    String leaderPhone = projectManager.getLeaderPhone();
                    String engPhone = projectManager.getEngPhone();
                    String content = "截止当天" + bean.getProjectName() +"，"+ bean.getTypeName() +"共" +bean.getWarnNum() + "件工器具已临检检验有效期30天，请尽快退回机具（物流）分公司复检，明细请登录机具管理系统查看";

                    // 省公司短信发送
                    List<String> mobileList = new ArrayList();
                    List<UseMaintenanceWarningBean> userList = mapper.getUserList(bean);

                    if(userList !=null && userList.size()>0){
                        for (UseMaintenanceWarningBean item : userList){
                            UseMaintenanceWarningBean item1 = mapper.getUserPhoneById(item);
                            if(item1.getClzPhone() != null){
                                mobileList.add(item1.getClzPhone());
                            }
                        }
                    }

                    mobileList.add(leaderPhone);
                    mobileList.add(engPhone);
                    System.out.println("短信发送成功: " + mobileList);
                    if (CollectionUtils.isNotEmpty(mobileList)){
                        JSONObject sendResult = SmsTool.sendSms(new BatchSmsByContentParam(mobileList, content), BmConfigItems.ANHUI_COMPANY_SMS_KEY);
                        if (sendResult != null && !sendResult.isEmpty()) {
                            log.info("短信发送成功: {}", sendResult);
                            System.out.println("短信发送成功: " + sendResult);
                        } else {
                            log.error("短信发送失败，发送结果为空!");
                            System.out.println("短信发送失败，发送结果为空!");
                        }
                    }



                }
            }

            //截止当天XX工程，速差器、安全带等X件工器具已临检检验有效期15天，请尽快退回机具（物流）分公司复检，明细请登录机具管理系统查看
            List<UseMaintenanceWarningBean> dayList = mapper.getWarningLastDayList(new UseMaintenanceWarningBean());
            if(dayList !=null && dayList.size()>0){
                for (UseMaintenanceWarningBean bean2 : dayList) {
                    //根据工程所属分公司查询施工管理科副科长、分公司分管领导，获取手机号

                    String content2 = "截止当天" + bean2.getProjectName() +","+ bean2.getTypeName() +"共"+ bean2.getWarnNum() + "件工器具已临检检验有效期15天，请尽快退回机具（物流）分公司复检，明细请登录机具管理系统查看";

                    // 省公司短信发送
                    List<String> mobileList2 = new ArrayList();
                    List<UseMaintenanceWarningBean> userManger = mapper.getUserManger(bean2);

                    if(userManger !=null && userManger.size()>0){
                        for (UseMaintenanceWarningBean item : userManger){
                            UseMaintenanceWarningBean item1 = mapper.getUserPhoneById(item);
                            if(item1.getClzPhone() != null){
                                mobileList2.add(item1.getClzPhone());
                            }
                        }
                    }
                    System.out.println("短信发送成功: " + mobileList2);
                    if (CollectionUtils.isNotEmpty(mobileList2)){
                        JSONObject sendResult = SmsTool.sendSms(new BatchSmsByContentParam(mobileList2, content2), BmConfigItems.ANHUI_COMPANY_SMS_KEY);
                        if (sendResult != null && !sendResult.isEmpty()) {
                            log.info("短信发送成功: {}", sendResult);
                            System.out.println("短信发送成功: " + sendResult);
                        } else {
                            log.error("短信发送失败，发送结果为空!");
                            System.out.println("短信发送失败，发送结果为空!");
                        }
                    }



                }
            }

        } catch (Exception e) {
            log.error("短信发送过程中发生异常: {}", e.getMessage());
            System.out.println("短信发送过程中发生异常: " + e.getMessage());
        }
         // 记录任务执行时间
        log.info("执行安全工器具预警短信推送任务执行时间：" + LocalDateTime.now().format(FORMATTER));
        System.out.println("执行安全工器具预警短信推送任务任务执行时间：" + LocalDateTime.now().format(FORMATTER));
    }

}
