package com.fdkankan.ucenter.service.impl;

import com.amazonaws.services.devopsguru.model.ListInsightsOngoingStatusFilter;
import com.amazonaws.services.simpleworkflow.flow.annotations.NoWait;
import com.fdkankan.common.constant.AppConstant;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.FileSizeUtil;
import com.fdkankan.ucenter.constant.CameraConstant;
import com.fdkankan.ucenter.constant.LoginConstant;
import com.fdkankan.ucenter.entity.*;
import com.fdkankan.ucenter.service.*;
import com.fdkankan.ucenter.vo.response.AppCameraSpace;
import com.fdkankan.ucenter.vo.response.CameraAppVo;
import com.fdkankan.ucenter.vo.response.GroupByCount;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigInteger;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AppCameraService {

    @Autowired
    IUserService userService;
    @Autowired
    ICameraDetailService cameraDetailService;
    @Autowired
    ICameraService cameraService;
    @Autowired
    ISceneProService sceneProService;
    @Autowired
    IScenePlusService scenePlusService;
    @Autowired
    IScenePlusExtService scenePlusExtService;
    @Autowired
    IUserIncrementService userIncrementService;
    @Autowired
    IIncrementTypeService incrementTypeService;
    @Autowired
    ICameraIncrementLogService cameraIncrementLogService;


    public List<CameraAppVo> getCameraForUser(String userName, Integer cameraType) {
        if(StringUtils.isEmpty(userName) || cameraType == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        User user = userService.getByUserName(userName);
        if(user == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3015, LoginConstant.FAILURE_MSG_3015);
        }
        List<CameraAppVo> cameraAppVoList = cameraDetailService.getListByUserAndType(user.getId(), cameraType);
        setIncrementInfo(cameraAppVoList,null);
        return cameraAppVoList;
    }

    private void setIncrementInfo(List<CameraAppVo> cameraAppVoList, HashMap<Long, GroupByCount> sceneNumMap){
        for (CameraAppVo cameraApp : cameraAppVoList) {
            if(sceneNumMap != null){
                Long sceneCount = sceneNumMap.get(cameraApp.getId()) == null ? 0L : sceneNumMap.get(cameraApp.getId()).getCount();
                cameraApp.setSceneCount(Math.toIntExact(sceneCount));
            }
            UserIncrement userIncrementEntity = userIncrementService.getByCameraId(cameraApp.getCameraId());
            if(userIncrementEntity != null){
                cameraApp.setMemberLevels(userIncrementEntity.getMemberLevels());
                cameraApp.setUserIncrementId(userIncrementEntity.getId());
                cameraApp.setIsExpire(userIncrementEntity.getIsExpired());
                IncrementType incrementType = incrementTypeService.getById(userIncrementEntity.getIncrementTypeId());
                if(incrementType == null || userIncrementEntity.getIsExpired() == 1){
                    continue;
                }
                if("GB".equals(cameraApp.getUnit())){
                    cameraApp.setTotalSpace( BigInteger.valueOf(incrementType.getCameraCapacity() * 1024L *1024L*1024L));
                }
                if("SP".equals(cameraApp.getUnit())){
                    cameraApp.setTotalSpace(BigInteger.valueOf(incrementType.getCameraSpace()));
                }
            }
        }
    }

    public CameraAppVo bindCamera(String userName, String snCode) {
        User user = userService.getByUserName(userName);
        if(user == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4007, AppConstant.FAILURE_MSG_4007);
        }
        Camera camera = null;
        if(snCode.contains("_")){
            camera = cameraService.getByWfiName(snCode);
        }else {
            camera = cameraService.getBySnCode(snCode);
        }
        if(camera == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        CameraDetail cameraDetail = cameraDetailService.getByCameraId(camera.getId());
        if(cameraDetail == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        if (cameraDetail.getUserId() != null){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6006, CameraConstant.FAILURE_MSG_6006);
        }
        List<Long> cameraIds = Collections.singletonList(camera.getId());

        cameraDetail.setUserId(user.getId());
        cameraIncrementLogService.saveLog(camera.getId(),null,user.getId(),2);

        cameraDetailService.bindCamera(cameraIds,user);
        sceneProService.bindOrUnCamera(cameraIds,user.getId());
        scenePlusService.bindOrUnCamera(cameraIds,user.getId());
        CameraAppVo responseCamera = new CameraAppVo();
        responseCamera.setChildName(camera.getChildName());
        responseCamera.setUnit(cameraDetail.getUnit());
        responseCamera.setUsedSpace(BigInteger.valueOf(cameraDetail.getUsedSpace()));
        responseCamera.setTotalSpace(BigInteger.valueOf(cameraDetail.getTotalSpace()));
        if("GB".equals(cameraDetail.getUnit())){
            responseCamera.setUsedSpaceStr(FileSizeUtil.formatFileSize(cameraDetail.getUsedSpace()));
            responseCamera.setTotalSpaceStr(FileSizeUtil.formatFileSize(cameraDetail.getTotalSpace()));
        }
        if("SP".equals(cameraDetail.getUnit())){
            responseCamera.setUsedSpaceStr(String.valueOf(cameraDetail.getUsedSpace()));
            responseCamera.setTotalSpaceStr(String.valueOf(cameraDetail.getTotalSpace()));
        }
        return responseCamera;
    }

    public void unbindCamera(String userName, String childName) {
        User user = userService.getByUserName(userName);
        if(user == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4007, AppConstant.FAILURE_MSG_4007);
        }
        Camera camera = cameraService.getByChildName(childName);
        if(camera == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        CameraDetail cameraDetail = cameraDetailService.getByCameraId(camera.getId());
        if(cameraDetail == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        if(!user.getId().equals(cameraDetail.getUserId())){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6005, CameraConstant.FAILURE_MSG_6005);
        }
        List<Long> cameraIds = Collections.singletonList(camera.getId());

        UserIncrement userIncrement = userIncrementService.getByCameraId(camera.getId());
        if(userIncrement != null){
            cameraIncrementLogService.saveLog(camera.getId(),userIncrement.getId(),user.getId(),1);
        }
        cameraIncrementLogService.saveLog(camera.getId(),null,user.getId(),3);

        userIncrementService.unbindCamera(cameraIds);                   //取消关联用户权益
        cameraDetailService.unbindCamera(cameraIds);                     //取消相机用户关联
        sceneProService.bindOrUnCamera(cameraIds,null);             //取消关联场景
        scenePlusService.bindOrUnCamera(cameraIds,null);            //取消关联场景
    }

    public CameraAppVo getCameraInfo(String childName, String childPassword) {
        if(StringUtils.isEmpty(childName) || StringUtils.isEmpty(childPassword)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        List<CameraAppVo> cameraAppVos = cameraService.getCameraInfo(childName,childPassword);
        if(cameraAppVos.size()<=0){
            return null;
        }
        List<Long> cameraIdList = cameraAppVos.parallelStream().map(CameraAppVo::getId).collect(Collectors.toList());
        //场景数量,最后拍摄时间
        HashMap<Long, GroupByCount> sceneNumMap =  sceneProService.findSceneNumByCameraIds(cameraIdList);

        setIncrementInfo(cameraAppVos,sceneNumMap);
        return cameraAppVos.get(0);
    }

    public void uploadUserCameraInfo(String snCode, String cameraVersion, String appVersion) {
        Camera cameraEntity = cameraService.getBySnCode(snCode);
        if(ObjectUtils.isEmpty(cameraEntity)){
            return;
        }
        cameraDetailService.uploadUserCameraInfo(cameraEntity.getId(),cameraVersion,appVersion);
    }


    public AppCameraSpace checkCameraSpace(String snCode,String unicode) {
        Camera camera = cameraService.getBySnCode(snCode);
        if(camera == null){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6029, CameraConstant.FAILURE_MSG_6029);
        }
        CameraDetail cameraDetail = cameraDetailService.getByCameraId(camera.getId());
        if(cameraDetail == null){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6029, CameraConstant.FAILURE_MSG_6029);
        }
        Long sapce = cameraDetail.getUsedSpace();
        if("SP".equals(cameraDetail.getUnit())){
            Long proCount = sceneProService.getCountByCameraId(cameraDetail.getCameraId(),true);
            Long pulsCount = scenePlusService.getCountByCameraId(cameraDetail.getCameraId(), true);
            sapce = proCount + pulsCount;
            if(StringUtils.isNotBlank(unicode)){
                ScenePro scenePro = sceneProService.getByUnicode(unicode);
                ScenePlusExt scenePlusExt = scenePlusExtService.getByUnicode(unicode);
                if(scenePro != null || scenePlusExt !=null){
                    if(scenePro!= null && scenePro.getStatus() != null &&  scenePro.getStatus() !=-1 &&  scenePro.getPayStatus() != null &&  scenePro.getPayStatus() !=1){
                        return new AppCameraSpace(0L,cameraDetail.getUnit());
                    }
                    if(scenePlusExt!= null ){
                        ScenePlus scenePlus = scenePlusService.getById(scenePlusExt.getPlusId());
                        if(scenePlus != null && scenePlus.getSceneStatus() != null  && scenePlus.getSceneStatus() !=-1 && scenePlus.getPayStatus() != null && scenePlus.getPayStatus() != 1){
                            return new AppCameraSpace(0L,cameraDetail.getUnit());
                        }
                    }
                    return new AppCameraSpace(1L,cameraDetail.getUnit());
                }
            }
        }
        Long totalSpace = cameraDetailService.getTotalSpaceByCameraId(cameraDetail);
        if(totalSpace != -1){
            totalSpace = totalSpace - sapce;
            totalSpace = totalSpace < 0 ? 0L : totalSpace;
        }
        return new AppCameraSpace(totalSpace,cameraDetail.getUnit());
    }
}
