package com.fizz.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fizz.business.constants.CommonConstants;
import com.fizz.business.constants.enums.WsTypeEnum;
import com.fizz.business.domain.ModSetupResult;
import com.fizz.business.form.CalcPdiPlanForm;
import com.fizz.business.form.ModSetupResultForm;
import com.fizz.business.mapper.ModSetupResultMapper;
import com.fizz.business.service.ModSetupResultService;
import com.fizz.business.utils.WebSocketUtil;
import com.fizz.business.vo.ModSetupResultKeyVO;
import com.fizz.business.vo.ModSetupResultVO;
import org.apache.commons.compress.utils.Lists;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

@Service
public class ModSetupResultServiceImpl extends ServiceImpl<ModSetupResultMapper, ModSetupResult> implements ModSetupResultService {

    @Resource
    RabbitTemplate rabbitTemplate;

    public static String  WS_EKY = "";

    @Override
    public List<ModSetupResultVO> list(ModSetupResultForm form) {

//        // 确保各个字段的非空验证
//        if (StringUtils.isEmpty(form.getGrade()) || form.getAnnealThick() == null ||
//                form.getEntryThick() == null || form.getExitThick() == null || form.getPassno() == null) {
//            throw new IllegalArgumentException("必要的字段缺失");
//        }
//
//        // 去除Double类型的字段的小数位
//        // 获取厚度并处理
//        int annealThick = Math.round(form.getAnnealThick() * 100);  // 乘以100并四舍五入
//        int entryThick = (int) Math.round(form.getEntryThick() * 100);    // 乘以100并四舍五入
//        int exitThick = (int) Math.round(form.getExitThick() * 100);      // 乘以100并四舍五入
//
//        // 格式化为三位数字
//        String annealThickStr = String.format("%03d", annealThick);
//        String entryThickStr = String.format("%03d", entryThick);
//        String exitThickStr = String.format("%03d", exitThick);
//
//        // 根据字段构建 calcId
//        String calcId = form.getGrade() + annealThickStr + entryThickStr + exitThickStr + form.getPassno();

        // 实际查询代码（根据 calcId 查询数据）
        // 这里假设查询方法为根据 calcId 查找结果
//        LambdaQueryWrapper<ModSetupResult> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ModSetupResult::getCalcId, calcId);


        return this.getSetupByCoilid(form.getCoilId());
    }

    @Override
    public String calcSetup(CalcPdiPlanForm form) {

        //发送MQ
        MessageProperties props = MessagePropertiesBuilder.newInstance()
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .setMessageId("CALL_SETUP")
                .build();
        rabbitTemplate.send(CommonConstants.RabbitMQ.SEND_MODEL,new Message(JSONUtil.toJsonStr(form).getBytes(StandardCharsets.UTF_8),props));

        // 获取当前时间的毫秒级时间戳
        long timestampMillis = LocalDateTime.now().atZone(ZoneOffset.UTC).toInstant().toEpochMilli();

        // 生成字符串：由 coilid 和当前时间戳拼接而成

        // 先返回构建的字符串
        // 这里是返回值先返回，后面调用副作用的逻辑

        // 然后调用mockCalcResult方法，它是异步的，不会影响返回值
        // mockCalcResult将会在返回之后执行，不影响calcSetup的返回
//        new Thread(() -> mockCalcResult(form.getCoilid(), resultString)).start();

        // 返回值会先返回给调用者
        String string = form.getCoilid() + timestampMillis;
        WS_EKY = string;
        return string;
    }

    private void mockCalcResult(String coilid, String string) {

        List<ModSetupResultVO> setup = this.getSetupByCoilid(coilid);


        ModSetupResultKeyVO modSetupResultKeyVO = new ModSetupResultKeyVO();
        modSetupResultKeyVO.setKey(string);
        modSetupResultKeyVO.setLists(setup);
        //socket
        WebSocketUtil.sendMessage(WsTypeEnum.calc_setup_result,JSONUtil.toJsonStr(modSetupResultKeyVO));


    }

    @Override
    public String retrySetup(String coilid) {

       try {
           //发送MQ
           MessageProperties props = MessagePropertiesBuilder.newInstance()
                   .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                   .setMessageId("CALL_SETUP_BY_COILID")
                   .build();
           rabbitTemplate.send(CommonConstants.RabbitMQ.SEND_MODEL,new Message(coilid.getBytes(StandardCharsets.UTF_8),props));
       }catch (Exception e){


       }

        return "";
    }

    @Override
    public List<ModSetupResultVO> getSetupByCoilid(String coilid) {

        LambdaQueryWrapper<ModSetupResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ModSetupResult::getCoilId,coilid);

        List<ModSetupResult> results = this.baseMapper.selectList(queryWrapper);

        if (results == null || results.isEmpty()){

            return Lists.newArrayList();
        }


        return BeanUtil.copyToList(results, ModSetupResultVO.class);
    }

}