package com.ozs.web.controller.accountmanagment;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ozs.common.annotation.Log;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysDictData;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.utils.AppendUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.poi.ExcelUtil;
import com.ozs.entity.*;
import com.ozs.entity.vo.MsgAlarmResp;
import com.ozs.entity.vo.MsgAlarmVo;
import com.ozs.mapper.MsgAlarmMapper;
import com.ozs.service.*;
import com.ozs.system.service.DataScoreUtil;
import com.ozs.system.service.ISysDeptService;
import com.ozs.system.service.ISysDictDataService;
import com.ozs.system.service.ISysDictTypeService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 报警信息表 前端控制器
 * </p>
 *
 * @author ozs
 * @since 2023-02-22
 */
@RestController
@RequestMapping("/service/msgAlarm")
public class MsgAlarmController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(MsgAlarmController.class);
    @Resource
    MsgAlarmService msgAlarmService;
    @Resource
    MsgAlarmMapper msgAlarmMapper;
    @Resource
    MsgAlarmFrequencyService msgAlarmFrequencyService;
    @Autowired
    BaseCameraManagementService baseCameraManagementService;
    @Autowired
    BaseRailwayManagementService baseRailwayManagementService;
    @Autowired
    private MsgWebPushService msgWebPushService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private DataScoreUtil dataScoreUtil;
    @Resource
    private BaseUserService baseUserService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * web更多消息-总数，已读数
     */
    @PostMapping("/messageMoreNum")
    @ApiOperation("更多消息--总数，已读数")
    @Log(title = "报警信息管理", businessType = BusinessType.SELECT)
    public AjaxResult messageMoreNum(@RequestBody MsgAlarmVo msgAlarmVo) {
        // MsgAlarmVo msgAlarmVo1 = (MsgAlarmVo) dataScoreUtil.setDataScore(getUserId(), msgAlarmVo);
        Map<String, Integer> messageMore = msgWebPushService.messageMoreNum(getUserId());
        return AjaxResult.success(messageMore);
    }

    /**
     * web更多消息
     */
    @PostMapping("/messageMore")
    @ApiOperation("更多消息")
    @Log(title = "报警信息管理", businessType = BusinessType.SELECT)
    public AjaxResult messageMore(@RequestBody MsgAlarmVo msgAlarmVo) {
        // MsgAlarmVo msgAlarmVo1 = (MsgAlarmVo) dataScoreUtil.setDataScore(getUserId(), msgAlarmVo);
        String userId = getUserId();
        if (!StringUtils.isEmpty(userId)) {
            msgAlarmVo.setUserId(userId);
        }
        IPage<MsgAlarm> messageMore = msgWebPushService.messageMore(msgAlarmVo);
        return AjaxResult.success(messageMore);
    }

    /**
     * web报警未读消息个数+未读消息列表
     */
    @GetMapping("/webAlarm")
    @ApiOperation("app报警推送次数")
    @Log(title = "报警信息管理", businessType = BusinessType.SELECT)
    public AjaxResult webAlarmNum() {
        // MsgAlarmVo msgAlarm = (MsgAlarmVo) dataScoreUtil.setDataScore(getUserId(), new MsgAlarmVo());
        Map webAlarm = msgWebPushService.webAlarm(getUserId());
        return AjaxResult.success(webAlarm);
    }

    /**
     * web消息全部已读
     */
    @PostMapping("/readAll")
    @ApiOperation(value = "web消息全部已读")
    @Log(title = "报警信息管理", businessType = BusinessType.SELECT)
    public AjaxResult readAll() {
        return toAjax(msgWebPushService.readAll(getUserId()));
    }

    /**
     * web消息已读
     */
    @PostMapping("/read")
    @ApiOperation(value = "web消息已读")
    @Log(title = "报警信息管理", businessType = BusinessType.SELECT)
    public AjaxResult read(@RequestBody MsgWebPush msgWebPush) {
//        if (StringUtils.isEmpty(msgWebPush) || ObjectUtils.isEmpty(msgWebPush.getPushId())) {
//            return AjaxResult.error("PushId不能为空！");
//        }
        return toAjax(msgWebPushService.read(msgWebPush));
    }

    /**
     * 报警信息分页
     *
     * @param msgAlarmVo
     * @return
     */
    @ApiOperation(value = "报警信息分页")
    @PostMapping("/list")
    @Log(title = "报警信息管理", businessType = BusinessType.SELECT)
    public AjaxResult selectMsgAlarm(@RequestBody MsgAlarmVo msgAlarmVo) {
        msgAlarmVo = (MsgAlarmVo) dataScoreUtil.setDataScore(getUserId(), msgAlarmVo);
        if (!ObjectUtils.isEmpty(msgAlarmVo.getAlarmMile())) {
            msgAlarmVo.setAlarmMile(msgAlarmVo.getAlarmMile() * 1000);
        }
        if (!ObjectUtils.isEmpty(msgAlarmVo.getBeginMile())) {
            msgAlarmVo.setBeginMile(msgAlarmVo.getBeginMile() * 1000);
        }
        if (!ObjectUtils.isEmpty(msgAlarmVo.getEndMile())) {
            msgAlarmVo.setEndMile(msgAlarmVo.getEndMile() * 1000);
        }
        IPage<MsgAlarm> page = msgAlarmService.queryPage(msgAlarmVo);
        page.setTotal(page.getTotal());
        page.setCurrent(page.getCurrent());
        page.setPages(page.getPages());

        if (!ObjectUtils.isEmpty(page) && page.getRecords().size() > 0) {
            List<MsgAlarm> dto1 = page.getRecords().stream().map(o -> {
                LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
                if (!ObjectUtils.isEmpty(o.getRailwayCode())) {
                    queryWrapper.eq(BaseRailwayManagement::getRailwayCode, o.getRailwayCode());
                }
                BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
                o.setRailwayName(baseRailwayManagement.getRailwayName());
                if (StringUtils.isNotEmpty(o.getReleasedBy())) {
                    BaseUser user = baseUserService.getUser(o.getReleasedBy());
                    o.setReleasedByName(user.getNickName());
                }
                String mils = AppendUtils.stringAppend(o.getAlarmMile());
                o.setAlarmMiles(mils);
                o.setLineDirName(o.getLineDir() == 1 ? "上行" : "下行");
                List<SysDictData> data = dictTypeService.selectDictDataByType("sys_alarm_type");
                data.stream().forEach(sysDictData -> {
                    if (sysDictData.getDictValue().equals(o.getAlarmType().toString())) {
                        o.setAlarmTypeName(sysDictData.getDictLabel());
                    }
                });
//                LambdaQueryWrapper<MsgAlarmFrequency> wrapper = new LambdaQueryWrapper<MsgAlarmFrequency>();
//                if (!ObjectUtils.isEmpty(o.getAlarmId())) {
//                    wrapper.eq(MsgAlarmFrequency::getAlarmId, o.getAlarmId());
//                }
//                 o.setAlarmCount((int) msgAlarmFrequencyService.count(wrapper));
                return o;
            }).collect(Collectors.toList());
            page.setRecords(dto1);
        }
        return AjaxResult.success(page);
    }

    /**
     * 导出报警消息
     *
     * @param response
     */
    @ApiOperation("导出报警消息")
    @PostMapping("/exportMsgAlarm")
    @Log(title = "报警信息管理", businessType = BusinessType.EXPORT)
    public void exportMsgAlarm(HttpServletResponse response, @RequestBody MsgAlarmVo msgAlarmVo) {
        msgAlarmVo = (MsgAlarmVo) dataScoreUtil.setDataScore(getUserId(), msgAlarmVo);
        if (!ObjectUtils.isEmpty(msgAlarmVo.getAlarmMile())) {
            msgAlarmVo.setAlarmMile(msgAlarmVo.getAlarmMile() * 1000);
        }
        if (!ObjectUtils.isEmpty(msgAlarmVo.getBeginMile())) {
            msgAlarmVo.setBeginMile(msgAlarmVo.getBeginMile() * 1000);
        }
        if (!ObjectUtils.isEmpty(msgAlarmVo.getEndMile())) {
            msgAlarmVo.setEndMile(msgAlarmVo.getEndMile() * 1000);
        }
        List<MsgAlarm> msgAlarmList = msgAlarmService.msgAlarmList(msgAlarmVo);
        for (MsgAlarm msgAlarm : msgAlarmList) {
//            String[] split = msgAlarm.getImageUrl().split(";");
//            ArrayList<String> objects = new ArrayList<>(Arrays.asList(split));
//            msgAlarm.setImageUrls(objects);
//            LambdaQueryWrapper<BaseCameraManagement> cameraManagementLambdaQueryWrapper = new LambdaQueryWrapper<BaseCameraManagement>();
//            if (!ObjectUtils.isEmpty(msgAlarm.getCameraCode())) {
//                cameraManagementLambdaQueryWrapper.eq(BaseCameraManagement::getCameraCode, msgAlarm.getCameraCode());
//            }
//            BaseCameraManagement cameraManagement = baseCameraManagementService.getOne(cameraManagementLambdaQueryWrapper);
//            LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
//            if (!ObjectUtils.isEmpty(cameraManagement.getRailwayCode())) {
//                queryWrapper.eq(BaseRailwayManagement::getRailwayCode, cameraManagement.getRailwayCode());
//            }
//            BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
//            msgAlarm.setRailwayName(baseRailwayManagement.getRailwayName());
//            if (StringUtils.isNotEmpty(msgAlarm.getReleasedBy())) {
//                BaseUser user = baseUserService.getUser(msgAlarm.getReleasedBy());
//                msgAlarm.setReleasedByName(user.getNickName());
//            }
//            String mils = AppendUtils.stringAppend(cameraManagement.getInstallMile());
//            msgAlarm.setAlarmMiles(mils);
//            String end = AppendUtils.stringAppend(cameraManagement.getEndMile());
//            msgAlarm.setEndMile(end);
//            String begin = AppendUtils.stringAppend(cameraManagement.getBeginMile());
//            msgAlarm.setBeginMile(begin);
//            LambdaQueryWrapper<MsgAlarmFrequency> wrapper = new LambdaQueryWrapper<MsgAlarmFrequency>();
//            if (!ObjectUtils.isEmpty(msgAlarm.getAlarmId())) {
//                wrapper.eq(MsgAlarmFrequency::getAlarmId, msgAlarm.getAlarmId());
//            }
//            msgAlarm.setAlarmCount((int) msgAlarmFrequencyService.count(wrapper));
//            msgAlarm.setLineDirName(msgAlarm.getLineDir() == 1 ? "上行" : "下行");
//            msgAlarm.setIsReleaseName(msgAlarm.getIsRelease() == 1 ? "已解除" : "未解除");
//            msgAlarm.setAlarmTypeName("泥石流");
        }
        ExcelUtil<MsgAlarm> util = new ExcelUtil<>(MsgAlarm.class);
        util.exportExcel(response, msgAlarmList, "报警信息管理");
    }

    @GetMapping(value = "/getByAlarmId/{alarmId}")
    @ApiOperation("根据报警信息ID获取详细信息-app")
    @Log(title = "报警信息管理", businessType = BusinessType.MESSAGE)
    public AjaxResult getByAlarmId(@PathVariable String alarmId) {
        MsgAlarm msgAlarm = msgAlarmService.getByAlarmId(alarmId);
        if (!ObjectUtils.isEmpty(msgAlarm)) {
//            LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
//            if (!ObjectUtils.isEmpty(msgAlarm.getCameraCode())) {
//                lw.eq(BaseCameraManagement::getCameraCode, msgAlarm.getCameraCode());
//            }
//            BaseCameraManagement baseCameraManagement = baseCameraManagementService.getOne(lw);
//            LambdaQueryWrapper<BaseRailwayManagement> wrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
//            if (!ObjectUtils.isEmpty(baseCameraManagement.getRailwayCode())) {
//                wrapper.eq(BaseRailwayManagement::getRailwayCode, baseCameraManagement.getRailwayCode());
//            }
//            BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(wrapper);
            MsgAlarmResp msgAlarmResp = new MsgAlarmResp();
//            String[] split = msgAlarm.getImageUrl().split(";");
//            ArrayList<String> objects = new ArrayList<>(Arrays.asList(split));
//            msgAlarm.setImageUrls(objects);
//            if (StringUtils.isNotEmpty(msgAlarm.getReleasedBy())) {
//                BaseUser user = baseUserService.getUser(msgAlarm.getReleasedBy());
//                msgAlarm.setReleasedByName(user.getNickName());
//            }
//            BeanUtils.copyProperties(msgAlarm, msgAlarmResp);
//            msgAlarmResp.setRailwayName(baseRailwayManagement.getRailwayName());
//            msgAlarmResp.setDeptId(baseCameraManagement.getDeptId());
//            String begin = AppendUtils.stringAppend(baseCameraManagement.getBeginMile());
//            String end = AppendUtils.stringAppend(baseCameraManagement.getEndMile());
//            String endMile = begin + "-" + end;
//            msgAlarmResp.setBeginMile(endMile);
//            String mile = AppendUtils.stringAppend(baseCameraManagement.getInstallMile());
//            msgAlarmResp.setAlarmMile(mile);
//            msgAlarmResp.setInstallLongitude(baseCameraManagement.getInstallLongitude() + "," + baseCameraManagement.getInstallLatitude());
            return AjaxResult.success(msgAlarmResp);
        } else {
            return success("无报警信息数据");
        }
    }

    @GetMapping(value = "/{id}")
    @ApiOperation("根据报警信息ID获取详细信息")
    @Log(title = "报警信息管理", businessType = BusinessType.MESSAGE)
    public AjaxResult getInfo(@PathVariable Long id) {
        MsgAlarm msgAlarm = msgAlarmService.getById(id);
        if (!ObjectUtils.isEmpty(msgAlarm)) {
//            LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
//            if (!ObjectUtils.isEmpty(msgAlarm.getCameraCode())) {
//                lw.eq(BaseCameraManagement::getCameraCode, msgAlarm.getCameraCode());
//            }
//            BaseCameraManagement baseCameraManagement = baseCameraManagementService.getOne(lw);
            LambdaQueryWrapper<BaseRailwayManagement> wrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
            if (!ObjectUtils.isEmpty(msgAlarm.getRailwayCode())) {
                wrapper.eq(BaseRailwayManagement::getRailwayCode, msgAlarm.getRailwayCode());
            }
            BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(wrapper);
            MsgAlarmResp msgAlarmResp = new MsgAlarmResp();
//            String[] split = msgAlarm.getImageUrl().split(";");
//            ArrayList<String> objects = new ArrayList<>(Arrays.asList(split));
//            msgAlarm.setImageUrls(objects);
//            if (StringUtils.isNotEmpty(msgAlarm.getReleasedBy())) {
//                BaseUser user = baseUserService.getUser(msgAlarm.getReleasedBy());
//                msgAlarm.setReleasedByName(user.getNickName());
//            }
            BeanUtils.copyProperties(msgAlarm, msgAlarmResp);
            msgAlarmResp.setRailwayName(baseRailwayManagement.getRailwayName());
//            msgAlarmResp.setDeptId(baseCameraManagement.getDeptId());
//            String begin = AppendUtils.stringAppend(baseCameraManagement.getBeginMile());
//            String end = AppendUtils.stringAppend(baseCameraManagement.getEndMile());
//            String endMile = "[" + begin + "]-[" + end + "]";
//            msgAlarmResp.setBeginMile(endMile);
            String mile = AppendUtils.stringAppend(msgAlarm.getAlarmMile());
            msgAlarmResp.setAlarmMile(mile);
            msgAlarmResp.setLineDirStr(msgAlarm.getLineDir() == 1 ? "上行" : "下行");
            List<SysDictData> data = dictTypeService.selectDictDataByType("sys_alarm_type");
            data.stream().forEach(sysDictData -> {
                if (sysDictData.getDictValue().equals(msgAlarm.getAlarmType().toString())) {
                    msgAlarmResp.setAlarmTypeName(sysDictData.getDictLabel());
                }
            });
//            msgAlarmResp.setInstallLongitude(msgAlarm.getInstallLongitude() + "," + baseCameraManagement.getInstallLatitude());
//            SysDept sysDept = deptService.selectDeptById(baseCameraManagement.getDeptId());
//            msgAlarmResp.setDeptName(sysDept.getDeptName());
            return AjaxResult.success(msgAlarmResp);
        } else {
            return success("无报警信息数据");
        }
    }

    @PutMapping(value = "/updateIsRelease")
    @ApiOperation("根据报警信息ID解除报警")
    @Log(title = "报警信息管理", businessType = BusinessType.UPDATE)
    public AjaxResult updateIsRelease(@RequestParam(value = "id") Long id) {
        MsgAlarm msgAlarm = msgAlarmService.getById(id);
        msgAlarm.setIsRelease(1);
        msgAlarm.setUpdateBy(getUserId());
        msgAlarm.setReleasedBy(getUserId());
        msgAlarm.setReleasedTime(new Date());
        return AjaxResult.success(msgAlarmService.updateById(msgAlarm));
    }

    @GetMapping(value = "/alarmHistoricalAlarm/{alarmId}")
    @ApiOperation("报警消息详情历史报警次数信息")
    @Log(title = "报警信息管理", businessType = BusinessType.SELECT)
    public AjaxResult alarmHistoricalAlarm(@PathVariable Long alarmId) {
        QueryWrapper<MsgAlarmFrequency> wrapper = new QueryWrapper<>();
        wrapper.eq("alarm_id", alarmId);
        wrapper.orderByDesc("alarm_time");
        List<MsgAlarmFrequency> list = msgAlarmFrequencyService.list(wrapper);
        return AjaxResult.success(list);
    }

    @GetMapping(value = "/videoHistoricalAlarm/{cameraCode}")
    @ApiOperation("视频服务历史报警信息")
    @Log(title = "报警信息管理", businessType = BusinessType.SELECT)
    public AjaxResult videoHistoricalAlarm(@PathVariable String cameraCode) {
        QueryWrapper<MsgAlarm> wrapper = new QueryWrapper<>();
        wrapper.eq("camera_code", cameraCode);
        wrapper.orderByDesc("alarm_time");
        List<MsgAlarm> list = msgAlarmService.list(wrapper);
        return AjaxResult.success(list);
    }
}

