package com.ozs.web.controller.accountmanagment;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.file.FileUtils;
import com.ozs.common.utils.http.HttpUtils;
import com.ozs.common.utils.poi.ExcelUtil;
import com.ozs.service.entity.BaseCameraManagement;
import com.ozs.service.entity.BaseDeviceDynamicManagement;
import com.ozs.service.entity.BaseLineManagement;
import com.ozs.service.entity.vo.BaseCameraManagementVo;
import com.ozs.service.service.BaseCameraManagementService;
import com.ozs.service.service.BaseDeviceDynamicManagementService;
import com.ozs.service.service.BaseLineManagementService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 台账管理表 前端控制器
 * </p>
 *
 * @author ozs
 * @since 2023-02-17
 */
@RestController
@RequestMapping("/service/baseCameraManagement")
@Slf4j
public class BaseCameraManagementController extends BaseController {
    @Resource
    BaseCameraManagementService baseCameraManagementService;
    @Resource
    BaseDeviceDynamicManagementService baseDeviceDynamicManagementService;
    @Resource
    BaseLineManagementService baseLineManagementService;

    /**
     * 相机台账管理分页
     *
     * @param baseCameraManagementVo
     * @return
     */
    @ApiOperation(value = "相机台账管理分页")
    @PostMapping("/list")
    public AjaxResult selectBaseAccountManagement(@RequestBody BaseCameraManagementVo baseCameraManagementVo) {
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
        if (!StringUtils.isBlank(baseCameraManagementVo.getLine())) {
            lw.eq(BaseCameraManagement::getRailway, baseCameraManagementVo.getLine());
        }
        if (!StringUtils.isBlank(baseCameraManagementVo.getLineType())) {
            lw.eq(BaseCameraManagement::getLineType, baseCameraManagementVo.getLineType());
        }
        if (!StringUtils.isBlank(baseCameraManagementVo.getPublicWorksSection())) {
            lw.eq(BaseCameraManagement::getPublicWorksSection, baseCameraManagementVo.getPublicWorksSection());
        }
        if (!ObjectUtils.isEmpty(baseCameraManagementVo.getBeginMile())) {
            lw.ge(BaseCameraManagement::getBeginMile, baseCameraManagementVo.getBeginMile());
        }
        if (!ObjectUtils.isEmpty(baseCameraManagementVo.getEndMile())) {
            lw.le(BaseCameraManagement::getEndMile, baseCameraManagementVo.getEndMile());
        }
        IPage<BaseCameraManagement> page = baseCameraManagementService.page(new Page<>(baseCameraManagementVo.getPageNum(), baseCameraManagementVo.getPageSize()), lw);
        return AjaxResult.success(page);
    }

