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.entity.IotAepProduct;
import com.sptg.iot.api.entity.IotAuthentication;
import com.sptg.iot.api.entity.IotDevice;
import com.sptg.iot.api.entity.IotSysConf;
import com.sptg.iot.api.util.IotHttpUtil;
import com.sptg.iot.biz.mapper.IotAepProductMapper;
import com.sptg.iot.biz.service.IotAepProductServiceInterface;
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/12/14 18:48
 */
@Service
@RequiredArgsConstructor
public class IotAepProductServiceImpl extends ServiceImpl<IotAepProductMapper, IotAepProduct> implements IotAepProductServiceInterface {

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

    @Override
    public ResultBean<List<IotAepProduct>> getList() {
        Wrapper<IotAepProduct> wrapper = new EntityWrapper<>();
        List<IotAepProduct> list = this.baseMapper.getList(wrapper);
        return new ResultBean<List<IotAepProduct>>(ResultEnum.SUCCESS, list);
    }

    @Override
    public ResultBean<String> syncAepProductList() {
        List<IotSysConf> iotSysConfList = this.iotSysConfServiceInterface.selectList(null);
        List<IotAepProduct> allIotAepProductList = 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){
                List<IotAepProduct> iotAepProductList = new ArrayList<>();
                IotHttpUtil httpUtil = new IotHttpUtil(iotSysConf);
                Map<String, Object> bizParamsMap = new HashMap<>();
                String[] prefixList = iotSysConf.getPrefix().split(",");
                for(int j = 0; j < prefixList.length; j++){
                    String prefix = prefixList[j];
                    String accessToken = iotAuthentication.getAccessToken();
                    ApiResultBean<PageData<IotAepProduct>> apiResultBean = httpUtil.syncAepProductList(bizParamsMap, prefix, accessToken);
                    String reqData = JsonUtils.objectToJson(bizParamsMap);
                    if(apiResultBean.getCode().equals(IotReturnCode.UNAUTHORIZED.getCode())){ //未认证，提示先去认证
                        this.iotApiLogServiceInterface.recordIotApiLog("/device/getProductList", prefix, appId, reqData, apiResultBean);
                        return new ResultBean<>(ResultEnum.FAILURE, IotReturnCode.UNAUTHORIZED.toString());
                    }
                    if(apiResultBean.getCode().equals(OperationConstant.ZERO)){
                        PageData<IotAepProduct> pageData = apiResultBean.getData();
                        List<IotAepProduct> items = pageData.getItems();
                        items.forEach(iotDevice -> {
                            iotDevice.setPrefix(prefix);
                        });
                        if(pageData.getItems() != null){
                            iotAepProductList.addAll(pageData.getItems());
                        }
                        this.iotApiLogServiceInterface.recordIotApiLog("/device/getProductList", prefix, appId, reqData, apiResultBean);
                    }
                }
                allIotAepProductList.addAll(iotAepProductList);
            }
        }
        List<IotAepProduct> updateIotProductList = new ArrayList<>();
        if(allIotAepProductList.size() > 0){
            allIotAepProductList.forEach(source ->{
                IotAepProduct target = this.getIotAepProductByProductId(source.getProductId());
                if(target == null){
                    target = new IotAepProduct();
                }else{
                    source.setId(target.getId());
                }
                BeanUtil.copyProperties(source, target);
                updateIotProductList.add(target);
            });
        }
        if(updateIotProductList.size() > 0){
            boolean result = this.insertOrUpdateBatch(updateIotProductList, 100);
            if(result){
                return new ResultBean<>(ResultEnum.SUCCESS, "AEP产品信息列表同步成功");
            }else{
                return new ResultBean<>(ResultEnum.FAILURE, "AEP产品信息列表同步成功，但保存失败");
            }
        }else{
            return new ResultBean<>(ResultEnum.SUCCESS, "AEP产品信息列表同步成功，但无数据");
        }
    }

    @Override
    public IotAepProduct getIotAepProductByProductId(String productId) {
        Wrapper<IotAepProduct> wrapper = new EntityWrapper<>();
        wrapper.eq("s_product_id", productId);
        return this.baseMapper.getOne(wrapper);
    }
}
