package com.fdkankan.ucenter.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.connect.model.HistoricalMetricResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.redis.constant.RedisKey;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.ucenter.common.CameraTypeEnum;
import com.fdkankan.ucenter.common.PageInfo;
import com.fdkankan.ucenter.common.Result;
import com.fdkankan.ucenter.common.constants.ConstantFilePath;
import com.fdkankan.ucenter.constant.CameraConstant;
import com.fdkankan.ucenter.constant.LoginConstant;
import com.fdkankan.ucenter.entity.*;
import com.fdkankan.ucenter.httpClient.service.LaserService;
import com.fdkankan.ucenter.service.*;
import com.fdkankan.ucenter.util.DateUserUtil;
import com.fdkankan.ucenter.vo.SceneBySnCodeVo;
import com.fdkankan.ucenter.vo.request.RequestScene;
import com.fdkankan.ucenter.vo.request.SceneParam;
import com.fdkankan.ucenter.vo.response.SceneVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class SceneApiService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ICameraService cameraService;
    @Autowired
    ICameraDetailService cameraDetailService;
    @Autowired
    ISceneService sceneService;
    @Autowired
    ISceneProService sceneProService;
    @Autowired
    IScenePlusService scenePlusService;
    @Autowired
    ISceneEditInfoService sceneEditInfoService;
    @Autowired
    IScenePlusExtService scenePlusExtService;
    @Autowired
    ISceneProEditService sceneProEditService;
    @Autowired
    LaserService laserService;
    @Autowired
    IUserService userService;
    @Autowired
    ICameraTypeService cameraTypeService;

    public Result getScenesBySnCode(String snCode, String token) {
        User user = checkToken(token);
        if(StringUtils.isEmpty(snCode)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }

        Camera cameraEntity = cameraService.getBySnCode(snCode);
        if(cameraEntity == null ){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6018, CameraConstant.FAILURE_MSG_6018);
        }
        CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
        if(cameraDetailEntity == null ){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6018, CameraConstant.FAILURE_MSG_6018);
        }
        if(!cameraDetailEntity.getUserId().equals(user.getId())){
            return Result.success();
        }
        CameraType cameraType = cameraTypeService.getByCameraType(cameraDetailEntity.getType());
        if (cameraType.getIsLaser() == 1) {
            List<SceneBySnCodeVo> scenesBySnCode = laserService.getScenesBySnCode(snCode, token);
            return Result.success(scenesBySnCode);
        }
        List<SceneBySnCodeVo> sceneVo = new ArrayList<>();

        LambdaQueryWrapper<ScenePro> proWr = new LambdaQueryWrapper<>();
        proWr.eq(ScenePro::getCameraId,cameraEntity.getId());
        proWr.eq(ScenePro::getIsUpgrade,0);
        proWr.eq(ScenePro::getUserId,user.getId());
        proWr.ne(ScenePro::getSceneSource,11);
        List<ScenePro> list = sceneProService.list(proWr);
        for (ScenePro scenePro : list) {
            SceneBySnCodeVo sceneBySnCodeVo = new SceneBySnCodeVo();
            sceneBySnCodeVo.setSceneNum(scenePro.getNum());
            sceneBySnCodeVo.setSceneName(scenePro.getSceneName());
            sceneVo.add(sceneBySnCodeVo);
        }

        LambdaQueryWrapper<ScenePlus> pluWr = new LambdaQueryWrapper<>();
        pluWr.eq(ScenePlus::getCameraId,cameraEntity.getId());
        pluWr.eq(ScenePlus::getUserId,user.getId());
        pluWr.ne(ScenePlus::getSceneSource,11);
        List<ScenePlus> list1 = scenePlusService.list(pluWr);

        for (ScenePlus scenePlus : list1) {
            SceneBySnCodeVo sceneBySnCodeVo = new SceneBySnCodeVo();
            sceneBySnCodeVo.setSceneNum(scenePlus.getNum());
            sceneBySnCodeVo.setSceneName(scenePlus.getTitle());
            sceneVo.add(sceneBySnCodeVo);
        }
        return Result.success(sceneVo);
    }

    private User checkToken (String token){
        if(StringUtils.isEmpty(token)){
            throw new BusinessException(3004, "无token参数");
        }
        String redisKey = String.format(RedisKey.TOKEN_V3,token);

        if( !redisUtil.hasKey(redisKey)){
            throw new BusinessException(3004, "token参数不正确");
        }
        User user = userService.getByToken(token);
        if(user == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        return user;
    }

    public PageInfo siweiSceneList(HttpServletRequest request, String token) {
        User user = checkToken(token);
        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");

        String sceneName = request.getParameter("sceneName");
        String snCode = request.getParameter("snCode");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String num = request.getParameter("num");

        Integer pageNum = 1;
        Integer pageSize = 10;
        if(StringUtils.isNotEmpty(pageNumStr)){
            pageNum = Integer.valueOf(pageNumStr);
        }

        if(StringUtils.isNotEmpty(pageSizeStr)){
            pageSize = Integer.valueOf(pageSizeStr);
        }
        RequestScene param = new RequestScene();
        param.setPageNum(pageNum);
        param.setPageSize(pageSize);
        param.setSnCode(snCode);
        param.setStartTime(startDate);
        param.setEndTime(endDate);
        param.setNum(num);
        param.setSceneName(sceneName);
        param.setUserId(user.getId());
        Page<SceneVo> sceneVoPage = sceneService.getSceneList(param);
        List<Map<String, Object>> list = new ArrayList<>();
        for (SceneVo sceneVo : sceneVoPage.getRecords()) {
            HashMap<String,Object> map = new HashMap<>();
            map.put("num", sceneVo.getNum());
            map.put("sceneName", sceneVo.getSceneName());
            Camera cameraEntity = cameraService.getById(sceneVo.getCameraId());
            if(cameraEntity != null){
                map.put("snCode", cameraEntity.getSnCode());
            }
            map.put("webSite", sceneVo.getWebSite());
            map.put("createDate", DateUserUtil.getDate(sceneVo.getCreateTime()).getTime());
            map.put("createTime", sceneVo.getCreateTime());
            map.put("thumb", sceneVo.getThumb());
            map.put("isUpgrade", sceneVo.getIsUpgrade());

            if(sceneVo.getIsUpgrade() == 0){
                ScenePro scenePro = sceneProService.getById(sceneVo.getId());
                if(scenePro!= null){
                    map.put("shootCount", scenePro.getShootCount());
                    SceneProEdit sceneProEdit = sceneProEditService.getByProId(scenePro.getId());
                    map.put("version", sceneProEdit.getVersion());
                }
            }
            if(sceneVo.getIsUpgrade() == 1){
                ScenePlus scenePlus = scenePlusService.getById(sceneVo.getId());
                if(scenePlus!= null){
                    ScenePlusExt ext = scenePlusExtService.getByPlusId(scenePlus.getId());
                    map.put("shootCount", ext.getShootCount());
                    SceneEditInfo editInfo = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
                    map.put("version", editInfo.getVersion());
                }
            }

            list.add(map);
        }
        Page<Map<String, Object>> page = new Page<Map<String, Object>>(pageNum, pageSize);
        page.setTotal(sceneVoPage.getTotal());
        page.setRecords(list);
        return PageInfo.PageInfo(page);
    }

    public PageInfo loadAllScene(JSONObject param) {
        String searchKey = param.getString("searchKey");
        Integer pageNum = param.getInteger("pageNum") == null ?1 : param.getInteger("pageNum");
        Integer pageSize = param.getInteger("pageSize")== null ?10 : param.getInteger("pageSize");


        if(param.getInteger("sceneScheme") == 4){
            LambdaQueryWrapper<ScenePro> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(ScenePro::getStatus, Arrays.asList(1,-2));
            if(StringUtils.isNotEmpty(searchKey)){
                wrapper.like(ScenePro::getSceneName,searchKey);
                wrapper.or().like(ScenePro::getNum,searchKey);
            }
            wrapper.orderByDesc(ScenePro::getCreateTime);
            Page<ScenePro> proPage = sceneProService.page(new Page<>(pageNum,pageSize),wrapper);
            return PageInfo.PageInfo(proPage);
        }
        LambdaQueryWrapper<Scene> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Scene::getStatus, Arrays.asList(1,-2));
        if(StringUtils.isNotEmpty(searchKey)){
            wrapper.like(Scene::getSceneName,searchKey);
            wrapper.or().like(Scene::getNum,searchKey);
        }
        wrapper.orderByDesc(Scene::getCreateTime);
        Page<Scene> proPage = sceneService.page(new Page<>(pageNum,pageSize),wrapper);
        return PageInfo.PageInfo(proPage);
    }

    public void addDownloadNum(String sceneNum) {
        if(StringUtils.isEmpty(sceneNum)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        ScenePro scenePro = sceneProService.getByNum(sceneNum);
        if(scenePro != null){
            SceneProEdit sceneProEditEntity = sceneProEditService.getByProId(scenePro.getId());
            if(sceneProEditEntity.getDownloadNum() == null){
                sceneProEditEntity.setDownloadNum(1);
            }else{
                sceneProEditEntity.setDownloadNum(sceneProEditEntity.getDownloadNum() + 1);
            }
            sceneProEditService.updateById(sceneProEditEntity);
        }
    }

    public List<String> getEditDataUrl(String num) {

        if(StringUtils.isEmpty(num)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        List<String> result = new ArrayList<>();
        ScenePro scenePro = sceneProService.getByNum(num);
        if(scenePro != null){
            List<String> urlList = new ArrayList<>();
            FileUtils.readfilePath(ConstantFilePath.SCENE_PATH + "data/data" + num, urlList);
            FileUtils.readfilePath(ConstantFilePath.SCENE_PATH + "images/images" + num, urlList);
            FileUtils.readfilePath(ConstantFilePath.SCENE_PATH + "voice/voice" + num, urlList);
            if(urlList.size() > 0){
                for(String url : urlList){
                    result.add(url.replace(ConstantFilePath.BASE_PATH + "/", ""));
                }
            }
        }else {
            ScenePlus plus = scenePlusService.getByNum(num);
            if(plus != null){
                List<String> urlList = new ArrayList<>();
                FileUtils.readfilePath(ConstantFilePath.SCENE_V4_PATH + num, urlList);
                if(urlList.size() > 0){
                    for(String url : urlList){
                        result.add(url.replace(ConstantFilePath.SCENE_V4_PATH , "scene_edit_data/"));
                    }
                }
            }
        }
        return result;
    }
}
