package com.sptg.iot.biz.controller;

import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.iot.api.beans.ApiResultBean;
import com.sptg.iot.api.beans.IotReturnCode;
import com.sptg.iot.api.entity.IotAuthentication;
import com.sptg.iot.api.entity.IotSubscribe;
import com.sptg.iot.api.entity.IotSysConf;
import com.sptg.iot.api.feigns.IotSubscribeFeign;
import com.sptg.iot.api.util.IotHttpUtil;
import com.sptg.iot.biz.service.IotApiLogServiceInterface;
import com.sptg.iot.biz.service.IotAuthServiceInterface;
import com.sptg.iot.biz.service.IotSysConfServiceInterface;
import feign.hystrix.FallbackFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zwx
 * @create 2020/11/5 14:29
 */

@Slf4j
@RestController
@RequiredArgsConstructor
public class IotISubscribeController implements IotSubscribeFeign {

    private final IotSysConfServiceInterface iotSysConfServiceInterface;
    private final IotAuthServiceInterface iotAuthServiceInterface;
    private final IotApiLogServiceInterface iotApiLogServiceInterface;

    @PostMapping(value = "/iot/subscribe")
    public ResultBean<String> subscribe(@RequestBody IotSubscribe iotSubscribe){
        List<IotSysConf> iotSysConfList = iotSysConfServiceInterface.selectList(null);
        int flag = 0;
        for(int i = 0; i < iotSysConfList.size(); i++){
            IotSysConf iotSysConf = iotSysConfList.get(i);
            IotHttpUtil httpUtil = new IotHttpUtil(iotSysConf);
            String heartbeat_url = iotSubscribe.getHeartbeat_url();
            String alarm_url = iotSubscribe.getAlarm_url();
            String device_status_url = iotSubscribe.getDevice_status_url();
            Map<String, Object> bizParamsMap = new HashMap<>();
            bizParamsMap.put("heartbeat_url", heartbeat_url);
            bizParamsMap.put("alarm_url", alarm_url);
            bizParamsMap.put("device_status_url", device_status_url);
            String[] prefixList = iotSysConf.getPrefix().split(",");
            String appId = iotSysConf.getAppId();
            IotAuthentication iotAuthentication = this.iotAuthServiceInterface.findByAppId(appId);
            for(int j = 0; j < prefixList.length; j++){
                String prefix = prefixList[j];
                ApiResultBean<Object> apiResultBean = httpUtil.subscribe(bizParamsMap, prefix, iotAuthentication.getAccessToken());
                if(apiResultBean.getCode().equals(IotReturnCode.UNAUTHORIZED.getCode())){ //未认证，提示先去认证
                    return new ResultBean<>(ResultEnum.FAILURE, IotReturnCode.UNAUTHORIZED.toString());
                }
                String reqData = JsonUtils.objectToJson(bizParamsMap);
                this.iotApiLogServiceInterface.recordIotApiLog("/setting/subscribe", prefix, appId, reqData, apiResultBean);
                if(apiResultBean.getCode().equals(OperationConstant.ZERO)){
                    flag++;
                }
            }
        }
        if(flag == iotSysConfList.size()){
            return new ResultBean<>(ResultEnum.SUCCESS, "订阅成功");
        }else{
            return new ResultBean<>(ResultEnum.SUCCESS, "部分订阅成功，请查看日志");
        }
    }

    /**
     * 查询已订阅的接口
     * @param iotSubscribe
     * @return
     */
    @PostMapping(value = "/iot/inquire")
    public ResultBean<String> inquire(@RequestBody IotSubscribe iotSubscribe){
        String appId = iotSubscribe.getAppId();
        IotSysConf iotSysConf = this.iotSysConfServiceInterface.findSysConfByAppId(iotSubscribe.getAppId());
        IotHttpUtil httpUtil = new IotHttpUtil(iotSysConf);
        IotAuthentication iotAuthentication = this.iotAuthServiceInterface.findByAppId(appId);
        String accessToken = iotAuthentication.getAccessToken();
        Map<String, Object> bizParamsMap = new HashMap<>();
        String[] prefixList = iotSysConf.getPrefix().split(",");
        int flag = 0;
        for(int i = 0; i < prefixList.length; i++){
            String prefix  = prefixList[i];
            ApiResultBean<Object> apiResultBean = httpUtil.inquireSubscribe(bizParamsMap, prefix, accessToken);
            String reqData = JsonUtils.objectToJson(bizParamsMap);
            this.iotApiLogServiceInterface.recordIotApiLog("/setting/inquire", prefix, appId, reqData, apiResultBean);
            if(apiResultBean.getCode().equals(IotReturnCode.UNAUTHORIZED.getCode())){ //未认证，提示先去认证
                return new ResultBean<>(ResultEnum.FAILURE, IotReturnCode.UNAUTHORIZED.toString());
            }
            if(!apiResultBean.getCode().equals(OperationConstant.ZERO)){
                return new ResultBean<>(ResultEnum.FAILURE, apiResultBean.getMsg());
            }
            if(apiResultBean.getCode().equals(OperationConstant.ZERO)){
                flag++;
            }
        }
        if(flag == prefixList.length){
            return new ResultBean<>(ResultEnum.SUCCESS, "全部组件订阅查询成功");
        }else{
            return new ResultBean<>(ResultEnum.SUCCESS, "部分组件尚无订阅信息");
        }
    }
}
