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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.constant.*;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.common.user.SSOUser;
import com.fdkankan.common.util.DateUtil;
import com.fdkankan.common.util.FileSizeUtil;
import com.fdkankan.common.util.NumberUtils;
import com.fdkankan.platform.agent.constant.AgentConstant;
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.mapper.ICameraMapper;
import com.fdkankan.platform.goods.service.ICameraDetailService;
import com.fdkankan.platform.goods.service.ICameraService;
import com.fdkankan.platform.goods.service.ICameraSpaceService;
import com.fdkankan.platform.goods.service.IGoodsService;
import com.fdkankan.platform.order.service.IDownloadOrderService;
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.platform.user.vo.ResponseCameraSpace;
import com.fdkankan.scene.api.dto.SceneProDTO;
import com.fdkankan.scene.api.feign.SceneUserSceneClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 相机主表 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-12-24
 */
@Service
public class CameraServiceImpl extends ServiceImpl<ICameraMapper, Camera> implements ICameraService {

    @Autowired
    private ICameraDetailService cameraDetailService;
    @Autowired
    private ICameraSpaceService cameraSpaceService;
    @Autowired
    private IUserIncrementService userIncrementService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;
    @Value("${upload.type}")
    private String type;
    @Autowired
    private SceneUserSceneClient sceneUserSceneClient;
    @Autowired
    private IDownloadOrderService downloadOrderService;


    @Override
    public Camera saveByAgent(String childName, String wifiName, String agentId, String balance) {
        Camera camera = getByChildName(childName);
        if(camera == null){
            Camera cameraEntity = new Camera();
            cameraEntity.setChildName(childName);
            cameraEntity.setChildPassword(AgentConstant.CHILD_PASSWORD_VALUE);
            cameraEntity.setWifiName(wifiName);
            cameraEntity.setWifiPassword(AgentConstant.WIFI_PASSWORD_VALUE);
            cameraEntity.setActivatedTime(new Date());
            save(cameraEntity);

            camera = getByChildName(childName);
            CameraDetail detailEntity = new CameraDetail();
            detailEntity.setCameraId(camera.getId());
            detailEntity.setAgency(agentId);
            detailEntity.setBalance(balance);
            detailEntity.setOwn(0);
            detailEntity.setCountry(0);
            //t_goods表的ID：1
            detailEntity.setGoodsId(1L);
            //detailEntity.setOrderSn(NumberUtils.getOrderSn());
            cameraDetailService.save(detailEntity);
        }
        return camera;
    }


