package com.zc.business.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.zc.business.domain.DcDevice;
import com.zc.business.domain.DcDispatch;
import com.zc.business.domain.DcNoStakeWarningTable;
import com.zc.business.domain.DcWarning;
import com.zc.business.domain.DcWarningBatchConvert;
import com.zc.business.enums.UniversalEnum;
import com.zc.business.service.IDcWarningService;
import com.zc.business.utils.WeatherTrafficProposeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 预警信息Controller
 *
 * @author ruoyi
 * @date 2024-01-26
 */
@Api(tags = "感知事件")
@Component
@RestController
@RequestMapping("/business/warning")
public class DcWarningController extends BaseController
{
    @Autowired
    private IDcWarningService dcWarningService;

    //定时任务,定时结束部分事件
    public void updateEndSection(){
        IDcWarningService ben = SpringUtils.getBean(IDcWarningService.class);
        ben.updateEndSection();
    }

    /**
     * 感知事件数据统计
     */
    @ApiOperation("感知事件数据统计")
    @GetMapping("/countNumber")
    public AjaxResult dcWarningCountNumber(@RequestParam(required = false) Integer warningSource) {
        return AjaxResult.success(dcWarningService.dcWarningCountNumber(warningSource));
    }

    /**
     * 查询预警信息列表
     */
    @ApiOperation("查询感知事件列表")
   // @PreAuthorize("@ss.hasPermi('business:warning:list')")
    @GetMapping("/list")
    public TableDataInfo list(DcWarning dcWarning)
    {
        startPage();
        List<HashMap<String,Object>> list = dcWarningService.selectDcWarningList(dcWarning);
        return getDataTable(list);
    }

    /**
     *
     */
    @ApiOperation("查询视频审核事件类型")
    // @PreAuthorize("@ss.hasPermi('business:warning:list')")
    @PostMapping("/videoReviewEventTypeList")
    public AjaxResult videoReviewEventType(@RequestBody DcWarning dcWarning)
    {
        Map<String, Object> list = dcWarningService.selectVideoReviewEventTypeList(dcWarning);
        return AjaxResult.success(list);
    }    @ApiOperation("查询视频审核路段分布")
    // @PreAuthorize("@ss.hasPermi('business:warning:list')")
    @GetMapping("/videoReviewSectionDistribution")
    public AjaxResult videoReviewSectionDistribution(DcWarning dcWarning)
    {
        return AjaxResult.success(dcWarningService.selectVideoReviewSectionDistribution(dcWarning)) ;
    }
    @ApiOperation("查询视频审核事件源分布")
    // @PreAuthorize("@ss.hasPermi('business:warning:list')")
    @GetMapping("/videoReviewEventSource")
    public AjaxResult videoReviewEventSource(DcWarning dcWarning)
    {
        return AjaxResult.success(dcWarningService.videoReviewEventSource(dcWarning)) ;
    }
    @ApiOperation("查询视频")
    // @PreAuthorize("@ss.hasPermi('business:warning:list')")
    @GetMapping("/videoReviewEventSourceList")
    public TableDataInfo videoReviewEventSourceList(DcWarning dcWarning)
    {
        startPage();
        return getDataTable(dcWarningService.videoReviewEventSourceList(dcWarning)) ;
    }

    @PostMapping("/videoReviewEventSourceListExport")
    public void videoReviewEventSourceListExport(HttpServletResponse response, DcWarning dcWarning) throws UnsupportedEncodingException {
        List<DcWarning> list = dcWarningService.videoReviewEventSourceList(dcWarning);
        ExcelUtil<DcWarning> util = new ExcelUtil<>(DcWarning.class);
        util.exportExcel(response, list, "视频审核事件");

    }    @PostMapping("/videoReviewListExport")
    public void videoReviewListExport(HttpServletResponse response, DcWarning dcWarning) throws UnsupportedEncodingException {
        List<DcWarning> list = dcWarningService.videoReviewEventTimeList(dcWarning);
        ExcelUtil<DcWarning> util = new ExcelUtil<>(DcWarning.class);
        util.exportExcel(response, list, "视频审核事件");

    }


