package com.fdkankan.ucenter.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.JwtUtil;
import com.fdkankan.ucenter.common.BaseController;
import com.fdkankan.ucenter.common.Result;
import com.fdkankan.ucenter.common.ResultData;
import com.fdkankan.ucenter.constant.LoginConstant;
import com.fdkankan.ucenter.entity.Camera;
import com.fdkankan.ucenter.entity.CameraDetail;
import com.fdkankan.ucenter.entity.ScenePro;
import com.fdkankan.ucenter.entity.User;
import com.fdkankan.ucenter.service.*;
import com.fdkankan.ucenter.util.DateUserUtil;
import com.fdkankan.ucenter.vo.request.CameraParam;
import com.fdkankan.ucenter.vo.request.ExportCameraParam;
import com.fdkankan.ucenter.vo.response.CameraAppVo;
import com.fdkankan.ucenter.vo.response.CameraExcelVo;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/ucenter/user/camera")
public class CameraController extends BaseController {

    @Autowired
    ICameraDetailService cameraDetailService;
    @Autowired
    ICameraService cameraService;
    @Autowired
    ISceneResourceService sceneResourceService;
    @Autowired
    IUserService userService;
    @Autowired
    ISceneProService sceneProService;

    /**
     * 获取设备到期数量
     */
    @PostMapping("/deadlineNumber")
    public Result deadlineNumber(){
        return Result.success(cameraDetailService.deadlineNumber(getUserName()));
    }

    /**
     * 分页列表
     */
    @PostMapping("/listNew")
    public Result listNew(@RequestBody CameraParam param){
        param.setUserName(getUserName());
        return Result.success(cameraService.pageList(param));
    }

    /**
     * 获取用户设备到期信息
     */
    @PostMapping("/deadline")
    public Result deadline(){
        return Result.success(cameraService.deadline(getUserName()));
    }

    /**
     * 用户解绑设备
     */
    @PostMapping("/unbind")
    public Result unbind(@RequestBody JSONObject jsonObject){
        cameraService.unbind(jsonObject.getLong("cameraId"),jsonObject.getString("ids"),getUserName());
        return Result.success();
    }

    /**
     *用户绑定设备
     */
    @PostMapping("/add")
    public Result add(@RequestBody JSONObject jsonObject){
        cameraService.bind(jsonObject.getInteger("cameraType"),jsonObject.getString("snCode"),getUserName());
        return Result.success();
    }

