package com.fdkankan.platform.goods.service.impl;

import com.fdkankan.common.constant.AppConstant;
import com.fdkankan.common.constant.CameraConstant;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.ServerCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.FileSizeUtil;
import com.fdkankan.platform.goods.entity.Camera;
import com.fdkankan.platform.goods.entity.CameraDetail;
import com.fdkankan.platform.goods.entity.Goods;
import com.fdkankan.platform.goods.service.ICameraDetailService;
import com.fdkankan.platform.goods.service.ICameraService;
import com.fdkankan.platform.goods.service.IDeviceService;
import com.fdkankan.platform.goods.service.IGoodsService;
import com.fdkankan.platform.goods.vo.ResponseCameraApp;
import com.fdkankan.platform.user.entity.User;
import com.fdkankan.platform.user.entity.UserIncrement;
import com.fdkankan.platform.user.request.RequestCamera;
import com.fdkankan.platform.user.service.IUserIncrementService;
import com.fdkankan.platform.user.service.IUserService;
import com.fdkankan.platform.user.vo.ResponseCamera;
import com.fdkankan.scene.api.feign.SceneUserSceneClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("deviceService")
@Transactional
public class DeviceServiceImpl implements IDeviceService {

    @Autowired
    private IUserService userService;
    @Autowired
    private ICameraDetailService cameraDetailService;
    @Autowired
    private ICameraService cameraService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IUserIncrementService userIncrementService;
    @Autowired
    private SceneUserSceneClient sceneUserSceneClient;


    @Override
    public ResponseCameraApp getCameraInfo(RequestCamera param) {
        if(StringUtils.isEmpty(param.getChildName()) || StringUtils.isEmpty(param.getChildPassword())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        ResponseCameraApp cameraEntity = this.getCameraInfo(param.getChildName(), param.getChildPassword());
        if(cameraEntity.getUserId() != null){
            User user = userService.getById(cameraEntity.getUserId());
            if (user == null){
                throw new BusinessException(ErrorCode.USER_NOT_EXIST);
            }
            cameraEntity.setUserName(user.getUserName());
        }
        Long count = (Long) sceneUserSceneClient.getSceneCount(cameraEntity.getId(),null,null).getData();
        cameraEntity.setSceneCount(count.intValue());
        UserIncrement userIncrementEntity = userIncrementService.getByCameraId(cameraEntity.getId());
        if(userIncrementEntity != null){
            cameraEntity.setUserIncrementId(userIncrementEntity.getId());
            cameraEntity.setIsExpire(userIncrementEntity.getIsExpired());
        }
        return cameraEntity;
    }

    public ResponseCameraApp getCameraInfo(String appUserName, String appPassword){
        Camera dbCameraEntity = cameraService.getByChildNameAndChildPassword(appUserName, appPassword);
        if (dbCameraEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4012, AppConstant.FAILURE_MSG_4012);
        }
        CameraDetail entity = cameraDetailService.getByCameraId(dbCameraEntity.getId());

        Goods goodsEntity = goodsService.getById(entity.getGoodsId());
        ResponseCameraApp cameraApp = new ResponseCameraApp();
        BeanUtils.copyProperties(dbCameraEntity, cameraApp);
        BeanUtils.copyProperties(entity, cameraApp);
        BeanUtils.copyProperties(goodsEntity, cameraApp);
        cameraApp.setId(dbCameraEntity.getId());
        return  cameraApp;
    }


