package com.fdkankan.modeling.feign;

import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.modeling.entity.ScenePro;
import com.fdkankan.modeling.entity.SceneProExt;
import com.fdkankan.modeling.service.ISceneProExtService;
import com.fdkankan.modeling.service.ISceneProService;
import com.fdkankan.platform.api.feign.PlatformClient;
import com.fdkankan.platform.api.vo.CameraDetail;
import com.fdkankan.platform.api.vo.User;
import com.fdkankan.platform.api.vo.UserIncrement;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserFeign {

    @Resource
    private PlatformClient platformClient;
    @Autowired
    private ISceneProService sceneProService;
    @Autowired
    private ISceneProExtService sceneProExtService;

    public User findByUserName(String userName) {
        ResultData resultData  = platformClient.getUserByName(userName);
        if(resultData.getCode() != 200 && resultData.getData()==null){
            return null;
        }
        Object userData = resultData.getData();
        return JSONObject.parseObject(JSONObject.toJSONString(userData), User.class);
    }

    public int updateUserUsedSpaceBySceneNum(Long userId, String projectNum) {
        ScenePro sceneProEntity = sceneProService.findBySceneNum(projectNum);
        if(sceneProEntity == null) {
            log.info("该场景不存在无法扣除容量，场景码为：" + projectNum);
            return -1;
        }
        SceneProExt sceneProExt = sceneProExtService.getBySceneProId(sceneProEntity.getId());
        ResultData resultData = platformClient.updateCameraDetailByCameraIdAndSpace(sceneProEntity.getCameraId(), sceneProExt.getSpace());
        if(resultData.getCode() != 200){
            log.info("调用platform服务updateCameraDetailByCameraIdAndSpace失败，参数{},{}" ,sceneProEntity.getCameraId(), sceneProExt.getSpace());
            return -1;
        }
        CameraDetail detailEntity = JSONObject.parseObject(JSONObject.toJSONString(resultData.getData()), CameraDetail.class);

        UserIncrement byCameraId = platformClient.getUserIncrementByCameraId(sceneProEntity.getCameraId());
        if(byCameraId == null || byCameraId.getIsExpired().intValue() == 1){
            // 新上传的场景，如果总容量小于使用容量，则该大场景保留在临时存储空间30天
            if (detailEntity.getTotalSpace().compareTo(detailEntity.getUsedSpace()) == -1){
                List<Long> ids = new ArrayList<>();
                ids.add(sceneProEntity.getId());
                sceneProService.tempScenes(ids);
            }
        }
        return 0;
    }
}
