package com.zehong.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zehong.common.constant.RoboticArmConstans;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.bean.BeanUtils;
import com.zehong.common.utils.http.HttpUtils;
import com.zehong.system.domain.MesDeviceDomain;
import com.zehong.system.domain.PalletDeviceBinding;
import com.zehong.system.domain.PalletDeviceUploadHistory;
import com.zehong.system.mapper.PalletDeviceUploadHistoryMapper;
import com.zehong.system.netty.handler.NettyUdpServerHandler;
import com.zehong.system.service.IPalletDeviceUploadHistoryService;
import com.zehong.system.service.ISysConfigService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 未上传成功的历史数据列Service业务层处理
 * 
 * @author zehong
 * @date 2025-11-24
 */
@Service
public class PalletDeviceUploadHistoryServiceImpl implements IPalletDeviceUploadHistoryService 
{
    @Resource
    private PalletDeviceUploadHistoryMapper palletDeviceUploadHistoryMapper;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private IPalletDeviceUploadHistoryService palletDeviceUploadHistoryService;
    /**
     * 查询未上传成功的历史数据列
     * 
     * @param id 未上传成功的历史数据列ID
     * @return 未上传成功的历史数据列
     */
    @Override
    public PalletDeviceUploadHistory selectPalletDeviceUploadHistoryById(Long id)
    {
        return palletDeviceUploadHistoryMapper.selectPalletDeviceUploadHistoryById(id);
    }

    /**
     * 查询未上传成功的历史数据列列表
     * 
     * @param palletDeviceUploadHistory 未上传成功的历史数据列
     * @return 未上传成功的历史数据列
     */
    @Override
    public List<PalletDeviceUploadHistory> selectPalletDeviceUploadHistoryList(PalletDeviceUploadHistory palletDeviceUploadHistory)
    {
        return palletDeviceUploadHistoryMapper.selectPalletDeviceUploadHistoryList(palletDeviceUploadHistory);
    }

    @Override
    public int batchInsert(List<PalletDeviceUploadHistory> palletDeviceUploadHistoryList) {
        return palletDeviceUploadHistoryMapper.batchInsert(palletDeviceUploadHistoryList);
    }

    /**
     * 新增未上传成功的历史数据列
     * 
     * @param palletDeviceUploadHistory 未上传成功的历史数据列
     * @return 结果
     */
    @Override
    public int insertPalletDeviceUploadHistory(PalletDeviceUploadHistory palletDeviceUploadHistory)
    {
        palletDeviceUploadHistory.setCreateTime(DateUtils.getNowDate());
        return palletDeviceUploadHistoryMapper.insertPalletDeviceUploadHistory(palletDeviceUploadHistory);
    }

