package com.yuchen.saas.park.service.service.security.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.thinkunion.sdk.iot.IoTClient;
import com.thinkunion.sdk.iot.bean.api.CallingDeviceServiceRequest;
import com.thinkunion.sdk.iot.bean.api.CallingDeviceServiceResponse;
import com.yuchen.saas.park.api.entity.security.SaasParkElectronicFence;
import com.yuchen.saas.park.service.service.security.ISaasParkElectronicFenceCallService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 洪铭铭
 * @time: 2024/9/11 9:40
 */
@Service
@Slf4j
public class SaasParkElectronicFenceCallServiceImpl implements ISaasParkElectronicFenceCallService {

    @Resource
    private IoTClient ioTClient;


    public static final String DEVICE_ACTION = "deviceAction";

    public static final String CHANNEL_ACTION = "channelAction";

    /**
     * @description: 设备操作
     * @param fence
     * @param action
     * @return: com.thinkunion.sdk.iot.bean.api.CallingDeviceServiceResponse
     * @author: 洪铭铭
     * @time: 2024/9/11 14:16
     */
    @Override
    public CallingDeviceServiceResponse deviceAction(SaasParkElectronicFence fence, String action) {

        Map<String, Object> request = prepareRequest(fence, DEVICE_ACTION, action);
        //request.setIdentify(DEVICE_ACTION);
        return this.callService(request);
    }

    /**
     * @description: 设备操作
     * @param fence
     * @param action
     * @return: com.thinkunion.sdk.iot.bean.api.CallingDeviceServiceResponse
     * @author: 洪铭铭
     * @time: 2024/9/11 14:16
     */
    public CallingDeviceServiceResponse channelAction(SaasParkElectronicFence fence,  String action) {
        Map<String, Object> request = prepareRequest(fence, CHANNEL_ACTION, action);
        //request.setIdentify(CHANNEL_ACTION);
        return this.callService(request);
    }

    /**
     * @description: 组装参数
     * @param fence
     * @param action
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @author: 洪铭铭
     * @time: 2024/9/11 14:17
     */
    public Map<String,Object> prepareRequest(SaasParkElectronicFence fence, String type, String action){
        Map<String,Object> paramMap = new HashMap<String,Object>(4);
        paramMap.put("productKey",fence.getProductKey());
        paramMap.put("deviceName",fence.getDeviceName());
        Map<String,Object> dataParam = new HashMap<String,Object>(8);
        Map<String,Object> dataMap = new HashMap<String,Object>();
        if(type.equals(DEVICE_ACTION)){
            paramMap.put("identify", DEVICE_ACTION);
            dataParam.put("deviceId",fence.getDeviceId());
            dataParam.put("actionType",action);
        } else {
            paramMap.put("identify", CHANNEL_ACTION);
            dataParam.put("deviceId",fence.getDeviceId());
            dataParam.put("channel",0);
            dataParam.put("chanAction",action);
        }
        paramMap.put("params",dataParam);
        return paramMap;
    }
    
    /**
     * @description: 调用iot
     * @param params
     * @return: com.thinkunion.sdk.iot.bean.api.CallingDeviceServiceResponse
     * @author: 洪铭铭
     * @time: 2024/9/11 14:23
     */
    public CallingDeviceServiceResponse callService(Map<String, Object> params) {
        try{
            CallingDeviceServiceRequest request = new CallingDeviceServiceRequest();
            request.setProductKey(params.get("productKey").toString());
            request.setDeviceName(params.get("deviceName").toString());
            request.setIdentifier(params.get("identify").toString());
            Map<String,Object> paramMap = (Map<String, Object>) params.get("params");
            JSONObject paramsObject = JSON.parseObject(JSON.toJSONString(params.get("params")));
            log.info("before send iot servce data==="+paramsObject.toJSONString());
            paramsObject.forEach((key, obj) -> {
                if (obj instanceof JSON) {
                    JSON json = (JSON) obj;
                    request.addParam(key, json.toJSONString());
                } else {
                    request.addParam(key, obj.toString());
                }
            });
            CallingDeviceServiceResponse response = this.ioTClient.send(request);
            log.info("after send iot servce data==="+JSONObject.toJSONString(response));
            return response;
        }catch ( Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//    @Override
//    public IotCommonResult<ResponseHolder> call(IotCommonRequest commonsParameter,CommandParameter commandParameter)  {
//        log.info("======调用iot原始传参 {}:\n{}\n{}\n{}", commonsParameter.getIdentify(), commonsParameter.getProductKey(),commonsParameter.getDeviceName(),commonsParameter);
//
//        try {
//            CallingDeviceServiceRequest request = this.prepareRequest(commonsParameter, commandParameter);
//
//            log.info("====== 调用iot传参：{}", JSON.toJSONString(request));
//
//            CallingDeviceServiceResponse response = ioTClient.send(request);
//
//            log.info("====== 调用iot返回结果：{}",JSON.toJSONString(response));
//
//            return this.handleResponse(response);
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//
//            return IotCommonResult.error(e.getMessage());
//        }
//    }
//    private CallingDeviceServiceRequest prepareRequest(IotCommonRequest commonsParameter, CommandParameter commandParameter) {
//        CallingDeviceServiceRequest request = new CallingDeviceServiceRequest();
//        request.setProductKey(commonsParameter.getProductKey());
//        request.setDeviceName(commonsParameter.getDeviceName());
//        request.setIdentifier(commonsParameter.getIdentify());
//
//        Map< String, Object> map = commandParameter.encoding();
//
//        log.debug("====== 参数:\n{}", JSON.toJSONString(map));
//
//        map.forEach((k, v) -> request.addParam(k, isJavaLang(v) ? v.toString() : JSON.toJSONString(v)));
//        return request;
//    }
//
//    private IotCommonResult<ResponseHolder> handleResponse(CallingDeviceServiceResponse response) {
//        log.debug("=== 原始响应: {} ===", response);
//
//        if (!(String.valueOf(HttpStatus.SC_OK)).equals(response.getCode())) {
//            return IotCommonResult.error(response.getMessage());
//        }
//        ResponseHolder holder = JSONObject.parseObject(JSON.toJSONString(response.getData()), ResponseHolder.class);
//        log.debug("=== 响应: {} ===", holder);
//
//        Map<String,Object> details  = holder.getData();
//        if (!"0".equals(holder.getCode())) {
//            log.warn("=== 调用失败: {} ===", details);
//            return IotCommonResult.error(holder.getMessage());
//        }
//
//        log.info("=== 调用成功 ===");
//
//        return IotCommonResult.successful(holder);
//    }

    private static boolean isJavaLang(Object o) {
        return o.getClass().getName().startsWith("java.lang");
    }
}
