package com.yeejoin.amos.boot.module.jcs.biz.controller;

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.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.feign.LatentDangerFeignClient;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlarmGiveStatisticsDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ESAlertCalledDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ESAlertCalledRequestDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.FireAndDutyAndIOTDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.jcs.api.enums.AlertStatusEnum;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertCalledServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertFormValueServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.ESAlertCalledService;
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.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.component.event.RestEventTrigger;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 警情接警记录
 *
 * @author tb
 * @date 2021-06-17
 */
@RestController
@Api(tags = "警情接警记录Api")
@RequestMapping(value = "/alert-called")
public class AlertCalledController extends BaseController {

    @Autowired
    LatentDangerFeignClient latentDangerFeignClient;
    @Autowired
    EquipFeignClient equipFeignClient;
    @Autowired
    AlertCalledServiceImpl iAlertCalledService;
    @Autowired
    AlertFormValueServiceImpl iAlertFormValueService;
    @Autowired
    private ESAlertCalledService eSAlertCalledService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    DataDictionaryServiceImpl dataDictionaryService;
    @Autowired
    OrgUsrServiceImpl iOrgUsrService;
    @Value("${redis.cache.failure.time}")
    private long time;

    private static String ALETR_TYPE_AID = "1214";
    private static String ALETR_TYPE_AID_STATUS = "patientStatus";

