package cn.ezhizao.framework.task;


import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.framework.qrCode.QcContent;
import cn.ezhizao.framework.qrCode.QrCodeService;
import cn.ezhizao.framework.web.domain.Server;
import cn.ezhizao.project.business.carrier.domain.BizCarrier;
import cn.ezhizao.project.business.carrier.service.IBizCarrierService;
import cn.ezhizao.project.business.email.domain.BizEmail;
import cn.ezhizao.project.business.email.service.IBizEmailService;
import cn.ezhizao.project.business.equipment.domain.BizEquipmentDetail;
import cn.ezhizao.project.business.equipment.service.IBizEquipmentDetailService;
import cn.ezhizao.project.business.message.domain.BizMessage;
import cn.ezhizao.project.business.message.service.IBizMessageService;
import cn.ezhizao.project.business.packageResourceGroup.domain.BizPackageResourceGroup;
import cn.ezhizao.project.business.packageResourceGroup.service.IBizPackageResourceGroupService;
import cn.ezhizao.project.system.service.ISysConfigService;
import cn.ezhizao.project.tool.email.service.EmailService;
import cn.ezhizao.project.websocket.WebSocketUser;
import cn.hutool.core.date.DateTime;
import com.alibaba.nacos.api.config.ConfigService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask {
    @Value("${file.upload.path}")
    private String uploadPath;
    @Resource
    ObjectMapper mapper;
    @Resource
    QrCodeService qrCodeService;

    @Resource
    IBizEquipmentDetailService bizEquipmentDetailService;

    @Resource
    IBizPackageResourceGroupService bizPackageResourceGroupService;

    @Resource
    IBizCarrierService bizCarrierService;

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() {
        System.out.println("执行无参方法");
    }

    public void resetCurrentCode() {
        List<BizPackageResourceGroup> groupList =bizPackageResourceGroupService.list();
        groupList.forEach(l -> {
            l.setCode("000000");
            l.setYear(DateTime.now().toString("yy"));
        });
        bizPackageResourceGroupService.updateBatchById(groupList);
    }


    /**
     * 新生成二维码方法，只生成箱号字符串
     */
    public <T> void GenerateQcCode(T t) throws JsonProcessingException {
        String className = t.getClass().getName();
        String content;
        String path;
        QcContent qcContent = new QcContent();
        switch (className) {
            case "cn.ezhizao.project.business.equipment.domain.BizEquipmentDetail":
                BizEquipmentDetail equipment = (BizEquipmentDetail) t;
                qcContent.setEquipmentDetailId(equipment.getId());
                qcContent.setEquipmentDetailCode(equipment.getEquipmentCode());
                qcContent.setType("equipment");
                content = mapper.writeValueAsString(qcContent);
                path = uploadPath + "qcCode/equipment/" + qcContent.getEquipmentDetailCode() + ".png";
                equipment.setQcCode("/profile/upload/qcCode/equipment/" + qcContent.getEquipmentDetailCode() + ".png");
                qrCodeService.createNewCodeToFile(content, path, qcContent.getEquipmentDetailCode());
                bizEquipmentDetailService.updateById(equipment);
                break;

            case "cn.ezhizao.project.business.carrier.domain.BizCarrier":

                BizCarrier carrier = (BizCarrier) t;
                // 定义二维码图片的存储路径
                String carrierCode = carrier.getCode(); // 假设您仍然需要使用carrier的code
                path = uploadPath + "qcCode/carrier/" + carrierCode + ".png";

                // 更新carrier对象的qcCode属性
                carrier.setQcCode("/profile/upload/qcCode/carrier/" + carrierCode + ".png");

                // 直接使用字符串生成二维码并保存到文件
                // 假设createNewCodeToFile方法可以接受一个字符串参数
                qrCodeService.createNewCodeToFile(carrierCode, path, carrierCode);


//                bizCarrierService.updateById(carrier);
//                BizCarrier carrier = (BizCarrier) t;
//                qcContent.setCarrierId(carrier.getId());
//                qcContent.setCarrierCode(carrier.getCode());
//                qcContent.setType("carrier");
//                content = mapper.writeValueAsString(qcContent);
//                path = uploadPath + "qcCode/carrier/" + qcContent.getCarrierCode() + ".png";
//                carrier.setQcCode("/profile/upload/qcCode/carrier/" + qcContent.getCarrierCode() + ".png");
//                qrCodeService.createNewCodeToFile(content, path, qcContent.getCarrierCode());
                bizCarrierService.updateById(carrier);
                break;


            default:
                break;
        }
    }


    @Resource
    IBizMessageService messageService;

    public void checkMessage() throws IOException {
        List<BizMessage> messages = messageService.query().eq("msg_read", 0).list();
        Map<Long, List<BizMessage>> groupById = messages.stream().collect(Collectors.groupingBy(BizMessage::getToUserId, Collectors.toList()));
        for (Map.Entry<Long, List<BizMessage>> entry : groupById.entrySet()) {
            WebSocketUser.sendInfo(String.valueOf(entry.getValue().size()), String.valueOf(entry.getKey()));
        }
        WebSocketUser.sendEmptyMessage(messages.stream().map(BizMessage::getToUserId).collect(Collectors.toList()));
    }

    @Autowired
    EmailService emailService;
    @Resource
    ISysConfigService sysConfigService;
    @Resource
    IBizEmailService bizEmailService;

    public void checkRemainStorage() throws Exception {
        // 获取存储余量
        Server server = new Server();
        server.copyTo();
//        String free = server.getSysFiles().get(0).getFree();
//        BigDecimal freeSpace = BigDecimal.valueOf(Double.parseDouble(free.substring(0, free.length() - 1)));
//        String total = server.getSysFiles().get(0).getTotal();
//        BigDecimal totalSpace = BigDecimal.valueOf(Double.parseDouble(total.substring(0, total.length() - 1)));
        // 判断存储余量
        String config = sysConfigService.selectConfigByKey("storage_alarm");
        System.out.println("总磁盘空间：" + server.getSysFiles().get(0).getTotal());
        System.out.println("磁盘空间剩余：" + server.getSysFiles().get(0).getFree());
        System.out.println("磁盘空间使用比例：" + server.getSysFiles().get(0).getUsage());
        System.out.println("预警比例：" + config);
        List<BizEmail> bizEmails = bizEmailService.query().eq("type", 1).eq("is_stop", 0).list();
        try {
            if (config != null && Double.parseDouble(config) > 0) {
                BigDecimal storageAlarm = BigDecimal.valueOf(Double.parseDouble(config));
                BigDecimal usage = BigDecimal.valueOf(100).subtract(BigDecimal.valueOf(server.getSysFiles().get(0).getUsage()));
//                BigDecimal storageAlarmSpace = totalSpace.multiply(storageAlarm);
                if (usage.compareTo(storageAlarm.multiply(BigDecimal.valueOf(100))) < 0) {
                    bizEmails.forEach(l -> {
                        emailService.sendEmail(l.getEmailAddress(), "存储空间预警", "服务器存储剩余空间" + server.getSysFiles().get(0).getFree());
                    });
//                    emailService.sendEmail("linliaoyouyin@163.com", "存储空间预警", "服务器存储剩余空间" + server.getSysFiles().get(0).getFree());
//                    emailService.sendEmail("zhanghongsen@cdms-china.com", "存储空间预警", "服务器存储剩余空间" + server.getSysFiles().get(0).getFree());
//                    emailService.sendEmail("bgs-yjl@cdms-china.com", "存储空间预警", "服务器存储剩余空间" + server.getSysFiles().get(0).getFree());
                }
            } else {
                // 发送邮件通知管理员
                bizEmails.forEach(l -> {
                    emailService.sendEmail(l.getEmailAddress(), "存储空间预警", "存储余量预警值设置为" + config + "小于0或大于1");
                });
//                emailService.sendEmail("linliaoyouyin@163.com", "存储余量预警值参数错误", "存储余量预警值设置为" + config + "小于0或大于1");
//                emailService.sendEmail("zhanghongsen@cdms-china.com", "存储余量预警值参数错误", "存储余量预警值设置为" + config + "小于0或大于1");
//                emailService.sendEmail("bgs-yjl@cdms-china.com", "存储余量预警值参数错误", "存储余量预警值设置为" + config + "小于0或大于1");
            }
        } catch (NumberFormatException e) {
            // 发送邮件通知管理员
            String text = "存储余量预警值设置为" + (config == null || config.isEmpty() ? "空" : config) + "为非数字，设置错误。请重新设置。";
            bizEmails.forEach(l -> {
                emailService.sendEmail(l.getEmailAddress(), "存储余量预警值参数错误", text);
            });
//            emailService.sendEmail("linliaoyouyin@163.com", "存储余量预警值参数错误", text);
//            emailService.sendEmail("zhanghongsen@cdms-china.com", "存储余量预警值参数错误", text);
//            emailService.sendEmail("bgs-yjl@cdms-china.com", "存储余量预警值参数错误", text);
        }

    }

    /** 原始二维码生成方法，生成JSON格式
     * public <T> void  GenerateQcCode(T t) throws JsonProcessingException {
     *         String className = t.getClass().getName();
     *         String content;
     *         String path;
     *         QcContent qcContent = new QcContent();
     *         switch (className) {
     *             case "cn.ezhizao.project.business.equipment.domain.BizEquipmentDetail":
     *                 BizEquipmentDetail equipment = (BizEquipmentDetail) t;
     *                 qcContent.setEquipmentDetailId(equipment.getId());
     *                 qcContent.setEquipmentDetailCode(equipment.getEquipmentCode());
     *                 qcContent.setType("equipment");
     *                 content = mapper.writeValueAsString(qcContent);
     *                 path = uploadPath + "qcCode/equipment/" + qcContent.getEquipmentDetailCode() + ".png";
     *                 equipment.setQcCode("/profile/upload/qcCode/equipment/" + qcContent.getEquipmentDetailCode() + ".png");
     *                 qrCodeService.createNewCodeToFile(content, path,qcContent.getEquipmentDetailCode());
     *                 bizEquipmentDetailService.updateById(equipment);
     *                 break;
     *
     *             case "cn.ezhizao.project.business.carrier.domain.BizCarrier":
     *                 BizCarrier carrier = (BizCarrier) t;
     *                 qcContent.setCarrierId(carrier.getId());
     *                 qcContent.setCarrierCode(carrier.getCode());
     *                 qcContent.setType("carrier");
     *                 content = mapper.writeValueAsString(qcContent);
     *                 path = uploadPath + "qcCode/carrier/" + qcContent.getCarrierCode() + ".png";
     *                 carrier.setQcCode("/profile/upload/qcCode/carrier/" + qcContent.getCarrierCode() + ".png");
     *                 qrCodeService.createNewCodeToFile(content, path,qcContent.getCarrierCode());
     *                 bizCarrierService.updateById(carrier);
     *                 break;
     *
     *
     *             default:
     *                 break;
     *         }
     *     }
     * */
}
