package com.zehong.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zehong.common.constant.RoboticArmConstans;
import com.zehong.common.core.redis.RedisCache;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.http.HttpUtils;
import com.zehong.system.domain.ProductStandardInspection;
import com.zehong.system.mapper.ProductStandardInspectionMapper;
import com.zehong.system.service.IProductStandardInspectionService;
import com.zehong.system.service.ISysConfigService;
import io.netty.handler.codec.http.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 产品主体标检单Service业务层处理
 *
 * @author zehong
 * @date 2026-01-17
 */
@Service
public class ProductStandardInspectionServiceImpl implements IProductStandardInspectionService
{
    public static final Logger logger = LoggerFactory.getLogger(ProductStandardInspectionServiceImpl.class);
    @Resource
    private ProductStandardInspectionMapper productStandardInspectionMapper;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private RedisCache redisCache;



    /**
     * 查询产品主体标检单
     *
     * @param productStandardInspectionId 产品主体标检单ID
     * @return 产品主体标检单
     */
    @Override
    public ProductStandardInspection selectProductStandardInspectionById(Long productStandardInspectionId)
    {
        return productStandardInspectionMapper.selectProductStandardInspectionById(productStandardInspectionId);
    }

    /**
     * 查询产品主体标检单列表
     *
     * @param productStandardInspection 产品主体标检单
     * @return 产品主体标检单
     */
    @Override
    public List<ProductStandardInspection> selectProductStandardInspectionList(ProductStandardInspection productStandardInspection)
    {
        return productStandardInspectionMapper.selectProductStandardInspectionList(productStandardInspection);
    }

    /**
     * 同步MES数据
     */
    @Override
    public void syncMESData() {

        String standardInspectionAddress = sysConfigService.directSelectConfigByKey(RoboticArmConstans.STANDARD_INSPECTION_ADDRESS);
        if (StringUtils.isBlank(standardInspectionAddress)) {
            throw new RuntimeException("MES地址未配置");
        }

        // 2. 获取token
        String token = getMESToken();
        if (StringUtils.isBlank(token)) {
            throw new RuntimeException("MES token未获取");
        }

        // 3. 构造请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + token);
        headers.put("Content-Type", "application/json");

        // 4. 调用MES接口
        String result = HttpUtils.get(standardInspectionAddress, headers, null);

        if (StringUtils.isNotBlank(result)) {
            // 5. 处理返回的数据
            processMESData(result);
            logger.info("MES数据同步成功");
        } else {
            throw new RuntimeException("MES接口调用失败");
        }
    }
    /**
     * 获取MES token
     */
    private String getMESToken() {
        // 1. 先从Redis中获取token
        Object tokenObj = redisCache.getCacheObject(RoboticArmConstans.MES_TOKEN);
        if (tokenObj != null) {
            String token = tokenObj.toString();
            // 检查token是否即将过期（提前5分钟刷新）
            long expireTime = redisCache.getExpire(RoboticArmConstans.MES_TOKEN, TimeUnit.MINUTES);
            if (expireTime > 1) { // 大于1分钟，直接返回
                return token;
            }
        }

        // 2. 如果Redis中没有或即将过期，重新获取token
        return refreshMESToken();
    }
    /**
     * 刷新MES token
     */
    private String refreshMESToken() {
        try {
            // 1. 获取登录配置信息
            String loginUrl = sysConfigService.directSelectConfigByKey(RoboticArmConstans.MES_LOGIN_URL);
            String username = sysConfigService.directSelectConfigByKey(RoboticArmConstans.MES_USERNAME);
            String password = sysConfigService.directSelectConfigByKey(RoboticArmConstans.MES_PASSWORD);

            if (StringUtils.isAnyBlank(loginUrl, username, password)) {
                throw new RuntimeException("MES登录配置信息不完整");
            }

            // 2. 构造登录参数
            Map<String, String> loginParams = new HashMap<>();
            loginParams.put("username", username);
            loginParams.put("password", password);

            // 3. 调用登录接口
            String response = HttpUtils.sendPost(loginUrl, JSON.toJSONString(loginParams));

            if (StringUtils.isNotBlank(response)) {
                // 4. 解析返回的token（根据实际接口返回格式调整）
                String token = parseTokenFromResponse(response);

                if (StringUtils.isNotBlank(token)) {
                    // 5. 将token存储到Redis，设置过期时间
                    redisCache.setCacheObject(RoboticArmConstans.MES_TOKEN, token, 300, TimeUnit.MINUTES); // 5分钟
                    return token;
                }
            }

            throw new RuntimeException("获取MES token失败");

        } catch (Exception e) {
            throw new RuntimeException("刷新MES token异常", e);
        }
    }
    /**
     * 从响应中解析token（根据实际接口返回格式调整）
     */
    private String parseTokenFromResponse(String response) {
        try {
            // 假设返回格式为：{"code": 200, "data": "abacadfsasd", "msg": "success"}
            JSONObject jsonObject = JSON.parseObject(response);
            if (jsonObject != null && jsonObject.getInteger("code") == 200) {
                String token = jsonObject.getString("data");
                if(StringUtils.isNotBlank(token)) {
                    return token;
                } else {
                    throw new RuntimeException("获取MES token失败");
                }
            }
        } catch (Exception e) {
            logger.error("解析token失败，响应内容：{}", response, e);
        }
        return null;
    }

    /**
     * 处理MES返回的数据
     */
    private void processMESData(String data) {
        // 根据实际业务需求处理数据
        // 这里只是示例，具体实现根据您的业务逻辑
        try {
            JSONObject jsonData = JSON.parseObject(data);
            // 处理数据逻辑...
            logger.debug("接收到MES数据：{}", jsonData);
        } catch (Exception e) {
            logger.error("处理MES数据异常：", e);
        }
    }

    /**
     * 新增产品主体标检单
     *
     * @param productStandardInspection 产品主体标检单
     * @return 结果
     */
    @Override
    public int insertProductStandardInspection(ProductStandardInspection productStandardInspection)
    {
        productStandardInspection.setCreateTime(DateUtils.getNowDate());
        return productStandardInspectionMapper.insertProductStandardInspection(productStandardInspection);
    }

    /**
     * 修改产品主体标检单
     *
     * @param productStandardInspection 产品主体标检单
     * @return 结果
     */
    @Override
    public int updateProductStandardInspection(ProductStandardInspection productStandardInspection)
    {
        return productStandardInspectionMapper.updateProductStandardInspection(productStandardInspection);
    }

    /**
     * 批量删除产品主体标检单
     *
     * @param productStandardInspectionIds 需要删除的产品主体标检单ID
     * @return 结果
     */
    @Override
    public int deleteProductStandardInspectionByIds(Long[] productStandardInspectionIds)
    {
        return productStandardInspectionMapper.deleteProductStandardInspectionByIds(productStandardInspectionIds);
    }

    /**
     * 删除产品主体标检单信息
     *
     * @param productStandardInspectionId 产品主体标检单ID
     * @return 结果
     */
    @Override
    public int deleteProductStandardInspectionById(Long productStandardInspectionId)
    {
        return productStandardInspectionMapper.deleteProductStandardInspectionById(productStandardInspectionId);
    }
}
