package com.mortals.xhx.protocol.complex;


import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ICacheService;
import com.mortals.xhx.protocol.complex.matter.model.req.DeviceLoginReq;
import com.mortals.xhx.protocol.complex.matter.model.rsp.LoginRspInfo;
import com.mortals.xhx.protocol.complex.matter.service.IComplexMatterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;

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


@Slf4j
public abstract class AbstractComplexService implements IComplexMatterService {

    //综窗访问地址
    @Value("${complex.host:}")
    protected String host;

    //综窗设备编码 多个逗号分割
    @Value("${complex.deviceCode:''}")
    protected String deviceCode;

    //综窗接件token  deviceCode--对应tokenMap
    public static Map<String, String> tokenMap=new HashMap<>();

    public static String DEVICE_LOGO_TOKEN = "device:logo:token";
    /***/
    public static Long TOKEN_TIMEOUT = 3600l;

    @Autowired
    private ICacheService iCacheService;

    @Override
    public String getToken(String deviceLogo) {
        try {

            String deviceToken = iCacheService.get(DEVICE_LOGO_TOKEN);
            if (ObjectUtils.isEmpty(deviceToken)) {
                DeviceLoginReq loginReq = new DeviceLoginReq();
                loginReq.setDeviceLogo(deviceLogo);
                Rest<LoginRspInfo> loginRspInfoRest = this.deviceLogin(loginReq);
                return loginRspInfoRest.getData().getToken();
            } else {
                return deviceToken;
            }
        } catch (Exception e) {
            log.error("获取TOKEN异常", e);
            throw new AppException(e.getMessage());
        }
    }

    @Override
    public void setToken(String token){
        iCacheService.set(DEVICE_LOGO_TOKEN,token,TOKEN_TIMEOUT);
    }

}