    @Override
    public List<ResponseCameraApp> getCamerasForUser(RequestCamera camera) {
        if(StringUtils.isEmpty(camera.getUserName())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        User user = userService.getUserByUserName(camera.getUserName());
        if(user == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        if(camera.getCameraType() == null){
            camera.setCameraType(4);
        }
        List<CameraDetail> list = cameraDetailService.getListByUserId(user.getId(), camera.getCameraType().longValue());
        if(list == null){
            throw new BusinessException(ErrorCode.NOT_RECORD);
        }
        List<ResponseCameraApp> resultList = new ArrayList<>();
        for(CameraDetail entity : list){
            Camera cameraEntity = cameraService.getById(entity.getCameraId());
            if(cameraEntity == null){
                continue;
            }
            ResponseCameraApp cameraApp = this.getCameraInfo(cameraEntity.getChildName(), cameraEntity.getChildPassword());
            if (cameraApp == null){
                throw new BusinessException(ErrorCode.NOT_RECORD);
            }
            UserIncrement userIncrementEntity = userIncrementService.getByCameraId(cameraEntity.getId());
            if(userIncrementEntity != null){
                cameraApp.setUserIncrementId(userIncrementEntity.getId());
                cameraApp.setIsExpire(userIncrementEntity.getIsExpired());
            }
            resultList.add(cameraApp);
        }
        return resultList;
    }

    @Override
    public ResponseCamera getCameraDetail(Long cameraId) throws Exception {
        ResponseCamera vo = null;
        Camera cameraEntity = cameraService.getById(cameraId);
        if (cameraEntity != null){
            CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraId);
            User user = userService.getById(cameraDetailEntity.getUserId());
            vo = new ResponseCamera();
            vo.setId(cameraEntity.getId());
            vo.setActivatedTime(cameraEntity.getActivatedTime());
            vo.setBalance(cameraDetailEntity.getBalance());
            vo.setChildName(cameraEntity.getChildName());
            vo.setUserName(user == null ? null : user.getUserName());
        }
        return vo;
    }

    /**
     *
     * @param camera
     * @return
     * @throws Exception
     */
    @Override
    public String bindCamera(RequestCamera camera)  throws Exception{
        User userEntity = userService.getUserByUserName(camera.getUserName());
        if (userEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4007, AppConstant.FAILURE_MSG_4007);
        }
        Camera cameraEntity = cameraService.getByChildName(camera.getChildName());
        if (cameraEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
        if (/*cameraDetailEntity.getGoodsId() == 4 && */cameraDetailEntity.getUserId() != null){
            // 八目相机只能绑定一人，不能重复绑定
            throw new BusinessException(CameraConstant.FAILURE_6006);
        }
        cameraDetailService.bind(cameraEntity.getId(), userEntity.getId());

        sceneUserSceneClient.updateUserIdByCameraId(null,cameraEntity.getId());
        return ServerCode.SUCCESS.message();
    }

    @Override
    public ResponseCameraApp bindProCamera(RequestCamera camera) throws Exception {
        User userEntity = userService.getUserByUserName(camera.getUserName());
        if (userEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4007, AppConstant.FAILURE_MSG_4007);
        }
        Camera cameraEntity = null;
        if(camera.getChildName() != null){
            cameraEntity = cameraService.getByChildName(camera.getChildName());
        }
        if(camera.getSnCode() != null){
            cameraEntity = cameraService.getBySnCode(camera.getSnCode());
        }
        if (cameraEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
        if (cameraDetailEntity.getUserId() != null){
            throw new BusinessException(CameraConstant.FAILURE_6006);
        }

        if(camera.getCameraType() == null){
            camera.setCameraType(4);
        }
        if(camera.getCameraType().longValue() != cameraDetailEntity.getGoodsId()){
            throw new BusinessException(CameraConstant.FAILURE_6005);
        }

        cameraDetailService.bind(cameraEntity.getId(), userEntity.getId());

        sceneUserSceneClient.updateUserIdByCameraId(userEntity.getId(), cameraEntity.getId());

        ResponseCameraApp responseCamera = new ResponseCameraApp();
        responseCamera.setChildName(cameraEntity.getChildName());

        responseCamera.setUsedSpace(cameraDetailEntity.getUsedSpace());
        responseCamera.setTotalSpace(cameraDetailEntity.getTotalSpace());
        responseCamera.setUsedSpaceStr(FileSizeUtil.formatFileSize(cameraDetailEntity.getUsedSpace()));
        responseCamera.setTotalSpaceStr(FileSizeUtil.formatFileSize(cameraDetailEntity.getTotalSpace()));
        return responseCamera;
    }

    @Override
    public Camera findByChildNameAndChildPassword(String appUserName, String appPassword) throws Exception{
        Camera dbCameraEntity = cameraService.getByChildName(appUserName);
        if (dbCameraEntity == null){
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }
        if(!appPassword.equals(dbCameraEntity.getChildPassword())){
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }
        return dbCameraEntity;
    }
    @Override
    public String unbind(RequestCamera camera) throws Exception {
        Camera cameraEntity = cameraService.getByChildName(camera.getChildName());
        if (cameraEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        CameraDetail detailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
        if(detailEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        User  userEntity = userService.getUserByUserName(camera.getUserName());
        if(userEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        if(userEntity.getId().longValue() != detailEntity.getUserId().longValue()){
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }
        cameraDetailService.unbind(cameraEntity.getId());

        //相机解除绑定，一并解除权益绑定
        UserIncrement userIncrementEntity = userIncrementService.getByCameraId(cameraEntity.getId());
        if(userIncrementEntity != null){
            userIncrementService.unbindCamera(detailEntity.getUserId(), userIncrementEntity.getId(), true,detailEntity,userIncrementEntity);
        }
        sceneUserSceneClient.updateUserIdByCameraId(userEntity.getId(),cameraEntity.getId());
        //删除所有相机协作信息
//        if(detailEntity.getCooperationUser() != null){
            camera.setCameraId(cameraEntity.getId());
            userService.deleteCooperationUser(camera,detailEntity);
//        }
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String unbindPro(RequestCamera camera) throws Exception {
        Camera cameraEntity = cameraService.getByChildName(camera.getChildName());
        if (cameraEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        CameraDetail detailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
        if(detailEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }
        User userEntity = userService.getUserByUserName(camera.getUserName());
        if(userEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        if(userEntity.getId().longValue() != detailEntity.getUserId().longValue()){
            throw new BusinessException(CameraConstant.FAILURE_6005);
        }

        if(camera.getCameraType() == null){
            camera.setCameraType(4);
        }
        if(camera.getCameraType().longValue() != detailEntity.getGoodsId()){
            throw new BusinessException(CameraConstant.FAILURE_6005);
        }

        cameraDetailService.unbind(cameraEntity.getId());

        //相机解除绑定，一并解除权益绑定
        UserIncrement userIncrementEntity = userIncrementService.getByCameraId(cameraEntity.getId());
        if(userIncrementEntity != null){
            userIncrementService.unbindCamera(detailEntity.getUserId(), userIncrementEntity.getId(), true,detailEntity,userIncrementEntity);
        }

        sceneUserSceneClient.updateUserIdByCameraId(userEntity.getId(),cameraEntity.getId());

        //删除所有相机协作信息
//        if(detailEntity.getCooperationUser() != null){
            camera.setCameraId(cameraEntity.getId());
            userService.deleteCooperationUser(camera,detailEntity);
//        }
        return ServerCode.SUCCESS.message();
    }


}