    /**
     * 新增警情接警记录
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增警情接警记录", notes = "新增警情接警记录")
    @Transactional
    public ResponseModel<AlertCalled> saveAlertCalled(@RequestBody AlertCalledObjsDto alertCalledObjsDto) throws Exception {

        if (ValidationUtil.isEmpty(alertCalledObjsDto)
                || ValidationUtil.isEmpty(alertCalledObjsDto.getAlertCalled()))
            throw new BadRequest("参数校验失败.");
        ReginParams reginParams = getSelectedOrgInfo();
        //获取当前登录人公司
        String name = reginParams.getCompany().getCompanyName();
        AlertCalled alertCalled = alertCalledObjsDto.getAlertCalled();
        alertCalled.setCompanyName(name);
        if (alertCalled.getAlertTypeCode().equals(ALETR_TYPE_AID)) {
            List<AlertFormValue> alertFormValue = alertCalledObjsDto.getAlertFormValue();
            alertFormValue.forEach(e -> {
                if (e.getFieldCode().equals(ALETR_TYPE_AID_STATUS)) {
                    if (e.getFieldValueCode() != null) {
                        if (e.getFieldValueCode().contains(",")) {
                            String[] split = e.getFieldValueCode().split(",");
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int i = 0; i < split.length; i++) {
                                DataDictionary hzxz = dataDictionaryService.getByCode(split[i], "HZXZ");
                                stringBuilder.append(hzxz.getName() + " ");
                                e.setFieldValue(stringBuilder.toString());
                            }
                        } else {
                            DataDictionary hzxz = dataDictionaryService.getByCode(e.getFieldValueCode(), "HZXZ");
                            e.setFieldValue(hzxz.getName());
                        }
                    }
                }
            });
            alertCalledObjsDto.setAlertFormValue(alertFormValue);
        }
        alertCalledObjsDto.setAlertCalled(alertCalled);
        alertCalledObjsDto = iAlertCalledService.createAlertCalled(alertCalledObjsDto);
        return ResponseHelper.buildResponse(alertCalledObjsDto.getAlertCalled());
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean deleteById(@PathVariable Long id) {
        return iAlertCalledService.removeById(id);
    }

    /**
     * 修改警情接警记录
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/updateById")
    @ApiOperation(httpMethod = "PUT", value = "修改警情接警记录", notes = "修改警情接警记录")
    public boolean updateByIdAlertCalled(@RequestBody AlertCalled alertCalled) {
        return iAlertCalledService.updateById(alertCalled);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/find/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<Object> selectById(@PathVariable Long id) {

        return ResponseHelper.buildResponse(iAlertCalledService.selectAlertCalledById(id));

    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/list")
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<AlertCalled>> listPage(String pageNum, String pageSize, String sort, AlertCalled alertCalled, Integer alertStatus,
                                                      String alertTypeCode,
                                                      String alertSourceCode,
                                                      String callTimeStart,
                                                      String callTimeEnd,
                                                      String isFatherAlert) {
       /* Page<AlertCalled> pageBean;
        IPage<AlertCalled> page;
        QueryWrapper<AlertCalled> alertCalledQueryWrapper = new QueryWrapper<>();
        page = iAlertCalledService.page(pageBean, alertCalledQueryWrapper);
        return ResponseHelper.buildResponse(page);
        setQueryWrapper(alertCalledQueryWrapper, alertCalled,sort); */
        /*分页存在问题 修改分页参数 陈召 2021-09-22 开始*/
        Page<AlertCalled> page = new Page<>();
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            page = new Page<>();
            page.setCurrent(0L);
            page.setSize(Long.MAX_VALUE);
        } else {
            page.setCurrent((Long.parseLong(pageNum) - 1) * Long.parseLong(pageSize));
            page.setSize(Long.parseLong(pageSize));
        }
        /*分页存在问题 修改分页参数 陈召 2021-09-22 结束*/

        /* bug2407 表头筛选失效 补充条件方法 XML中添加了排序条件判断  data代表排序条件 lift 升降序 陈召 2021-09-03 开始*/
        /* bug2408 筛选参数解析异常  修改筛选条件方法 修改入参分离筛选条件
        alertStatus 警情状态  alertTypeCode 报警类型code  alertSourceCode 警情来源code
        陈召 2021-08-21 开始*/
        IPage<AlertCalled> alertCalledIPage = null;

        alertCalledIPage = iAlertCalledService.queryForCalledList(page, alertStatus, alertTypeCode, alertSourceCode, callTimeStart, callTimeEnd, sort,isFatherAlert);
        /*  bug  2406   接警记录，列表缺少警情状态字段  by litw start*/
        alertCalledIPage.getRecords().stream().forEach(e -> {
            if (e.getAlertStatus()) {
                e.setAlertStatusStr(AlertStatusEnum.CLOSED.getName());
            } else {
                e.setAlertStatusStr(AlertStatusEnum.UNCLOSED.getName());
            }
        });
        /*  bug  2406   接警记录，列表缺少警情状态字段  by litw end*/
        return ResponseHelper.buildResponse(alertCalledIPage);
        /* bug2408 筛选参数解析异常  修改筛选条件方法 陈召 2021-08-21 结束*/
        /* bug2407 表头筛选失效 补充条件方法 XML中添加了排序条件判断  data代表排序条件 lift 升降序 陈召 2021-09-03 结束*/
    }

    /**
     * <pre>
     * 相似警情分页查询
     * </pre>
     *
     * @param
     * @param current
     * @param size
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "相似警情分页查询")
    @PostMapping(value = "/page/similar")
    public ResponseModel<Page<ESAlertCalledDto>> pageBySimilar(
            @RequestBody ESAlertCalledRequestDto alertCalledVo,
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size) throws Exception {
        /*bug 3090 警情填报，相似警情中响应级别错误显示为code 2021-10-13 chenzhao */
        Page<ESAlertCalledDto> esAlertCalledDtoPage = eSAlertCalledService.queryByKeys(alertCalledVo, current, size);
        List<ESAlertCalledDto> records = esAlertCalledDtoPage.getRecords();

        for (ESAlertCalledDto record : records) {
            if (record.getResponseLevelCode() != null) {
                DataDictionary byCode = dataDictionaryService.getByCode(record.getResponseLevelCode(), "XYJBR");
                record.setResponseLevel(byCode.getName());
            }
        }
        /*bug 3090 警情填报，相似警情中响应级别错误显示为code 2021-10-13 chenzhao */
        return ResponseHelper.buildResponse(esAlertCalledDtoPage);
    }

    /**
     * <pre>
     * 初始化ES
     * </pre>
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "初始化ES")
    @PutMapping(value = "/es/init")
    public ResponseModel<Boolean> initEs() throws Exception {
        return ResponseHelper.buildResponse(eSAlertCalledService.initEs());
    }

    /**
     * 列表无分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getList")
    @ApiOperation(httpMethod = "GET", value = "列表无分页查询", notes = "列表无分页查询")
    public ResponseModel<List<AlertCalled>> list(AlertCalled alertCalled) {
        QueryWrapper<AlertCalled> alertCalledQueryWrapper = new QueryWrapper<>();
        setQueryWrapper(alertCalledQueryWrapper, alertCalled, null);
        List<AlertCalled> list = iAlertCalledService.list(alertCalledQueryWrapper);
        return ResponseHelper.buildResponse(list);
    }

    private QueryWrapper<AlertCalled> setQueryWrapper(QueryWrapper<AlertCalled> queryWrapper, AlertCalled alertCalled, String sort) {
        Class<? extends AlertCalled> aClass = alertCalled.getClass();
        queryWrapper.eq("is_delete", 0);

        if (sort != null) {
            String[] date = sort.split(",");
            if (date[1].equals("ascend")) {
                queryWrapper.orderByAsc(RedisKey.humpToLine(date[0]));
            } else {
                queryWrapper.orderByDesc(RedisKey.humpToLine(date[0]));
            }
        } else {
            queryWrapper.orderByDesc("call_time");
        }

        if (alertCalled.getCallTimeStart() != null && alertCalled.getCallTimeEnd() != null) {
            queryWrapper.between("call_time", alertCalled.getCallTimeStart(), alertCalled.getCallTimeEnd());
        }
        if (alertCalled.getIsFatherAlert()) { // 0：接警；1：处警
            queryWrapper.isNull("father_alert");
        }
        if (!ValidationUtil.isEmpty(alertCalled.getAlertSourceCodeStr())) {
            String[] arr = alertCalled.getAlertSourceCodeStr().split(",");
            List<String> collect = Arrays.stream(arr).collect(Collectors.toList());
            queryWrapper.in("alert_source_code", collect);
        }
        Stream<Field> fieldStream = Arrays.stream(aClass.getDeclaredFields()).filter(field -> {
            String name = NameUtils.camel2Underline(field.getName());
            return !("IS_FATHER_ALERT".equals(name) || "ALERT_SOURCE_CODE_STR".equals(name));
        });
        fieldStream.forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(alertCalled);
                if (o != null && !"serialVersionUID".equals(field.getName())) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(alertCalled);
                        queryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(alertCalled);
                        queryWrapper.eq(name, fileValue);
                    } else if (type.equals(Boolean.class)) {
                        Boolean fileValue = (Boolean) field.get(alertCalled);
                        queryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class) || "long".equals(type.toString())) {
                        Long fileValue = (Long) field.get(alertCalled);
                        queryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("系统异常");
            }
        });

        queryWrapper.or().eq("sequence_nbr",alertCalled.getFatherAlert());
        return queryWrapper;
    }

    /**
     * 查询指定日期内警情列表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/dateRange/list")
    @ApiOperation(httpMethod = "GET", value = "查询指定日期内警情列表", notes = "查询指定日期内警情列表")
    public ResponseModel<Map<String, Object>> listByDateRange(@RequestParam(value = "beginDate", required = false) String beginDate,
                                                              @RequestParam("endDate") String endDate) {
        return ResponseHelper.buildResponse(iAlertCalledService.getAlertInfoList(beginDate, endDate));
    }

    /**
     * <pre>
     * 设备联动紧急响应
     * 启动所有消防队伍的警铃、广播，并自动开启所有车库门
     * </pre>
     *
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/billsend")
    @ApiOperation(httpMethod = "POST", value = "设备联动紧急响应", notes = "启动所有消防队伍的警铃、广播，并自动开启所有车库门")
    @Transactional
    @RestEventTrigger(value = "opreateLogEventHandler")
    public ResponseModel<Boolean> controlEquip() throws Exception {

        return ResponseHelper.buildResponse(iAlertCalledService.controlEquip());
    }

    /**
     * 警情重新定位
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/reLocate")
    @ApiOperation(httpMethod = "PUT", value = "警情重新定位", notes = "警情重新定位")
    public ResponseModel<Boolean> reLocateById(@RequestParam String alertCalled, @RequestParam String longitude,
                                               @RequestParam String latitude) {
        return ResponseHelper.buildResponse(iAlertCalledService.reLocate(alertCalled, longitude, latitude));
    }
    /*2304 地址 联系人模糊查询缺失  陈召 2021-09-23 开始*/

    /**
     * 警情填报联系人模糊查询
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getAmosId", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "警情填报联系人模糊查询", notes = "警情填报联系人模糊查询")
    public ResponseModel<Object> getContact() {

//        if (redisUtils.hasKey(RedisKey.CONTACT_USER)) {
//            Object obj = redisUtils.get(RedisKey.CONTACT_USER);
//            return ResponseHelper.buildResponse(obj);
//        } else {
            List<Map<String, String>> contactName = iAlertCalledService.getContactName();
           // redisUtils.set(RedisKey.CONTACT_USER, contactName, time);
            return ResponseHelper.buildResponse(contactName);
        
    }

    /**
     * 警情填报地址模糊查询
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getAddress", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "警情填报地址模糊查询", notes = "警情填报地址模糊查询")
    public ResponseModel<List<String>> getAddress() {

        return ResponseHelper.buildResponse(iAlertCalledService.getCalledAddress());
    }
    /*2304 地址 联系人模糊查询缺失  陈召 2021-09-23 结束*/

    /**
     * 警情填报地址模糊查询
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getAlarmGiveStatistics", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "app领导统计", notes = "app领导统计")
    public ResponseModel<AlarmGiveStatisticsDto> getAlarmGiveStatistics() {
        AlarmGiveStatisticsDto dto = new AlarmGiveStatisticsDto();
        LambdaQueryWrapper<AlertCalled> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(AlertCalled::getFatherAlert);
        queryWrapper.eq(AlertCalled::getAlertStatus, false);
        queryWrapper.eq(AlertCalled::getIsDelete, false);
        Integer alertNum = iAlertCalledService.getBaseMapper().selectCount(queryWrapper);
        dto.setAlarmNum(alertNum);

        ResponseModel<Map<String, Object>> fireAlarm = equipFeignClient.getFireAlarm();
        Map<String, Object> map = fireAlarm.getResult();
        int fireAlarmNum = !ValidationUtil.isEmpty(map.get("FireAlarmNum")) ? Integer.valueOf(map.get("FireAlarmNum").toString()) : 0;

        ResponseModel<Map<String, Object>> faultAlarm = equipFeignClient.getFaultAlarm();
        map = faultAlarm.getResult();
        int faultAlarmNum = !ValidationUtil.isEmpty(map.get("FaultAlarmNum")) ? Integer.valueOf(map.get("FaultAlarmNum").toString()) : 0;

        ResponseModel<Map<String, Object>> monitorEvent = equipFeignClient.getMonitorEvent();
        map = monitorEvent.getResult();
        int monitorEventNum = !ValidationUtil.isEmpty(map.get("monitorEventNum")) ? Integer.valueOf(map.get("monitorEventNum").toString()) : 0;

        dto.setIotDetection(fireAlarmNum + faultAlarmNum + monitorEventNum);

        ResponseModel<Object> currentHiddenDanger = latentDangerFeignClient.getUnFinishedDangerCount();
        Integer currentHiddenDangerNum = (Integer) currentHiddenDanger.getResult();
        dto.setCurrentHiddenDanger(currentHiddenDangerNum);

        dto.setAllNum(dto.getAlarmNum() + dto.getIotDetection() + currentHiddenDangerNum);

        return ResponseHelper.buildResponse(dto);
    }

    /**
     * 消防报警，在岗检测，物联告警
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getFireAndDutyAndIOT", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "消防报警，在岗检测，物联告警", notes = "消防报警，在岗检测，物联告警")
    public ResponseModel<FireAndDutyAndIOTDto> getFireAndDutyAndIOT() {
        FireAndDutyAndIOTDto dto = new FireAndDutyAndIOTDto();


        ResponseModel<Map<String, Object>> fireAlarm = equipFeignClient.getFireAlarm();
        Map<String, Object> map = fireAlarm.getResult();
        int fireAlarmNum = !ValidationUtil.isEmpty(map.get("FireAlarmNum")) ? Integer.valueOf(map.get("FireAlarmNum").toString()) : 0;

        ResponseModel<Map<String, Object>> faultAlarm = equipFeignClient.getFaultAlarm();
        map = faultAlarm.getResult();
        int faultAlarmNum = !ValidationUtil.isEmpty(map.get("FaultAlarmNum")) ? Integer.valueOf(map.get("FaultAlarmNum").toString()) : 0;

        ResponseModel<Map<String, Object>> monitorEvent = equipFeignClient.getMonitorEvent();
        map = monitorEvent.getResult();
        int monitorEventNum = !ValidationUtil.isEmpty(map.get("monitorEventNum")) ? Integer.valueOf(map.get("monitorEventNum").toString()) : 0;

        dto.setFireNum(fireAlarmNum);
        dto.setFaultAlarmNum(faultAlarmNum);
        dto.setIotNum(monitorEventNum);

        return ResponseHelper.buildResponse(dto);
    }

    /**
     * 获取坐席情况
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getLocation")
    @ApiOperation(httpMethod = "GET", value = "模糊获取地址的方法", notes = "模糊获取地址的方法")
    public ResponseModel<Object> getLocationLike(@RequestParam(required = false) String locationt) {
        return ResponseHelper.buildResponse(iAlertCalledService.getLocationLike(locationt));
    }
}