package com.sptg.iot.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
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.beans.PageData;
import com.sptg.iot.api.dto.IotAlarmThresholdDto;
import com.sptg.iot.api.entity.*;
import com.sptg.iot.api.util.IotHttpUtil;
import com.sptg.iot.biz.mapper.IotAlarmThresholdMapper;
import com.sptg.iot.biz.service.IotAlarmThresholdServiceInterface;
import com.sptg.iot.biz.service.IotApiLogServiceInterface;
import com.sptg.iot.biz.service.IotAuthServiceInterface;
import com.sptg.iot.biz.service.IotSysConfServiceInterface;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author zwx
 * @create 2020/10/19 23:21
 * 告警阈值 服务层实现层
 */
@Service
@RequiredArgsConstructor
public class IotAlarmThresholdServiceImpl extends ServiceImpl<IotAlarmThresholdMapper, IotAlarmThreshold> implements IotAlarmThresholdServiceInterface {

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

    @Override
    public ResultBean<String> syncIotAlarmThresholdList(IotAlarmThresholdDto iotAlarmThresholdDto) {
        List<IotSysConf> iotSysConfList = this.iotSysConfServiceInterface.selectList(null);
        List<IotAlarmThreshold> allIotAlarmThresholdList = new ArrayList<>();
        for(int i = 0; i < iotSysConfList.size(); i++){
            IotSysConf iotSysConf = iotSysConfList.get(i);
            String appId = iotSysConf.getAppId();
            IotAuthentication iotAuthentication = this.iotAuthServiceInterface.findByAppId(appId);
            if(iotAuthentication != null){
                IotHttpUtil httpUtil = new IotHttpUtil(iotSysConf);
                List<IotAlarmThreshold> iotAlarmThresholdList = new ArrayList<>();
                Map<String, Object> bizParamsMap = BeanUtil.beanToMap(iotAlarmThresholdDto);
                String[] prefixList = iotSysConf.getPrefix().split(",");
                for(int j = 0; j < prefixList.length; j++){
                    String prefix = prefixList[j];
                    String accessToken = iotAuthentication.getAccessToken();
                    ApiResultBean<PageData<IotAlarmThreshold>> apiResultBean = httpUtil.syncAlarmThresholdList(bizParamsMap, prefix, accessToken);
                    if(apiResultBean.getCode().equals(IotReturnCode.UNAUTHORIZED.getCode())){ //未认证，提示先去认证
                        return new ResultBean<>(ResultEnum.FAILURE, IotReturnCode.UNAUTHORIZED.toString());
                    }
                    if(apiResultBean.getCode().equals(OperationConstant.ZERO)){
                        PageData<IotAlarmThreshold> pageData = apiResultBean.getData();
                        List<IotAlarmThreshold> items = pageData.getItems();
                        items.forEach(iotAlarmThreshold -> {
                            iotAlarmThreshold.setLastSyncDate(new Date());
                            iotAlarmThreshold.setAppId(appId);
                            iotAlarmThreshold.setPrefix(prefix);
                        });
                        iotAlarmThresholdList.addAll(pageData.getItems());
                        String reqData = JsonUtils.objectToJson(bizParamsMap);
                        this.iotApiLogServiceInterface.recordIotApiLog("/alarm/thresholdList", prefix, appId, reqData, apiResultBean);
                    }
                }
                allIotAlarmThresholdList.addAll(iotAlarmThresholdList); //将改应用ID下的所有设备记录下来
            }
        }
        List<IotAlarmThreshold> updateIotAlarmThresholdList = new ArrayList<>();
        if(allIotAlarmThresholdList.size() > 0){
            allIotAlarmThresholdList.forEach(source ->{
                IotAlarmThreshold target = this.getIotAlarmThreshold(source.getThreshold_id());
                if(target == null){
                    target = new IotAlarmThreshold();
                }else{
                    source.setId(target.getId());
                }
                BeanUtil.copyProperties(source, target);
                updateIotAlarmThresholdList.add(target);
            });
        }
        boolean result = this.insertOrUpdateBatch(updateIotAlarmThresholdList);
        if(result){
            return new ResultBean<>(ResultEnum.SUCCESS, "同步成功");
        }else{
            return new ResultBean<>(ResultEnum.FAILURE, "同步成功，但保存失败");
        }
    }

    @Override
    public IotAlarmThreshold getIotAlarmThreshold(String thresholdId) {
        Wrapper<IotAlarmThreshold> wrapper = new EntityWrapper<>();
        wrapper.eq("s_threshold_id", thresholdId);
        return this.selectOne(wrapper);
    }
}