    /**
     * 删除相机信息
     *
     * @param accountManagementIds
     * @return
     */
    @DeleteMapping("/{accountManagementIds}")
    @ApiOperation("删除相机信息")
    public AjaxResult removeAccountManagement(@PathVariable List<Long> accountManagementIds) {
        if (baseCameraManagementService.removeByIds(accountManagementIds)) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 新增相机信息
     *
     * @param baseCameraManagement
     * @return
     */
    @PostMapping("/saveAccountManagement")
    @ApiOperation("新增相机信息")
    public AjaxResult saveDistributionModule(@RequestBody BaseCameraManagement baseCameraManagement) {
        baseCameraManagement.setCreateBy(getUsername());
        BaseDeviceDynamicManagement baseDynamicManagement = new BaseDeviceDynamicManagement();
        baseDynamicManagement.setCameraCode(baseCameraManagement.getCameraCode());
        if (baseCameraManagementService.save(baseCameraManagement) && baseDeviceDynamicManagementService.save(baseDynamicManagement)) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 修改相机信息
     *
     * @param baseCameraManagement
     * @return
     */
    @PutMapping("/editAccountManagement")
    @ApiOperation("修改相机信息")
    public AjaxResult editAccountManagement(@RequestBody BaseCameraManagement baseCameraManagement) {
        baseCameraManagement.setUpdateBy(getUsername());
        if (baseCameraManagementService.updateById(baseCameraManagement)) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @GetMapping(value = "/{accountManagementId}")
    @ApiOperation("根据相机ID获取详细信息")
    public AjaxResult getInfo(@PathVariable Long accountManagementId) {
        return AjaxResult.success(baseCameraManagementService.getById(accountManagementId));
    }

    /**
     * 台账管理导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @ApiOperation("台账管理导入")
    @PostMapping("/importBaseAccountManagement")
    public AjaxResult importBaseAccountManagement(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BaseCameraManagement> util = new ExcelUtil<BaseCameraManagement>(BaseCameraManagement.class);
        List<BaseCameraManagement> AccountManageList = util.importExcel(file.getInputStream());
        String message = baseCameraManagementService.importBaseAccountManagement(AccountManageList, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 导出台账管理
     *
     * @param response
     */
    @ApiOperation("导出台账管理")
    @PostMapping("/exportBaseAccountManagement")
    public void exportBaseAccountManagement(HttpServletResponse response, @RequestBody BaseCameraManagementVo baseAccountManagementVo) {
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
        if (!StringUtils.isBlank(baseAccountManagementVo.getLine())) {
            lw.eq(BaseCameraManagement::getRailway, baseAccountManagementVo.getLine());
        }
        if (!StringUtils.isBlank(baseAccountManagementVo.getLineType())) {
            lw.eq(BaseCameraManagement::getLineType, baseAccountManagementVo.getLineType());
        }
        if (!StringUtils.isBlank(baseAccountManagementVo.getPublicWorksSection())) {
            lw.eq(BaseCameraManagement::getPublicWorksSection, baseAccountManagementVo.getPublicWorksSection());
        }
        if (!ObjectUtils.isEmpty(baseAccountManagementVo.getBeginMile())) {
            lw.ge(BaseCameraManagement::getBeginMile, baseAccountManagementVo.getBeginMile());
        }
        if (!ObjectUtils.isEmpty(baseAccountManagementVo.getEndMile())) {
            lw.le(BaseCameraManagement::getEndMile, baseAccountManagementVo.getEndMile());
        }
        List<BaseCameraManagement> list = baseCameraManagementService.list(lw);
        ExcelUtil<BaseCameraManagement> util = new ExcelUtil<>(BaseCameraManagement.class);
        util.exportExcel(response, list, "台账管理相机数据");
    }


    @ApiOperation("模板下载")
    @GetMapping("/downloaExcel")
    public void downloadZip(HttpServletResponse response) {
        try {
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/template/provisionalPlan.xlsx");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, "临时计划导入模板.xlsx");
            FileUtils.writeBytesByInput(resourceAsStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @ApiOperation("获取视频服务一级菜单")
    @GetMapping("/firstLevelMenu")
    public AjaxResult firstLevelMenu() {
        List<BaseLineManagement> list = baseLineManagementService.list();
        List<String> collect = list.stream().map(BaseLineManagement::getLineName).collect(Collectors.toList());
        return success(collect);
    }

    @ApiOperation("获取视频服务二级菜单")
    @GetMapping("/secondaryMenu/{lineName}")
    public AjaxResult secondaryMenu(@PathVariable String lineName) {
        return baseCameraManagementService.secondaryMenu(lineName);
    }

    @ApiOperation("获取视频服务三级菜单")
    @GetMapping("/threeLevelMenu/{secondaryMenuName}/{lineName}")
    public AjaxResult threeLevelMenu(@PathVariable String secondaryMenuName, @PathVariable String lineName) {
        return baseCameraManagementService.threeLevelMenu(secondaryMenuName, lineName);
    }


    @ApiOperation("查询录像")
    @GetMapping("/api/records")
    public AjaxResult apiRecords() {
        String param = "id=34020000001320000002&channel=34020000001320000002";
        String s = HttpUtils.sendGet("http://47.106.159.135:8554/gb28181/api/records", param);
        System.out.println(s);
        return success(HttpUtils.sendGet("http://47.106.159.135:8554/gb28181/api/records", param));
    }

    @ApiOperation("播放回放")
    @GetMapping("/api/invite")
    public AjaxResult apiInvite() {
        String param = "id=34020000001320000002&channel=34020000001320000002&startTime=1677230469&endTime=1677230513";
        return success(HttpUtils.sendGet("http://47.106.159.135:8554/gb28181/api/invite/", param));
    }


    @ApiOperation("视频服务设备数量")
    @GetMapping("/totalNumberOfDevices")
    public AjaxResult totalNumberOfDevices() {
        long count = baseDeviceDynamicManagementService.count();
        LambdaQueryWrapper<BaseDeviceDynamicManagement> lw = new LambdaQueryWrapper<BaseDeviceDynamicManagement>();
        lw.eq(BaseDeviceDynamicManagement::getCameraState, 1);
        long onLine = baseDeviceDynamicManagementService.count(lw);
        LambdaQueryWrapper<BaseDeviceDynamicManagement> wrapper = new LambdaQueryWrapper<BaseDeviceDynamicManagement>();
        wrapper.eq(BaseDeviceDynamicManagement::getCameraState, 2);
        long offLine = baseDeviceDynamicManagementService.count(wrapper);
        List<Long> size = new ArrayList<>();
        size.add(count);
        size.add(onLine);
        size.add(offLine);
        return success(size);
    }

    @ApiOperation("视频服务树形结构")
    @GetMapping("/cameraTree")
    @Cacheable(value = "baseAccountManagement", key = "'cameraTree'")
    public AjaxResult cameraTree(@RequestParam(value = "name",required = false) String name) {
     return    success(baseDeviceDynamicManagementService.cameraTree(name));
    }
}