    /**
     * 添加相机协作用户
     */
    @PostMapping("/saveCooperationUser")
    public Result saveCooperationUser(@RequestBody JSONObject jsonObject){
        if(jsonObject.getString("userName").equals(getUserName())){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3025, LoginConstant.FAILURE_MSG_3025);
        }
        cameraService.saveCooperationUser(jsonObject.getString("ids"),
                jsonObject.getLong("cameraId"),jsonObject.getString("resourceIds"),jsonObject.getString("userName"), getLang());
        return Result.success();
    }

    /**
     * 删除相机协作用户
     */
    @PostMapping("/deleteCooperationUser")
    public Result deleteCooperationUser(@RequestBody JSONObject jsonObject){
        cameraService.deleteCooperationUser(jsonObject.getLong("cameraId"));
        return Result.success();
    }

    /**
     * 根据相机id获取场景资源集合
     */
    @PostMapping("/sceneResourceByCameraId")
    public Result sceneResourceByCameraId(@RequestBody JSONObject jsonObject){
        if(jsonObject.get("cameraId") == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        return Result.success(sceneResourceService.sceneResourceByCameraId(jsonObject.getLong("cameraId")));
    }

    /**
     * 获取用户设备--新（根据sn返回全部不分页）
     */
    @PostMapping("/listNewAll")
    public Result listNewAll(@RequestBody JSONObject jsonObject){
        if(jsonObject.get("childName") == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        return Result.success(cameraService.getAllList(jsonObject.getString("childName"),getToken()));
    }

    /**
     * 获取协作相机sn码集合
     */
    @PostMapping(value = "/getCooperationSnCodes")
    public Result getCooperationSnCodes() throws Exception {
        User user = userService.getByToken(getToken());
        LambdaQueryWrapper<CameraDetail> condition = new LambdaQueryWrapper<>();
        condition.eq(CameraDetail::getCooperationUser,user.getId());
        condition.eq(CameraDetail::getType,10);
        List<CameraDetail> list = cameraDetailService.list(condition);
        if(CollectionUtils.isEmpty(list)){
            return Result.success();
        }
        LambdaQueryWrapper<Camera>  condition2 = new LambdaQueryWrapper<>();
        condition2.in(Camera::getId,list.stream().map(CameraDetail::getCameraId)
                        .collect(Collectors.toList()));
        List<Camera> cameraEntities = cameraService.list(condition2);
        return Result.success(cameraEntities.stream().map(Camera::getSnCode).collect(Collectors.toList()));
    }

    /**
     * 相机登录之后使用 获取用户设备
     */
    @PostMapping(value = "/detail")
    public Result detail(@RequestBody  JSONObject jsonObject) {
        if(jsonObject.get("childName") == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        return Result.success(userService.findCameraDetailByChildName(getToken(), jsonObject.getString("childName")));
    }

    /**
     * 获取四维看看PRO - 我的相机列表 并到处execl
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public HSSFWorkbook export(@RequestBody ExportCameraParam param) throws Exception {

        String fileName = "我的相机";
        User user = userService.getByToken(getToken());
        List<CameraExcelVo> responseCameraList = cameraDetailService.getListByUserAndTypeEx(user.getId());
        List<Long> cameraIdList = responseCameraList.stream().map(CameraExcelVo::getCameraId).collect(Collectors.toList());

        List<ScenePro> sceneEntityList = new ArrayList<>();
        LambdaQueryWrapper<ScenePro> wrapper = new LambdaQueryWrapper<>();
        if(cameraIdList.size() >0){
            wrapper.in(ScenePro::getCameraId,cameraIdList);
            sceneEntityList = sceneProService.list(wrapper);
        }

        HashMap<Long,List<ScenePro>> sceneProMap = new HashMap<>();
        for (ScenePro scenePro : sceneEntityList) {
            if(sceneProMap.get(scenePro.getCameraId()) == null){
                List<ScenePro> proList = new ArrayList<>();
                proList.add(scenePro);
                sceneProMap.put(scenePro.getCameraId(),proList);
            }else {
                sceneProMap.get(scenePro.getCameraId()).add(scenePro);
            }

        }

        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 (CameraExcelVo 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.getSpaceEndStr() == null){
                    rowData.createCell(1).setCellValue(UsedSpaceStr + " / " + TotalSpaceStr);
                }else {
                    if(rc.getIsExpired() == null || rc.getIsExpired() == 1){
                        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.getCooperationUser());
                }
                List<ScenePro> proList = sceneProMap.get(rc.getCameraId());
                if(proList == null || proList.size() <=0){
                    rowData.createCell(4).setCellValue("");
                    rowData.createCell(5).setCellValue("");
                }else {
                    rowData.createCell(4).setCellValue(proList.size());
                    String lastTime = null;
                    for (ScenePro scenePro : proList) {
                        if(lastTime == null){
                            lastTime = scenePro.getCreateTime();
                        }else {
                            Date date1 = DateUserUtil.getDate(lastTime);
                            Date date2 = DateUserUtil.getDate(scenePro.getCreateTime());
                            if(date2.getTime() >date1.getTime()){
                                lastTime = scenePro.getCreateTime();
                            }
                        }

                    }
                    rowData.createCell(5).setCellValue(lastTime);
                }
                i++;
            }

        }

        if(sceneEntityList.size() >0){
            if(StringUtils.isNotBlank(param.getStartTime())){
                wrapper.ge(ScenePro::getCreateTime,param.getStartTime());
            }
            if(StringUtils.isNotBlank(param.getEndTime())){
                String date = DateUserUtil.getLastZeroTime(param.getEndTime());
                wrapper.le(ScenePro::getCreateTime,date);
            }
            if(StringUtils.isNotBlank(param.getStartTime()) || StringUtils.isNotBlank(param.getEndTime())){
                sceneEntityList = sceneProService.list(wrapper);
            }
        }

        HashMap<Long, Camera> cameraMap = cameraService.getByIds(cameraIdList);
        HashMap<Long, Integer> cameraSnCodeCountMap = new HashMap<>();
        for (ScenePro sceneProEntity : sceneEntityList) {
            if(cameraSnCodeCountMap.get(sceneProEntity.getCameraId()) ==null){
                cameraSnCodeCountMap.put(sceneProEntity.getCameraId(),1);
                continue;
            }
            Integer totalNum = 1 + 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 : cameraMap.keySet()) {
            HSSFRow rowData = sheet.createRow(i);
            i++;
            rowData.createCell(0).setCellValue(cameraMap.get(cameraId) == null ? "" : cameraMap.get(cameraId).getSnCode());
            rowData.createCell(1).setCellValue(param.getStartTime() == null ? "" : param.getStartTime());
            rowData.createCell(2).setCellValue(param.getEndTime() == null ? "" : param.getEndTime());
            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 (ScenePro sceneProEntity : sceneEntityList) {
            HSSFRow rowData = sheet2.createRow(k);
            k++;
            if(cameraMap.get(sceneProEntity.getCameraId()) == null){
                rowData.createCell(0).setCellValue("");
            }else {
                rowData.createCell(0).setCellValue(cameraMap.get(sceneProEntity.getCameraId()).getSnCode());
            }
            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 ? "" : sceneProEntity.getCreateTime());
        }

        //输出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;
    }
}