    /**
     * 批量处理未上传成功的数据
     * @return r
     */
    @Override
    public AjaxResult handleReUpload() {

        AjaxResult ajax = AjaxResult.success();
        List<PalletDeviceUploadHistory> palletDeviceUploadHistoriesDb = palletDeviceUploadHistoryMapper.selectPalletDeviceUploadHistoryList(new PalletDeviceUploadHistory());

        if (palletDeviceUploadHistoriesDb == null || palletDeviceUploadHistoriesDb.isEmpty()) {
            ajax.put("code", 200);
            ajax.put("msg", "上传数据列表不能为空");
            return ajax;
        }

        List<PalletDeviceUploadHistory> palletDeviceUploadHistories = palletDeviceUploadHistoriesDb.stream().filter(item -> StringUtils.isNotBlank(item.getDeviceCode())).collect(Collectors.toList());

        try {
            // 1. 初始化MES数据并上传
            List<PalletDeviceUploadHistory> failedUploads = initMesDataAndUpload(palletDeviceUploadHistories);

            // 2. 处理上传结果
            if (failedUploads.isEmpty()) {
                // 全部成功，删除所有历史数据
                List<Long> successIds = palletDeviceUploadHistories.stream()
                        .map(PalletDeviceUploadHistory::getId)
                        .collect(Collectors.toList());
                if (!successIds.isEmpty()) {
                    int deleteCount = deletePalletDeviceUploadHistoryByIds(successIds.toArray(new Long[0]));
                    return AjaxResult.success("所有数据上传成功，已删除 " + deleteCount + " 条历史记录");
                }
            } else {
                // 部分成功，只删除成功的数据
                List<Long> successIds = palletDeviceUploadHistories.stream()
                        .filter(item -> !failedUploads.contains(item))
                        .map(PalletDeviceUploadHistory::getId)
                        .collect(Collectors.toList());

                int successCount = 0;
                if (!successIds.isEmpty()) {
                    successCount = deletePalletDeviceUploadHistoryByIds(successIds.toArray(new Long[0]));
                }

                // 构建失败设备列表
                List<String> failedDeviceCodes = failedUploads.stream()
                        .map(PalletDeviceUploadHistory::getDeviceCode)
                        .collect(Collectors.toList());

                Map<String, Object> result = new HashMap<>();
                result.put("successCount", successCount);
                result.put("failedCount", failedUploads.size());
                result.put("failedDeviceCodes", failedDeviceCodes);

                ajax.put("code", 200);
                ajax.put("msg", "部分数据上传失败，成功 " + successCount + " 条，失败 " + failedUploads.size() + " 条");
                ajax.put("data", result);
                return ajax;
            }

            return AjaxResult.success("数据处理完成");

        } catch (Exception e) {
            ajax.put("code", 200);
            ajax.put("msg", "处理上传数据时发生异常" + e.getMessage());
            return ajax;
        }
    }
    /**
     * 初始化MES数据并上传，返回上传失败的设备列表
     */
    private List<PalletDeviceUploadHistory> initMesDataAndUpload(List<PalletDeviceUploadHistory> palletDeviceUploadHistoryList) {
        List<MesDeviceDomain> mesDeviceDomains = new ArrayList<>();

        for (PalletDeviceUploadHistory palletDeviceBinding : palletDeviceUploadHistoryList) {
            MesDeviceDomain mesDeviceDomain = new MesDeviceDomain();
            if(StringUtils.isBlank(palletDeviceBinding.getDeviceCode())
            || palletDeviceBinding.getCalibrationConcentration()!= null
            || StringUtils.isBlank(palletDeviceBinding.getCalibrationConcentrationStatus())
            || StringUtils.isBlank(palletDeviceBinding.getConcentration())
            || palletDeviceBinding.getRealTimeAd() == null
            || StringUtils.isBlank(palletDeviceBinding.getRealTimeAdStatus())) {
                throw new RuntimeException("数据不完整");
            }
            // 主板码
            mesDeviceDomain.setMotherboardCode(palletDeviceBinding.getDeviceCode());
            // 标定浓度值
            mesDeviceDomain.setCalibrationConcentration(palletDeviceBinding.getCalibrationConcentration());
            // 标定浓度结果
            mesDeviceDomain.setCalibrationConcentrationStatus(palletDeviceBinding.getCalibrationConcentrationStatus());
            // 浓度
            mesDeviceDomain.setConcentration(palletDeviceBinding.getConcentration());
            // 实时AD
            mesDeviceDomain.setRealTimeAd(palletDeviceBinding.getRealTimeAd());
            // 实时状态
            mesDeviceDomain.setRealTimeStatus(palletDeviceBinding.getRealTimeAdStatus());
            mesDeviceDomains.add(mesDeviceDomain);
        }

        String mesUploadAddress = sysConfigService.directSelectConfigByKey(RoboticArmConstans.UPLOAD_MES_ADDRESS);
        if (StringUtils.isBlank(mesUploadAddress)) {
            throw new RuntimeException("MES上传地址未配置");
        }
        try {
            String result = HttpUtils.sendPost(mesUploadAddress, JSON.toJSONString(mesDeviceDomains));
            if (StringUtils.isBlank(result)) {
                throw new RuntimeException("MES接口返回为空");
            }

            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getInteger("code") == 200) {
                // 全部成功，返回空列表
                return new ArrayList<>();
            } else {
                // 部分失败，处理失败的数据
                String data = jsonObject.getString("data");
                if (StringUtils.isNotBlank(data)) {
                    return processPalletDeviceUploadHistory(palletDeviceUploadHistoryList, data);
                } else {
                    JSONObject jsonObject1 = JSON.parseObject(data);
                    throw new RuntimeException("调用MES接口失败: " + jsonObject1.get("msg").toString());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("调用MES接口失败: " + e.getMessage());
        }
    }

    /**
     * 处理托盘设备上传历史数据，返回上传失败的设备列表
     */
    private List<PalletDeviceUploadHistory> processPalletDeviceUploadHistory(List<PalletDeviceUploadHistory> palletDeviceBindings, String data) {
        JSONObject jsonObject = JSON.parseObject(data);

        if (!jsonObject.containsKey("failedCount")) {
            return new ArrayList<>(palletDeviceBindings);
        }

        JSONArray failedCodes = jsonObject.getJSONArray("failedCodes");
        if (failedCodes == null || failedCodes.isEmpty()) {
            return new ArrayList<>();
        }

        // 使用Set提高查找效率
        Set<String> failedCodeSet = failedCodes.stream()
                .map(Object::toString)
                .collect(Collectors.toSet());

        // 返回失败的数据列表
        return palletDeviceBindings.stream()
                .filter(binding -> failedCodeSet.contains(binding.getDeviceCode()))
                .collect(Collectors.toList());
    }

    /**
     * 转换对象 - 修正方法签名（如果需要的话）
     */
    private PalletDeviceUploadHistory convertToUploadHistory(PalletDeviceUploadHistory binding) {
        PalletDeviceUploadHistory history = new PalletDeviceUploadHistory();
        // 正确的参数顺序：源对象在前，目标对象在后
        BeanUtils.copyProperties(binding, history);
        return history;
    }
    /**
     * 修改未上传成功的历史数据列
     * 
     * @param palletDeviceUploadHistory 未上传成功的历史数据列
     * @return 结果
     */
    @Override
    public int updatePalletDeviceUploadHistory(PalletDeviceUploadHistory palletDeviceUploadHistory)
    {
        return palletDeviceUploadHistoryMapper.updatePalletDeviceUploadHistory(palletDeviceUploadHistory);
    }

    /**
     * 批量删除未上传成功的历史数据列
     * 
     * @param ids 需要删除的未上传成功的历史数据列ID
     * @return 结果
     */
    @Override
    public int deletePalletDeviceUploadHistoryByIds(Long[] ids)
    {
        return palletDeviceUploadHistoryMapper.deletePalletDeviceUploadHistoryByIds(ids);
    }

    /**
     * 删除未上传成功的历史数据列信息
     * 
     * @param id 未上传成功的历史数据列ID
     * @return 结果
     */
    @Override
    public int deletePalletDeviceUploadHistoryById(Long id)
    {
        return palletDeviceUploadHistoryMapper.deletePalletDeviceUploadHistoryById(id);
    }
}