    @Override
    public Camera getByChildName(String childName){
        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Camera::getTbStatus,TbStatus.VALID.code());
        queryWrapper.lambda().eq(Camera::getChildName,childName);
        return this.getEntityByQuery(queryWrapper);
    }

    @Override
    public Page<ResponseCamera> getPageByUser(RequestCamera param, Long userId)  throws Exception{
        Page<ResponseCamera> pageVo = cameraDetailService.getPageByUserAndType(param, userId);
        if (param.getCameraType() == 4 || param.getCameraType() == 9 || param.getCameraType() == 10){
            coverList(pageVo.getRecords());
        }
        return pageVo;
    }

    private void coverList(List<ResponseCamera> list) throws Exception{
        UserIncrement userIncrement = null;

        for (ResponseCamera responseCamera : list) {
            Integer surplusDate = null;

            List<ResponseCameraSpace> cameraList = cameraSpaceService.getVoListByCameraId(responseCamera.getId());
            if(cameraList != null && cameraList.size() > 0){
                responseCamera.setSpace((long) FileSizeUtil.formetFileSize(cameraList.get(0).getSpace(), FileSizeUtil.SIZETYPE_GB));
                responseCamera.setSpaceStr(FileSizeUtil.formatFileSize(cameraList.get(0).getSpace()));
                responseCamera.setSpaceEndStr(DateUtil.date2String(cameraList.get(0).getSpaceEndTime(), DateUtil.YYYY_MM_DD_DATE_FORMAT));
                if(Days.daysBetween(new DateTime(), new DateTime(cameraList.get(0).getSpaceEndTime())).getDays() < 7){
                    responseCamera.setIsExpire(true);
                }
            }

            userIncrement = userIncrementService.getByCameraId(responseCamera.getId());

            if(userIncrement != null){
                responseCamera.setUserIncrementId(userIncrement.getId());
                responseCamera.setSpaceEndStr(DateUtil.date2String(userIncrement.getIncrementEndTime(), DateUtil.YYYY_MM_DD_DATE_FORMAT));
                surplusDate = Days.daysBetween(new DateTime(), new DateTime(userIncrement.getIncrementEndTime())).getDays();
                if(surplusDate < 31){
                    responseCamera.setIsExpire(true);
                    responseCamera.setSurplusDate(surplusDate);
                }else {
                    responseCamera.setIsExpire(false);
                }
            }

            if(responseCamera.getCooperationUser() != null){
                User userEntity = userService.getById(responseCamera.getCooperationUser());
                if(userEntity != null){
                    responseCamera.setCooperationUserName(userEntity.getUserName());
                }
            }
            ResultData<Integer> sceneNumResult = sceneUserSceneClient
                .getSceneNumByCameraId(responseCamera.getId(),responseCamera.getType(),responseCamera.getSnCode());
            if(!sceneNumResult.getSuccess())
                throw new Exception(ServerCode.FEIGN_REQUEST_FAILD.message());
            responseCamera.setSceneNum(sceneNumResult.getData());

            ResultData<SceneProDTO> SceneProResult = sceneUserSceneClient
                .getLastSceneByCameraId(responseCamera.getId());
            if(!SceneProResult.getSuccess())
                throw new Exception(ServerCode.FEIGN_REQUEST_FAILD.message());
            SceneProDTO sceneProDTO = SceneProResult.getData();
            if(sceneProDTO != null){
                responseCamera.setLastTime(sceneProDTO.getCreateTime());
            }

        }
    }

    @Override
    public List<ResponseCamera> getByUser(Long userId, Integer cameraType) {
        QueryWrapper<CameraDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CameraDetail::getTbStatus,TbStatus.VALID.code());
        if(cameraType == null){
            queryWrapper.lambda().eq(CameraDetail::getUserId,userId);
        }else if(cameraType == 4){
            queryWrapper.lambda().eq(CameraDetail::getUserId,userId);
            queryWrapper.lambda().ge(CameraDetail::getGoodsId,cameraType);
        }else {
            queryWrapper.lambda().le(CameraDetail::getGoodsId,cameraType);
        }
        List<CameraDetail> list = cameraDetailService.list(queryWrapper);
        return convert(list);
    }

    @Override
    public List<ResponseCamera>  convert(List<CameraDetail> list) {
        List<ResponseCamera> vos = new ArrayList<>();
        if (list != null && list.size() > 0){
            for (CameraDetail detailEntity : list){
                Camera cameraEntity = this.getById(detailEntity.getCameraId());
                Goods goodsEntity = goodsService.getById(detailEntity.getGoodsId());
                if (cameraEntity != null && goodsEntity != null){
                    ResponseCamera vo = new ResponseCamera();
                    vo.setId(cameraEntity.getId());
                    vo.setActivatedTime(cameraEntity.getActivatedTime());
                    vo.setBalance(detailEntity.getBalance());
                    vo.setChildName(cameraEntity.getChildName());
                    vo.setSnCode(cameraEntity.getSnCode());
                    vo.setGoodsName(goodsEntity.getGoodName());
                    vo.setImageUrl(goodsEntity.getImageUrl());
                    vo.setGoodsId(detailEntity.getGoodsId());
                    vo.setPic(goodsEntity.getPic());
                    vo.setCooperationUser(detailEntity.getCooperationUser());
                    if (detailEntity.getCameraType() != 0){
                        vo.setUsedSpace(FileSizeUtil.formetFileSize(detailEntity.getUsedSpace(), FileSizeUtil.SIZETYPE_GB));
                        vo.setTotalSpace(FileSizeUtil.formetFileSize(detailEntity.getTotalSpace(), FileSizeUtil.SIZETYPE_GB));
                        vo.setUsedSpaceStr(FileSizeUtil.formatFileSize(detailEntity.getUsedSpace()));
                        vo.setTotalSpaceStr(FileSizeUtil.formatFileSize(detailEntity.getTotalSpace()));
                    }
                    vo.setType(detailEntity.getCameraType());
                    vos.add(vo);
                }
            }
        }
        return vos;
    }

    @Override
    public String addCamera(RequestCamera camera, String token) {
        Long userId = null;
        if(token != null){
            SSOUser ssoUser = userService.getSSOUserByToken(token);
            userId = ssoUser.getId();
        }
        String[] snCodeArr = camera.getSnCode().split(",");
        for (String snCode : snCodeArr) {
            Camera cameraEntity = this.getBySnCode(snCode);
            if (cameraEntity == null){
                cameraEntity = this.getBySnCode(snCode.replace("4DKKPRO_",""));
                if(cameraEntity == null){
                    throw new BusinessException(AppConstant.FAILURE_CODE_4010, snCode + "-" + AppConstant.FAILURE_MSG_4010);
                }
            }
            CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
            if (cameraDetailEntity.getUserId() != null){
                throw new BusinessException(CameraConstant.FAILURE_6010);
            }
           this.addCamera(userId, camera.getCameraType(), cameraEntity.getId());
        }
        return ServerCode.SUCCESS.message();
    }

    private void addCamera(Long userId, Integer cameraType, Long cameraId){
        cameraDetailService.bind(userId,cameraId);
        sceneUserSceneClient.updateUserIdByCameraId(userId,cameraId);
    }

    @Override
    public Camera getBySnCode(String snCode) {
        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Camera::getTbStatus,TbStatus.VALID.code());
        queryWrapper.lambda().eq(Camera::getSnCode,snCode);
        return this.getEntityByQuery(queryWrapper);
    }

    @Override
    public List<ResponseCameraSpace> cameraSpaceList(RequestCamera camera) {
        if(camera == null || camera.getChildName() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        Camera cameraEntity = this.getByChildName(camera.getChildName());
        if (cameraEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4010, AppConstant.FAILURE_MSG_4010);
        }

        return cameraSpaceService.getVoListByCameraId(cameraEntity.getId());
    }

    @Override
    public ResponseCamera findCameraBySn(RequestCamera camera) {
        if(camera == null || camera.getSnCode() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        Camera cameraEntity = this.getBySnCode(camera.getSnCode());
        if (cameraEntity == null){
            cameraEntity = this.getBySnCode(camera.getSnCode().replace("4DKKPRO_",""));
            if(cameraEntity == null){
                throw new BusinessException(CameraConstant.FAILURE_6003);
            }
        }
        CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
        if(cameraDetailEntity == null){
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }

        if(cameraDetailEntity.getUserId() == null){
            throw new BusinessException(CameraConstant.FAILURE_6012);
        }
        User userEntity = userService.getById(cameraDetailEntity.getUserId());
        if(userEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }

        ResponseCamera responseCamera = new ResponseCamera();
        BeanUtils.copyProperties(cameraEntity, responseCamera);

        responseCamera.setUserName(userEntity.getUserName());
        return responseCamera;
    }

    @Override
    public List<Camera> getCameraLikeSnCode(String trim) {
        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Camera::getTbStatus,TbStatus.VALID.code());
        queryWrapper.lambda().like(Camera::getSnCode,trim);
        return this.list(queryWrapper);
    }

    @Override
    public Camera getByChildNameAndChildPassword(String appUserName, String appPassword) {
        QueryWrapper<Camera> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Camera::getTbStatus,TbStatus.VALID.code());
        queryWrapper.lambda().eq(Camera::getChildName,appUserName);
        queryWrapper.lambda().eq(Camera::getChildPassword,appPassword);
        return this.getEntityByQuery(queryWrapper);
    }

    @Override
    public Camera getAvailableById(Long id) {
        Camera camera = this.getOne(new LambdaQueryWrapper<Camera>()
                .eq(Camera::getTbStatus, TbStatus.VALID.code())
                .eq(Camera::getId, id));
        return camera;
    }

    private Camera getEntityByQuery(QueryWrapper<Camera> queryWrapper ){
        List<Camera> list = this.list(queryWrapper);
        if(list == null || list.size() <= 0){
            return null;
        }
        return list.get(0);
    }

    @Override
    public HSSFWorkbook export(String token, HttpServletResponse response,RequestCamera param) throws Exception {

        String fileName = "我的相机";
        SSOUser ssoUser = userService.getSSOUserByToken(token);
        List<ResponseCamera> responseCameraList = cameraDetailService.getListByUserAndType(4, ssoUser.getId());
        HSSFWorkbook wb = new HSSFWorkbook();
        if (responseCameraList != null) {

            HSSFSheet sheet = wb.createSheet("camera");
            //在sheet里创建第一行，这里即是表头
            HSSFRow rowTitle = sheet.createRow(0);
            rowTitle.createCell(0).setCellValue("S/N码");
            rowTitle.createCell(1).setCellValue("云容量");
            rowTitle.createCell(2).setCellValue("到期时间");
            rowTitle.createCell(3).setCellValue("协作者");
            rowTitle.createCell(4).setCellValue("拍摄场景数量");
            rowTitle.createCell(5).setCellValue("最后拍摄时间");

            int i = 1;
            String rl = "";
            String UsedSpaceStr = "";
            String TotalSpaceStr = "";
            for (ResponseCamera rc : responseCameraList) {
                HSSFRow rowData = sheet.createRow(i);
                rowData.createCell(0).setCellValue(rc.getSnCode());


                if(rc.getUsedSpaceStr() == null || StringUtils.isEmpty(rc.getUsedSpaceStr())){
                    UsedSpaceStr = "0GB";
                }else {
                    UsedSpaceStr = rc.getUsedSpaceStr();
                }

                if(rc.getTotalSpaceStr() == null || StringUtils.isEmpty(rc.getTotalSpaceStr())){
                    TotalSpaceStr = "0GB";
                }else {
                    TotalSpaceStr = rc.getTotalSpaceStr();
                }

                if(rc.getUserIncrementId() == null){
                    rowData.createCell(1).setCellValue(UsedSpaceStr + " / " + TotalSpaceStr);
                }else {
                    if(rc.getIsExpire() == null || rc.getIsExpire() == true){
                        rowData.createCell(1).setCellValue(UsedSpaceStr + " / " + TotalSpaceStr);
                    }else{
                        rowData.createCell(1).setCellValue(UsedSpaceStr);
                    }
                }

                if(rc.getSpaceEndStr() == null ){
                    rowData.createCell(2).setCellValue("");
                }else{
                    rowData.createCell(2).setCellValue(rc.getSpaceEndStr());
                }

                if(rc.getCooperationUser() == null ){
                    rowData.createCell(3).setCellValue("");
                }else{
                    rowData.createCell(3).setCellValue(rc.getCooperationUserName());
                }
                if(rc.getSceneNum() == null ){
                    rowData.createCell(4).setCellValue("");
                }else{
                    rowData.createCell(4).setCellValue(rc.getSceneNum());
                }
                if(rc.getLastTime() == null ){
                    rowData.createCell(5).setCellValue("");
                }else{
                    String time = DateUtil.date2String(rc.getLastTime(),null);
                    rowData.createCell(5).setCellValue(time);
                }
                i++;
            }
        }
        assert responseCameraList != null;
        List<Long> cameraIdList = responseCameraList.stream().map(ResponseCamera::getId).collect(Collectors.toList());
        StringBuilder cameraIds = new StringBuilder();
        for (Long aLong : cameraIdList) {
            cameraIds.append(aLong).append(",");
        }
        if(cameraIds.length() >0 && cameraIds.toString().contains(",")){
            cameraIds.deleteCharAt(cameraIds.lastIndexOf(","));
        }
        ResultData reultData = sceneUserSceneClient.findByCameraIds(cameraIds.toString(), param.getStartTime(), param.getEndTime());
        List<SceneProDTO> sceneEntityList = (List<SceneProDTO>) reultData.getData();
        HashMap<String, Integer> countBySceneNumMap = downloadOrderService.getCountBySceneNum();
        List<Camera> cameras = this.findByIds(cameraIdList);
        HashMap<Long, String> cameraSnCodeMap = new HashMap<>();
        for (Camera camera : cameras) {
            cameraSnCodeMap.put(camera.getId(),camera.getSnCode());
        }
        HashMap<Long, Integer> cameraSnCodeCountMap = new HashMap<>();
        for (SceneProDTO sceneProEntity : sceneEntityList) {
            if(cameraSnCodeCountMap.get(sceneProEntity.getCameraId()) ==null){
                cameraSnCodeCountMap.put(sceneProEntity.getCameraId(),countBySceneNumMap.get(sceneProEntity.getNum()));
                continue;
            }
            Integer num = countBySceneNumMap.get(sceneProEntity.getNum()) == null ? 0 :countBySceneNumMap.get(sceneProEntity.getNum());
            Integer totalNum = num + (cameraSnCodeCountMap.get(sceneProEntity.getCameraId())== null ? 0 :cameraSnCodeCountMap.get(sceneProEntity.getCameraId()));
            cameraSnCodeCountMap.put(sceneProEntity.getCameraId(),totalNum);
        }

        HSSFSheet sheet = wb.createSheet("scene");
        //在sheet里创建第一行，这里即是表头
        HSSFRow rowTitle = sheet.createRow(0);
        rowTitle.createCell(0).setCellValue("S/N码");
        rowTitle.createCell(1).setCellValue("开始时间");
        rowTitle.createCell(2).setCellValue("结束时间");
        rowTitle.createCell(3).setCellValue("下载数量");
        int i = 1;
        for (Long  cameraId : cameraSnCodeMap.keySet()) {
            HSSFRow rowData = sheet.createRow(i);
            i++;
            rowData.createCell(0).setCellValue(cameraSnCodeMap.get(cameraId) == null ? "" : cameraSnCodeMap.get(cameraId));
            rowData.createCell(1).setCellValue(param.getStartDate() == null ? "" : param.getStartDate());
            rowData.createCell(2).setCellValue(param.getEndDate() == null ? "" : param.getEndDate());
            if(cameraSnCodeCountMap.get(cameraId) == null){
                rowData.createCell(3).setCellValue("");
                continue;
            }
            rowData.createCell(3).setCellValue(cameraSnCodeCountMap.get(cameraId));
        }


        HSSFSheet sheet2 = wb.createSheet("info");
        //在sheet里创建第一行，这里即是表头
        HSSFRow rowTitle2 = sheet2.createRow(0);
        rowTitle2.createCell(0).setCellValue("S/N码");
        rowTitle2.createCell(1).setCellValue("场景码");
        rowTitle2.createCell(2).setCellValue("场景名称");
        rowTitle2.createCell(3).setCellValue("场景链接");
        rowTitle2.createCell(4).setCellValue("创建时间");

        int k = 1;
        for (SceneProDTO sceneProEntity : sceneEntityList) {
            HSSFRow rowData = sheet2.createRow(k);
            k++;
            if(cameraSnCodeMap.get(sceneProEntity.getCameraId()) == null){
                rowData.createCell(0).setCellValue("");
            }else {
                rowData.createCell(0).setCellValue(cameraSnCodeMap.get(sceneProEntity.getCameraId()));
            }
            rowData.createCell(1).setCellValue(sceneProEntity.getNum() == null ? "" :sceneProEntity.getNum());
            rowData.createCell(2).setCellValue(sceneProEntity.getSceneName() == null ? "" :sceneProEntity.getSceneName());
            rowData.createCell(3).setCellValue(sceneProEntity.getWebSite() == null ? "" :sceneProEntity.getWebSite());
            rowData.createCell(4).setCellValue(sceneProEntity.getCreateTime() == null ? "" : DateUtil.date2String(sceneProEntity.getCreateTime(),DateUtil.DEFAULT_DATE_FORMAT));
        }

        //输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        //中文名称要进行编码处理
        response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO8859-1") + ".xls");
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        return wb;
    }

    @Override
    public Camera addCameraByManager(RequestCamera param) {
        Camera camera = this.getByChildName(param.getChildName());
        if (camera != null){
            throw new BusinessException(CameraConstant.FAILURE_6001);
        }
        String orderSn = param.getOrderSn();
        if (StringUtils.isEmpty(orderSn)){
            orderSn = NumberUtils.getOrderSn();
        }
        //添加相机
        Camera cameraEntity = new Camera();
        cameraEntity.setActivatedTime(new Date());
        cameraEntity.setWifiPassword(AgentConstant.WIFI_PASSWORD_VALUE);
        cameraEntity.setWifiName(param.getWifiName());
        cameraEntity.setSnCode(param.getSnCode());
        cameraEntity.setChildName(param.getChildName());
        cameraEntity.setChildPassword(AgentConstant.CHILD_PASSWORD_VALUE);
        this.save(cameraEntity);

        CameraDetail detailEntity = new CameraDetail();
        detailEntity.setCameraId(cameraEntity.getId());
        detailEntity.setOrderSn(orderSn);
        detailEntity.setOwn(StringUtils.isEmpty(param.getOwn()) ? 0 : Integer.valueOf(param.getOwn()));
        detailEntity.setAgency(AgentConstant.DEFAULT_AGENT);
        detailEntity.setCountry(0);//默认中国
        if("aws".equals(type)){
            detailEntity.setCountry(1);//1-国外
        }
        detailEntity.setBalance(param.getBalance());
        detailEntity.setCameraType(param.getType());
        if(param.getType() == 9){
            detailEntity.setGoodsId(9L);
        }else if(param.getType() == 10){
            detailEntity.setGoodsId(10L);
        }else{
            detailEntity.setGoodsId(param.getType() == 0 ? 1L : 4L);
        }

        if (1 == param.getType() || 9 == param.getType() || 10 == param.getType()){
            detailEntity.setTotalSpace(Long.parseLong(Constant.CAMERA_BASE_SPACE_VALUE));
            detailEntity.setUsedSpace(0L);
        }
        detailEntity.setCompanyId(param.getCompanyId());
        cameraDetailService.save(detailEntity);
        return cameraEntity;
    }

    @Override
    public Camera updateCameraByManager(RequestCamera param) {
        Camera dbCamera = this.getByChildName(param.getChildName());
        if (dbCamera == null){
            throw new BusinessException(CameraConstant.FAILURE_6020);
        }
        String orderSn = param.getOrderSn();
        if (StringUtils.isEmpty(orderSn)){
            orderSn = NumberUtils.getOrderSn();
        }
        //添加相机
        Camera cameraEntity = new Camera();
        cameraEntity.setId(param.getCameraId());

        cameraEntity.setActivatedTime(new Date());
        cameraEntity.setWifiPassword(AgentConstant.WIFI_PASSWORD_VALUE);
        cameraEntity.setWifiName(param.getWifiName());
        cameraEntity.setSnCode(param.getSnCode());
        cameraEntity.setChildName(param.getChildName());
        cameraEntity.setChildPassword(AgentConstant.CHILD_PASSWORD_VALUE);
        this.updateById(cameraEntity);

        CameraDetail detailEntity = cameraDetailService.getByCameraId(param.getCameraId());

        if(detailEntity!=null){

            detailEntity.setCameraId(param.getCameraId());
            detailEntity.setOwn(param.getOwn() ==null ? 0 : Integer.valueOf(param.getOwn()));
            detailEntity.setBalance(param.getBalance());
            detailEntity.setOrderSn(orderSn);
            // lite类型的相机，修改为 Pro、 Minion、Laser类型，相机云端总容量没有更新为10GB
            if (0 == detailEntity.getCameraType() && param.getType()!=detailEntity.getCameraType()){
                detailEntity.setTotalSpace(Long.parseLong(Constant.CAMERA_BASE_SPACE_VALUE));
            }
            detailEntity.setCameraType(param.getType());
            if(param.getType() == 9 || param.getType() == 10){
                detailEntity.setGoodsId(param.getType().longValue());
            }else{
                detailEntity.setGoodsId(param.getType() == 0 ? 1L : 4L);
            }
            detailEntity.setCompanyId(param.getCompanyId());

            cameraDetailService.updateById(detailEntity);
        }

        return cameraEntity;
    }

    @Override
    public String deleteCamera(RequestCamera param) {
        String[] ids = param.getIds().split(",");
        List<Long>  detailIds = new ArrayList<>();
        for(String id : ids){
            CameraDetail cameraDetail = cameraDetailService.getByCameraId(Long.valueOf(id));
            detailIds.add(cameraDetail.getId());
        }
        if(!cameraDetailService.removeByIds(detailIds)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        if(!this.removeByIds(Arrays.asList(ids))){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String deleteCameraNew(RequestCamera param) {
        String[] ids = param.getIds().split(",");
        CameraDetail cameraDetailEntity = null;
        for(String id : ids){
            cameraDetailEntity = cameraDetailService.getByCameraId(Long.valueOf(id));
            if(cameraDetailEntity.getOwn() != null){
                throw new BusinessException(CameraConstant.FAILURE_6017);
            }
            cameraDetailService.removeById(cameraDetailEntity.getId());
            this.removeById(Long.valueOf(id));
        }
        return ServerCode.SUCCESS.message();
    }

    @Override
    public List<Camera> findByIds(List<Long> ids) {
        LambdaQueryWrapper<Camera> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Camera::getId,ids);
        return this.list(queryWrapper);
    }
}