    @ApiOperation("查询视频审核事件时间")
    // @PreAuthorize("@ss.hasPermi('business:warning:list')")
    @GetMapping("/videoReviewEventTime")
    public AjaxResult videoReviewEventTime(DcWarning dcWarning)
    {
        return AjaxResult.success(dcWarningService.videoReviewEventTime(dcWarning)) ;
    }     @ApiOperation("查询视频审核事件时间列表")
    // @PreAuthorize("@ss.hasPermi('business:warning:list')")
    @GetMapping("/videoReviewEventTimeList")
    public TableDataInfo videoReviewEventTimeList(DcWarning dcWarning)
    {
        startPage();
        return getDataTable(dcWarningService.videoReviewEventTimeList(dcWarning)) ;
    }
    /**
     * 导出预警信息列表
     */
    //@PreAuthorize("@ss.hasPermi('business:warning:export')")
    @Log(title = "预警信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,@RequestBody DcWarning dcWarning) throws UnsupportedEncodingException {
        List<DcWarning> list = dcWarningService.export(dcWarning);
        ExcelUtil<DcWarning> util = new ExcelUtil<>(DcWarning.class);
        util.exportExcel(response, list, UniversalEnum.EARLY_WARNING_INFORMATION_DATA.getValue());

    }



    /**
     * 新增预警信息
     */
   // @PreAuthorize("@ss.hasPermi('business:warning:add')")
    @Log(title = "预警信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DcWarning dcWarning)
    {
        //设置事件Id UUID无下划线格式32
        String uuid = IdUtils.fastSimpleUUID();
        dcWarning.setId(uuid);
        return toAjax(dcWarningService.insertDcWarning(dcWarning));
    }

    /**
     * 修改预警信息
     */
   // @PreAuthorize("@ss.hasPermi('business:warning:edit')")
    @Log(title = "预警信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DcWarning dcWarning)
    {
        return toAjax(dcWarningService.updateDcWarning(dcWarning));
    }

    /**
     * 删除预警信息
     */
    //@PreAuthorize("@ss.hasPermi('business:warning:remove')")
    @Log(title = "预警信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String id)
    {
        return toAjax(dcWarningService.deleteDcWarningByIds(id));
    }

    //感知事件转交通事件
    @PostMapping("/updateWarningConvert")
    public AjaxResult updateWarningConvert(@RequestBody DcWarning dcWarning)
    {
        return dcWarningService.updateWarningConvert(dcWarning);
    }
    //感知事件删除
    @PostMapping("/delete")
    public AjaxResult deleteDcWarningByStringId(@RequestBody DcWarning dcWarning)
    {
        if (dcWarning==null){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        if (StringUtils.isBlank(dcWarning.getId())){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return toAjax(dcWarningService.deleteDcWarningByStringId(dcWarning));
    }
    /**
     *视频AI 上报 条件查询
     */

    @GetMapping("/selectDcWarningoTherConfiglist")
    public TableDataInfo selectDcWarningoTherConfig(DcWarning dcWarning)
    {
        startPage();
        List<HashMap<String,Object>> list = dcWarningService.selectDcWarningoTherConfig(dcWarning);
        return getDataTable(list);
    }

    @ApiOperation("感知事件批量转换")
    @PostMapping("/batchConvert")
    public AjaxResult batchConvert(@RequestBody  DcWarningBatchConvert dcWarningBatchConvert){

        return dcWarningService.batchConvert(dcWarningBatchConvert);
    }

    //1,指挥调度,查看是否存在记录和资源信息,存在即返回
    @PostMapping("/commandAndDispatch")
    public AjaxResult commandAndDispatch(@RequestBody DcWarning dcWarning){
        if (StringUtils.isBlank(dcWarning.getStakeMark())||StringUtils.isBlank(dcWarning.getId())){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return (dcWarningService.commandAndDispatch(dcWarning));
    }
    //2,指挥调度,当调度信息为空的时候调用智能分配资源
    @PostMapping("/intelligentSource")
    public AjaxResult intelligentSource(@RequestBody DcWarning dcWarning){
        if (StringUtils.isBlank(dcWarning.getStakeMark())){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return (dcWarningService.intelligentSource(dcWarning));
    }
    //3.指挥调度,新增调度记录信息
    @PostMapping("/insertDispatch")
    public AjaxResult insertDispatch(@RequestBody HashMap map){
        if (map == null || !map.containsKey("eventId")||StringUtils.isBlank(map.get("eventId").toString())){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return (dcWarningService.insertDispatch(map));
    }
    //4.指挥调度资源新增(用户修改弹窗的提交)
    @PostMapping("/updateSource")
    public AjaxResult insertDispatchSource(@RequestBody HashMap map){
        return toAjax(dcWarningService.insertDispatchSource(map));
    }
    //5.修改调度资源记录 1.查询记录id
//    @PostMapping("/selectDispatchId")
//    public AjaxResult selectDispatchId(@RequestBody HashMap map){
//        if (map == null || !map.containsKey("eventId")||StringUtils.isBlank(map.get("eventId").toString())){
//            return AjaxResult.error("参数错误");
//        }
//        return AjaxResult.success(dcWarningService.selectDispatchId(map.get("eventId").toString()));
//    }
    //5.修改调度资源记录 2.提交调度资源
    @PostMapping("/updateDispatchSource")
    public AjaxResult updateDispatch(@RequestBody HashMap map){
        if (map == null || !map.containsKey("dispatchId")||StringUtils.isBlank(map.get("dispatchId").toString())){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return toAjax(dcWarningService.updateDispatchSource(map));
    }
    //指挥调度记录修改
    @PostMapping("/updateDispatch")
    public AjaxResult insertDispatch(@RequestBody DcDispatch dcDispatch){
        if (dcDispatch.getOrganizationId()==null){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return toAjax(dcWarningService.insertDispatch(dcDispatch));
    }
    //感知事件误报
    @PostMapping("/falseAlarm")
    public AjaxResult falseAlarmResolution(@RequestBody DcWarning dcWarning){
        if (dcWarning==null||dcWarning.getRelieveType()==null||StringUtils.isBlank(dcWarning.getId())){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return toAjax(dcWarningService.falseAlarmResolution(dcWarning));
    }

    /**
     * 获取雷达事件视频
     *
     *
     */
    @GetMapping("/video/{id}")
    public AjaxResult getRadarIncidentVideo(@PathVariable("id") String id)throws Exception{

        return AjaxResult.success(dcWarningService.getRadarIncidentVideoUrl(id));
    }

    //首页气象预警,最近三天的数据
    @PostMapping("/meteorologicalList")
    public TableDataInfo selectStakeWarningTable(){
        startPage();
        List<DcNoStakeWarningTable> list = dcWarningService.selectStakeWarningTable();

        List<DcNoStakeWarningTable> updatedList = list.stream()
                .peek(warningTable -> {
                    if ("2".equals(warningTable.getWarningType())) {
                        JSONObject otherConfig = JSONObject.parseObject(warningTable.getOtherConfig());
                        String earlyWorningSignal = otherConfig.getString("earlyWorningSignal");
                        String[] split = earlyWorningSignal.split(UniversalEnum.YJ_STRING.getValue());
                        String content = WeatherTrafficProposeUtil.content(
                                Integer.parseInt(split[UniversalEnum.ONE.getNumber()]),
                                split[UniversalEnum.ZERO.getNumber()]
                        );
                        warningTable.setWarningDescription(warningTable.getWarningDescription() + "\n" + content);
                    }
                })
                .collect(Collectors.toList());

        return getDataTable(updatedList);
    }
    @ApiOperation("查询雷达事件视频回放列表")
    // @PreAuthorize("@ss.hasPermi('business:warning:list')")
    @GetMapping("/radarList")
    public TableDataInfo radarList(DcWarning dcWarning)
    {
        return getDataTable(dcWarningService.radarList(dcWarning)) ;
    }

}