package com.fdkankan.platform.goods.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.common.constant.*;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.*;
import com.fdkankan.platform.agent.constant.AgentConstant;
import com.fdkankan.platform.agent.entity.AgentFramework;
import com.fdkankan.platform.agent.service.IAgentFrameworkService;
import com.fdkankan.platform.agent.vo.ResponseAgentCamera;
import com.fdkankan.platform.common.ConstantExcel;
import com.fdkankan.platform.common.ExcelUtil;
import com.fdkankan.platform.common.ImportExeclUtil;
import com.fdkankan.platform.goods.common.CameraCache;
import com.fdkankan.platform.goods.entity.Camera;
import com.fdkankan.platform.goods.entity.CameraDetail;
import com.fdkankan.platform.goods.entity.CameraSpace;
import com.fdkankan.platform.goods.entity.Company;
import com.fdkankan.platform.order.entity.VirtualOrder;
import com.fdkankan.platform.order.service.IVirtualOrderService;
import com.fdkankan.platform.user.entity.Manager;
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.request.RequestVirtualOrder;
import com.fdkankan.platform.user.service.IManagerService;
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.redis.util.RedisUtil;
import com.fdkankan.scene.api.feign.SceneUserSceneClient;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ManagerCameraService {

    @Autowired
    private IVirtualOrderService virtualOrderService;
    @Autowired
    private ICameraDetailService cameraDetailService;
    @Autowired
    private ICameraService cameraService;
    @Autowired
    private  ICameraSpaceService cameraSpaceService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IUserIncrementService userIncrementService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IManagerService managerService;
    @Autowired
    private IAgentFrameworkService agentFrameworkService;
    @Autowired
    private SceneUserSceneClient sceneUserSceneClient;

    @Resource
    private RedisUtil redisUtil;
    @Value("${upload.type}")
    private String type;


    public Page<ResponseAgentCamera> searchAgentListDetail(RequestCamera param) throws Exception {
        Page<ResponseCamera> pageCameraVo = cameraDetailService.getPageByUserAndType(param, param.getUserId());
        List<ResponseAgentCamera> agentCameraResponseVos = this.getAgentCameraResponseVos(pageCameraVo.getRecords(), param.getStartDate(), param.getEndDate());

        Page<ResponseAgentCamera> pageVo = new Page<>(param.getPageNum(), param.getPageSize());
        pageVo.setTotal(pageCameraVo.getTotal());
        pageVo.setRecords(agentCameraResponseVos);
        return pageVo;
    }

    private List<ResponseAgentCamera> getAgentCameraResponseVos(List<ResponseCamera> cameraDetailEntities, String startDate, String endDate) throws Exception {
        List<ResponseAgentCamera> result = new ArrayList<>();
        for (ResponseCamera entity : cameraDetailEntities) {
            Camera cameraEntity = cameraService.getById(entity.getCameraId());
            if (cameraEntity == null) continue;
            ResponseAgentCamera vo = virtualOrderService.getPointsByCameraId(entity.getCameraId(), startDate, endDate);
            vo.setId(cameraEntity.getId());
            vo.setBalance(Integer.parseInt(entity.getBalance()));
            vo.setChildName(cameraEntity.getChildName());
            result.add(vo);
        }
        return result;
    }

    public JSONObject searchStatistics(RequestCamera param) {
        if(redisUtil.hasKey("CameraListTotalAmount")){
            String result = redisUtil.get("CameraListTotalAmount");
            return JSONObject.parseObject(result);
        }
        //累计充值金额/点数
        int subSubMoney = 0;
        //累计消耗点数
        int subSubStract = 0;

        int subMoney = 0;
        int subStract = 0;
        int subGift = 0;
        List<VirtualOrder> virtualOrderEntities = virtualOrderService.getAllByParam(param);
        for (VirtualOrder entity : virtualOrderEntities){
            if (entity.getStatus() == 1) {
                subMoney += entity.getPoints();
            } else if (entity.getStatus() == -1) {
                subStract += entity.getPoints();
            } else if (entity.getStatus() == 0) {
                subGift += entity.getPoints();
            } else if (entity.getStatus() == -2) {
                subMoney -= entity.getPoints();
            }
        }
        if (subStract > subGift) {
            subStract -= subGift;
        } else {
            subStract = 0;
        }
        subSubMoney += subMoney;
        subSubStract += subStract;
        JSONObject jo = new JSONObject();
        jo.put("subPoint", subSubMoney);
        jo.put("subCharge", subSubMoney);
        jo.put("subSubStract", subSubStract * AgentConstant.EXTRACT);
        jo.put("subSubStractPoint", subSubStract);
        redisUtil.set("CameraListTotalAmount", JSONObject.toJSONString(jo));
        return jo;
    }

    public JSONObject searchCameraDetailStatistics(RequestCamera param) {
        if (StringUtils.isNotEmpty(param.getStartDate()) && StringUtils.isEmpty(param.getEndDate())){
            param.setEndDate(new DateTime().toString("yyyy-MM-dd"));
        }
        if (StringUtils.isNotEmpty(param.getEndDate()) && StringUtils.isEmpty(param.getStartDate())){
            param.setStartDate(new DateTime().toString("yyyy-MM-dd"));
        }
        int subPoint = 0;
        List<VirtualOrder> virtual1 = virtualOrderService.getAllByParam(param);
        for (VirtualOrder virtualTrade : virtual1){
            subPoint += virtualTrade.getPoints();
        }
        if (param.getType() == 1){
            param.setType(-2);
            List<VirtualOrder> virtual2 = virtualOrderService.getAllByParam(param);
            for (VirtualOrder virtual : virtual2) {
                subPoint -= virtual.getAmount().intValue();
            }
        }
        CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(param.getCameraId());
        JSONObject jo = new JSONObject();
        jo.put("result", subPoint);
        jo.put("balance", cameraDetailEntity.getBalance());
        return jo;
    }

    public Page<ResponseCamera> queryCameraListByParams(RequestCamera param) {
        Page<ResponseCamera> pageInfo = cameraDetailService.queryListByParams(param);
        for (ResponseCamera responseCamera : pageInfo.getRecords()){
            if(responseCamera.getGoodsId() == 4){
                List<ResponseCameraSpace> cameraList = cameraSpaceService.getVoListByCameraId(responseCamera.getId());
                if(cameraList != null && cameraList.size() > 0){
                    responseCamera.setSpace((long) FileSizeUtil.formetFileSize(cameraList.get(0).getSpace().longValue(), FileSizeUtil.SIZETYPE_GB));
                    responseCamera.setSpaceStr(FileSizeUtil.formatFileSize(cameraList.get(0).getSpace().longValue()));
                    responseCamera.setSpaceEndStr(DateUtil. date2String(cameraList.get(0).getSpaceEndTime(), DateUtil.YYYY_MM_DD_DATE_FORMAT));
                }
            }
        }
        return pageInfo;
    }

    public String addCamera(RequestCamera param) {
        Camera cameraEntity = cameraService.addCameraByManager(param);
        if (cameraEntity == null){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        RequestVirtualOrder vo = new RequestVirtualOrder();
        vo.setBody(AgentConstant.DEFAULT_BODY);
        vo.setStatus(String.valueOf(0));//0-系统赠送
        vo.setPoints(Integer.parseInt(param.getBalance()));
        vo.setPayStatus(1);// 1表示成功
        vo.setPayType(2); // paypal
        vo.setOrderSn(param.getOrderSn());
        vo.setCameraId(cameraEntity.getId());
        vo.setAbroad(0);//0-国内
        if("aws".equals(type)){
            vo.setAbroad(1);//1-国外
        }
        vo.setUserId(null);// 空表示后台管理员添加
        vo.setTradeTime(new Date());
        vo.setAmount(new BigDecimal("0.00"));
        if(!virtualOrderService.addVirtualOrder(vo)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        //新增完相机后，判断是否归属企业账号，若归属查看企业账号相机是否自动注册，A注册，I不注册
        CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
        if(cameraDetailEntity.getCompanyId() != null){
            Company companyEntity = companyService.getById(cameraDetailEntity.getCompanyId());
            if(companyEntity != null && companyEntity.getCameraDelete() == 0){
                cameraEntity.setTbStatus(TbStatus.DELETE.code());
                cameraService.updateById(cameraEntity);
            }
        }
        return ServerCode.SUCCESS.message();
    }

    public void exportCamera(RequestCamera param, HttpServletRequest request, HttpServletResponse response) throws Exception{
        Page<ResponseCamera> responseCameraPage = cameraDetailService.queryListByParams(param);

        //导出的数据
        Map<String, String> item = null;
        List<Map> dataList = new ArrayList<Map>();
        String outType = "";
        for(ResponseCamera camera : responseCameraPage.getRecords()){
            //购买相机的订单
            item = new HashMap();
            item.put(ConstantExcel.CAMEREXCELCOLENAME[0], camera.getChildName());
            item.put(ConstantExcel.CAMEREXCELCOLENAME[1], camera.getSnCode());
            item.put(ConstantExcel.CAMEREXCELCOLENAME[2], DateUtil.date2String(camera.getInTime(), null));
            if(camera.getType() != null){
                if(camera.getType() == 0){
                    item.put(ConstantExcel.CAMEREXCELCOLENAME[3], "测试使用");
                }
                if(camera.getType() == 1){
                    item.put(ConstantExcel.CAMEREXCELCOLENAME[3], "线上出库");
                }
                if(camera.getType() == 2){
                    item.put(ConstantExcel.CAMEREXCELCOLENAME[3], "经销出库");
                }
            }
            item.put(ConstantExcel.CAMEREXCELCOLENAME[4], camera.getOrderSn());
            item.put(ConstantExcel.CAMEREXCELCOLENAME[5], camera.getAgentName());
            item.put(ConstantExcel.CAMEREXCELCOLENAME[6], DateUtil.date2String(camera.getOutTime(), null));
            item.put(ConstantExcel.CAMEREXCELCOLENAME[7], camera.getCountry() == 0? "大陆" : "海外");
            item.put(ConstantExcel.CAMEREXCELCOLENAME[8], camera.getUserName());
            item.put(ConstantExcel.CAMEREXCELCOLENAME[9], DateUtil.date2String(camera.getActivatedTime(), null));

            dataList.add(item);
        }

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = "库存数据-" + dateFormat.format(new Date());
        String fileName = dateStr + ".xls";
        File file = new File(FileUtils.getResource() + dateStr + ".xls");

        ExcelUtil.writeExcel(dataList, ConstantExcel.CAMEREXCELCOLENAME.length, FileUtils.getResource() + dateStr + ".xls", 5);

        String agent = request.getHeader("User-Agent");
        if (agent != null && (agent.contains("MSIE")||agent.contains("Trident"))) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
        response.setContentType(request.getServletContext().getMimeType(fileName));
        response.setContentLength((int) file.length());
        ExcelUtil.output(response, file);
    }

    public String modifyPoints(RequestCamera param) {
        String result = virtualOrderService.modifyPoints(param);
        boolean result2 = cameraDetailService.updateCameraBalance(param.getCameraId(), param.getBody(), param.getPoints());
        if(!result2){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        return result;
    }

    public String unbindCamera(Long cameraId) throws Exception {
        boolean bind = cameraDetailService.unbind(cameraId);
        if(!bind){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        CameraDetail detailEntity = cameraDetailService.getByCameraId(cameraId);
        //相机解除绑定，一并解除权益绑定
        UserIncrement userIncrementEntity = userIncrementService.getByCameraId(cameraId);
        if(userIncrementEntity != null){
            userIncrementService.unbindCamera(detailEntity.getUserId(), userIncrementEntity.getId(), true,detailEntity,userIncrementEntity);
        }

        sceneUserSceneClient.updateUserIdByCameraId(null,cameraId);

        //删除所有相机协作信息

//        if(detailEntity.getCooperationUser() != null){
        RequestCamera camera = new RequestCamera();
        camera.setCameraId(cameraId);
        userService.deleteCooperationUser(camera,detailEntity);
        return ServerCode.SUCCESS.message();
    }

    public String bindCamera(Long cameraId, String userName) {
        User userEntity = userService.getUserByUserName(userName);
        if (userEntity == null){
            throw new BusinessException(AppConstant.FAILURE_CODE_4007, AppConstant.FAILURE_MSG_4007);
        }
        boolean bind = cameraDetailService.bind(cameraId, userEntity.getId());
        if(!bind){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        sceneUserSceneClient.updateUserIdByCameraId(userEntity.getId(),cameraId);
        return ServerCode.SUCCESS.message();

    }

    public String manageSpace(RequestCamera param) {
        if(param.getCameraId() == null || param.getMonth() == null || param.getSpace() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        //新的容量套餐方案
        cameraSpaceService.removeByCameraId(param.getCameraId());

        CameraDetail detailEntity = cameraDetailService.getByCameraId(param.getCameraId());
        if(detailEntity == null){
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }

        CameraSpace cameraSpaceEntity = new CameraSpace();
        DateTime date = null;
        if(param.getMonth() == 12){
            date = new DateTime().plusYears(1);
        }else {
            date = new DateTime().plusDays(param.getMonth() * 31);
        }
        cameraSpaceEntity.setUserId(detailEntity.getUserId());
//        cameraSpaceEntity.setOrderSn(orderSn);
        cameraSpaceEntity.setCameraId(param.getCameraId());
        cameraSpaceEntity.setSpace(Long.parseLong(Constant.EXPANSION_SPACE_VALUE_1G )* Long.parseLong(param.getSpace() + ""));
        cameraSpaceEntity.setSpaceType(2);
        cameraSpaceEntity.setSpaceStartTime(new Date());
        cameraSpaceEntity.setSpaceEndTime(date.toDate());
        cameraSpaceService.save(cameraSpaceEntity);

        detailEntity.setTotalSpace(cameraSpaceEntity.getSpace());
        cameraDetailService.updateById(detailEntity);

        sceneUserSceneClient.unlockBeyondSpaceScenes(cameraSpaceEntity.getSpace(),  param.getCameraId());
        return ServerCode.SUCCESS.message();
    }

    public String recoverSpace(RequestCamera param) {
        if(param.getCameraId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        //删除改相机所有扩容记录
        cameraSpaceService.removeByCameraId(param.getCameraId());


        //恢复10G基本容量
        CameraDetail detailEntity = cameraDetailService.getByCameraId(param.getCameraId());
        if(detailEntity == null){
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }
        detailEntity.setTotalSpace(Long.parseLong(Constant.EXPANSION_SPACE_VALUE_1G) * 10);
        cameraDetailService.updateById(detailEntity);
        sceneUserSceneClient.lockBeyondSpaceScenes(detailEntity.getUsedSpace(), detailEntity.getTotalSpace(), detailEntity.getCameraId());
        return ServerCode.SUCCESS.message();

    }

    public Page<ResponseCamera> companyList(RequestCamera param, String token) {
        Manager managerEntity = this.checkManagerUser(token);
        param.setUserName(managerEntity.getUsername());
        return cameraDetailService.queryCompanyCameraListByParams(param);
    }

    public String companyUpdate(RequestCamera param, String token) {
        this.checkManagerUser(token);
        Camera cameraEntity = new Camera();
        cameraEntity.setId(param.getCameraId());
        cameraEntity.setTbStatus(param.getTbStatus());
        cameraService.updateById(cameraEntity);

        CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(param.getCameraId());
        cameraDetailEntity.setAddress(param.getAddress());
        cameraDetailService.updateById(cameraDetailEntity);
        return ServerCode.SUCCESS.message();
    }
    private Manager checkManagerUser(String token){
        String userName = JwtUtil.getUsername(token);
        Manager managerEntity = managerService.getByUserName(userName.replace(SsoUtil.PREFIX_CACHE_MANAGER, ""));
        if (managerEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }
        if(managerEntity.getIsCompany() != 1){
            throw new BusinessException(ErrorCode.NOT_PERMISSION);
        }
        return managerEntity;
    }

    public Camera addCameraNew(RequestCamera param) {
        if(StringUtils.isEmpty(param.getSnCode()) || param.getType() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        Camera cameraEntity = cameraService.getBySnCode(param.getSnCode());
        if(cameraEntity != null){
            throw new BusinessException(CameraConstant.FAILURE_6001);
        }

        cameraEntity = new Camera();
        cameraEntity.setSnCode(param.getSnCode());
        cameraEntity.setChildName(param.getSnCode());
        cameraEntity.setActivatedTime(new Date());
        cameraEntity.setWifiPassword(AgentConstant.WIFI_PASSWORD_VALUE);
        cameraEntity.setWifiName("4DKKPRO_" + param.getSnCode());
        cameraEntity.setChildPassword(AgentConstant.CHILD_PASSWORD_VALUE);
        cameraService.save(cameraEntity);

        CameraDetail detailEntity = new CameraDetail();
        detailEntity.setCameraId(cameraEntity.getId());
        detailEntity.setAgency(AgentConstant.DEFAULT_AGENT);
        detailEntity.setCountry(0);//默认中国
        if("aws".equals(type)){
            detailEntity.setCountry(1);//1-国外
        }
        detailEntity.setCameraType(param.getType());
        //商品类型，type：1为8目，type：2为双目 3:为转台
        if(param.getType().equals(3)){
            detailEntity.setGoodsId(9L);
        }else {
            detailEntity.setGoodsId(param.getType() == 1 ? 4L : 8L);
        }

        detailEntity.setTotalSpace(Long.valueOf(Constant.CAMERA_BASE_SPACE_VALUE));
        detailEntity.setUsedSpace(Long.valueOf("0"));
        cameraDetailService.save(detailEntity);
        return cameraEntity;
    }

    public String cameraOwn(RequestCamera param) {
        if(StringUtils.isEmpty(param.getOwn()) || param.getCameraId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }

        if(Integer.parseInt(param.getOwn()) == 4 && param.getAgentFrameworkId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        Camera cameraEntity = cameraService.getById(param.getCameraId());
        if(cameraEntity == null || TbStatus.DELETE.code().equals(cameraEntity.getTbStatus())){
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }
        CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
        cameraDetailEntity.setOwn(Integer.valueOf(param.getOwn()));
        cameraDetailEntity.setAgentFrameworkId(param.getAgentFrameworkId());
        cameraDetailService.updateById(cameraDetailEntity);
        return ServerCode.SUCCESS.message();
    }

    public Page<ResponseCamera> cameraList(RequestCamera param, String userName) {
        //查找该用户的权限，判断是否四维看看管理员用户
        Manager managerEntity = managerService.getByUserName(userName);
        if(managerEntity == null){
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }

        AgentFramework agentFrameworkEntity = null;

        if(managerEntity.getAgentFrameworkId() != null){
            agentFrameworkEntity = agentFrameworkService.getById(managerEntity.getAgentFrameworkId());
            //四维看看管理员用户是最顶层父类，若有父类，则是企业用户，则只返回该企业的相机列表
            if(agentFrameworkEntity != null && agentFrameworkEntity.getParentId() != null){
                param.setAgentFrameworkId(agentFrameworkEntity.getId());
            }
        }

        Page<ResponseCamera> pageInfo = cameraDetailService.cameraList(param);

        Company companyEntity = null;
        User userEntity = null;
        for (ResponseCamera responseCamera : pageInfo.getRecords()) {
            if(responseCamera.getAgentFrameworkId() != null){
                agentFrameworkEntity = agentFrameworkService.getById(responseCamera.getAgentFrameworkId());
                if(agentFrameworkEntity != null && TbStatus.VALID.code().equals(agentFrameworkEntity.getTbStatus())){
                    responseCamera.setAgentFrameworkName(agentFrameworkEntity.getAgentName());
                }
            }

            if(responseCamera.getCompanyId() != null){
                companyEntity = companyService.getById(responseCamera.getCompanyId());
                if(companyEntity != null && TbStatus.VALID.code().equals(companyEntity.getTbStatus())){
                    responseCamera.setCompanyName(companyEntity.getCompanyName());
                }
            }

            if(responseCamera.getUserId() != null){
                userEntity = userService.getById(responseCamera.getUserId());
                if(userEntity != null && TbStatus.VALID.code().equals(userEntity.getTbStatus())){
                    responseCamera.setUserName(userEntity.getUserName());
                }
            }
        }
        return pageInfo;
    }

    public Integer importCamera(MultipartFile file) throws Exception{
        if (file.isEmpty() && file.getSize() <= 0) {
            throw new BusinessException(SceneConstant.FAILURE_CODE_5012, SceneConstant.FAILURE_MSG_5012);
        }

        //文件上传的位置可以自定义
        String path = FileUtils.getResource() + "camera/";
        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        String fileName = "inCamera-" + DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS_DATA_FORMAT);
        targetFile = new File(path + File.separator + fileName);
        // 保存
        synchronized(this)
        {
            if(targetFile.exists())
            {
                FileUtils.deleteFile(path + File.separator + fileName);
            }
            file.transferTo(targetFile);
        }

        ImportExeclUtil poi = new ImportExeclUtil();
        List<List<String>> list = poi.read(path + File.separator + fileName);
        if (list != null) {
            Camera cameraEntity = null;
            String importError = "";
            RequestCamera param = new RequestCamera();
            for (int i = 0; i < list.size(); i++) {
                List<String> cellList = list.get(i);
                if(i < 3){
                    continue;
                }
                importError = CameraCache.IMPORT_ERROR_NUM.replace("{n}", (i + 1) + "");
                if(!"四维看看Pro八目相机".equals(cellList.get(0).trim()) && !"四维看看Lite双目相机".equals(cellList.get(0).trim())){
                    throw new BusinessException(CameraConstant.FAILURE_6018.code(), importError + CameraConstant.FAILURE_6018.name());
                }

                cameraEntity = cameraService.getBySnCode(cellList.get(1).trim());
                if(cameraEntity != null){
                    throw new BusinessException(CameraConstant.FAILURE_6001.code(), importError + CameraConstant.FAILURE_6001.name());
                }

                param = new RequestCamera();
                param.setSnCode(cellList.get(1).trim());
                if("四维看看Pro八目相机".equals(cellList.get(0).trim())){
                    param.setType(1);
                }
                if("四维看看Lite八目相机".equals(cellList.get(0).trim())){
                    param.setType(2);
                }
                this.addCameraNew(param);
            }

        }
        return list.size() - 3;
    }

    public Integer importOutCamera(MultipartFile file) throws Exception {
        if (file.isEmpty() && file.getSize() <= 0) {
            throw new BusinessException(SceneConstant.FAILURE_CODE_5012, SceneConstant.FAILURE_MSG_5012);
        }

        //文件上传的位置可以自定义
        String path = FileUtils.getResource() + "camera/";
        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        String fileName = "outCamera-" + DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS_DATA_FORMAT);
        targetFile = new File(path + File.separator + fileName);
        // 保存
        synchronized(this)
        {
            if(targetFile.exists())
            {
                FileUtils.deleteFile(path + File.separator + fileName);
            }
            file.transferTo(targetFile);
        }

        ImportExeclUtil poi = new ImportExeclUtil();
        List<List<String>> list = poi.read(path + File.separator + fileName);
        if (list != null) {
            Camera cameraEntity = null;
            String importError = "";
            QueryWrapper<AgentFramework> queryWrapper = null;
            Long agentFrameworkId = null;
            CameraDetail cameraDetailEntity = null;
            for (int i = 0; i < list.size(); i++) {
                List<String> cellList = list.get(i);
                if(i < 3){
                    continue;
                }
                importError = CameraCache.IMPORT_ERROR_NUM.replace("{n}", (i + 1) + "");
                if(StringUtils.isEmpty(cellList.get(0).trim())){
                    throw new BusinessException(CameraConstant.FAILURE_6019.code(), importError + CameraConstant.FAILURE_6019.name());
                }
                if(StringUtils.isEmpty(cellList.get(1).trim())){
                    throw new BusinessException(CameraConstant.FAILURE_6021.code(), importError + CameraConstant.FAILURE_6021.name());
                }
                if(!"正常销售".equals(cellList.get(1).trim()) && !"经销商销售".equals(cellList.get(1).trim())
                        && !"礼品赠送".equals(cellList.get(1).trim()) && !"员工自用".equals(cellList.get(1).trim())
                        && !"其他".equals(cellList.get(1).trim())){
                    throw new BusinessException(CameraConstant.FAILURE_6022.code(), importError + CameraConstant.FAILURE_6022.name());

                }
                if("经销商销售".equals(cellList.get(1).trim())){
                    if(StringUtils.isEmpty(cellList.get(2).trim())){
                        throw new BusinessException(CameraConstant.FAILURE_6023.code(), importError + CameraConstant.FAILURE_6023.name());
                    }

                    queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(AgentFramework::getTbStatus,TbStatus.VALID.code());
                    queryWrapper.lambda().eq(AgentFramework::getAgentName,cellList.get(2).trim());
                    List<AgentFramework> agentFrameworkEntityList = agentFrameworkService.list(queryWrapper);
                    if(agentFrameworkEntityList.size() <= 0){
                        throw new BusinessException(CameraConstant.FAILURE_6024.code(), importError + CameraConstant.FAILURE_6024.name());
                    }
                    agentFrameworkId = agentFrameworkEntityList.get(0).getId();
                }

                cameraEntity = cameraService.getBySnCode(cellList.get(0).trim());
                if(cameraEntity == null || TbStatus.DELETE.code().equals(cameraEntity.getTbStatus())){
                    throw new BusinessException(CameraConstant.FAILURE_6020.code(), importError + CameraConstant.FAILURE_6020.name());
                }

                cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
                if("正常销售".equals(cellList.get(1).trim())){
                    cameraDetailEntity.setOwn(0);
                }
                if("经销商销售".equals(cellList.get(1).trim())){
                    cameraDetailEntity.setOwn(4);
                }
                if("礼品赠送".equals(cellList.get(1).trim())){
                    cameraDetailEntity.setOwn(2);
                }
                if("员工自用".equals(cellList.get(1).trim())){
                    cameraDetailEntity.setOwn(1);
                }
                if("其他".equals(cellList.get(1).trim())){
                    cameraDetailEntity.setOwn(3);
                }
                cameraDetailEntity.setAgentFrameworkId(agentFrameworkId);
                cameraDetailService.updateById(cameraDetailEntity);
            }

        }
        return list.size() - 3;
    }

    public Integer importCompanyCamera(MultipartFile file) throws Exception {
        if (file.isEmpty() && file.getSize() <= 0) {
            throw new BusinessException(SceneConstant.FAILURE_CODE_5012, SceneConstant.FAILURE_MSG_5012);
        }

        //文件上传的位置可以自定义
        String path = FileUtils.getResource() + "camera/";
        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        String fileName = "companyCamera-" + DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS_DATA_FORMAT);
        targetFile = new File(path + File.separator + fileName);
        // 保存
        synchronized(this)
        {
            if(targetFile.exists())
            {
                FileUtils.deleteFile(path + File.separator + fileName);
            }
            file.transferTo(targetFile);
        }

        ImportExeclUtil poi = new ImportExeclUtil();
        List<List<String>> list = poi.read(path + File.separator + fileName);
        if (list != null) {
            Camera cameraEntity = null;
            String importError = "";
            CameraDetail cameraDetailEntity = null;
            QueryWrapper<Company> queryWrapper = null;
            List<Company> companyEntityList = null;
            Long companyId = null;
            for (int i = 0; i < list.size(); i++) {
                List<String> cellList = list.get(i);
                if(i < 3){
                    continue;
                }
                importError = CameraCache.IMPORT_ERROR_NUM.replace("{n}", (i + 1) + "");

                if(StringUtils.isEmpty(cellList.get(0).trim())){
                    throw new BusinessException(CameraConstant.FAILURE_6019.code(), importError + CameraConstant.FAILURE_6019.name());
                }
                if(StringUtils.isEmpty(cellList.get(1).trim())){
                    throw new BusinessException(CameraConstant.FAILURE_6026.code(), importError + CameraConstant.FAILURE_6026.name());
                }

                cameraEntity = cameraService.getBySnCode(cellList.get(1).trim());
                if(cameraEntity == null || TbStatus.DELETE.code().equals(cameraEntity.getTbStatus())){
                    throw new BusinessException(CameraConstant.FAILURE_6020.code(), importError + CameraConstant.FAILURE_6020.name());
                }

                cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
                if(cameraDetailEntity.getOwn() == null){
                    throw new BusinessException(CameraConstant.FAILURE_6025.code(), importError + CameraConstant.FAILURE_6025.name());
                }

                queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(Company::getTbStatus,TbStatus.VALID.code());
                queryWrapper.lambda().eq(Company::getCompanyName,cellList.get(1).trim());
                companyEntityList = companyService.list(queryWrapper);
                if(companyEntityList.size() <= 0){
                    throw new BusinessException(CameraConstant.FAILURE_6027.code(), importError + CameraConstant.FAILURE_6027.name());

                }
                companyId = companyEntityList.get(0).getId();

                cameraDetailEntity.setCameraId(companyId);
                cameraDetailService.updateById(cameraDetailEntity);
            }

        }
        return list.size() - 3;
    }
}
