package com.casic.missiles.modular.alarm.controller;

;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.casic.missiles.core.application.context.AbstractPermissionContext;
import com.casic.missiles.core.base.controller.ExportController;
import com.casic.missiles.core.datascope.DataScope;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.page.PageFactory;
import com.casic.missiles.core.util.EhcacheConstant;
import com.casic.missiles.model.response.ResponseData;
import com.casic.missiles.modular.alarm.model.RecordExcelDto;
import com.casic.missiles.modular.alarm.service.IAlarmRecordsService;
import com.casic.missiles.modular.system.enums.DeviceExportEnum;
import com.casic.missiles.modular.system.model.AlarmRecords;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author dev
 * @Date 2019-05-17 10:49:02
 */
@Controller
@RequestMapping("/alarm")
public class AlarmRecordsController extends ExportController {


    @Autowired
    private IAlarmRecordsService alarmRecordsService;
    @Resource
    private AbstractPermissionContext iCommonPermissionService;

    @Value("${smartcity.office.maxRowsExcel}")
    private int maxRowsExcel;
    @Value("${smartcity.config.config-path}")
    private String templatePath;
    @Value("${smartcity.adminRoleName}")
    private String sAdmin;
    @Value("${smartcity.opRoleName}")
    private String sOperator;

    /**
     * 获取分页列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object alarmList(HttpServletRequest httpServletRequest) {
        String keywords = httpServletRequest.getParameter("keywords");
        String beginTime = httpServletRequest.getParameter("beginTime");
        String endTime = httpServletRequest.getParameter("endTime");
        String statusStr = httpServletRequest.getParameter("status");
        String alarmTypeStr = httpServletRequest.getParameter("alarmType");
        String alarmContentStr = httpServletRequest.getParameter("alarmContentType");
        Page<Map<String, Object>> page = PageFactory.defaultPage();
        DataScope dataScope = iCommonPermissionService.getAuthService().getLoginUserDataScope();
        AuthUser currentUser = iCommonPermissionService.getAuthService().getLoginUser();
        if (!currentUser.getRoleTips().contains(sAdmin) && !currentUser.getRoleTips().contains(sOperator)) {
            alarmTypeStr = "1";
        }
        dataScope.setScopeName("bwi.DEPTID");
        List<Map<String, Object>> retList = alarmRecordsService.alarmList(page, keywords, beginTime, endTime, statusStr, alarmTypeStr, alarmContentStr, dataScope);
        retList.forEach(this::alarmRecordWrapper);
        page.setRecords(retList);
        return ResponseData.success(super.packForBT(page));
    }

    private void alarmRecordWrapper(Map<String, Object> map) {
        // 设置闸井相关字段
        String wellCode = map.get("wellCode").toString();
        Map<String, Object> wellInfoMap = EhcacheConstant.retBean().getWellInfoViaCode(wellCode);
        // 设置权属单位、负责人、联系电话
        String deptidStr = wellInfoMap.get("deptid").toString();
        long deptid = StrUtil.isEmpty(deptidStr) ? -1 : Long.valueOf(deptidStr);
        map.put("deptName", EhcacheConstant.retBean().getSimpleDeptNameById(deptid));
        if (deptid > 0) {
            Long staffstr = EhcacheConstant.retBean().getUserByDept(deptid);
            if (null == staffstr) {
                wellInfoMap.replace("staff", "");
                wellInfoMap.replace("tel", "");
            } else {
                Map<String, Object> userInfoMap = EhcacheConstant.retBean().getUserInfoById(staffstr);
                wellInfoMap.putAll(userInfoMap);
            }
        }
        map.putAll(wellInfoMap);

        // 告警类型
        String alarmTypeStr = map.get("alarmType").toString();
        map.put("alarmTypeName", EhcacheConstant.retBean().getAlarmTypeNameByCodeNum(alarmTypeStr));

        // 告警内容
        String alarmContentNameStr = map.get("alarmContentName").toString();
        map.put("alarmContent", EhcacheConstant.retBean().getAlarmContentByName(alarmContentNameStr));

        // 告警值加单位
        if (ObjectUtil.isNotEmpty(map.get("alarmValue"))) {
            String alarmValue = map.get("alarmValue").toString();
            String alarmContentName = map.get("alarmContentName").toString();
            if ("液位超限".equals(alarmContentName)) {
                alarmValue += "m";
                map.replace("alarmValue", alarmValue);
            }
            if ("浓度超限".equals(alarmContentName)) {
                alarmValue += "%LEL";
                map.replace("alarmValue", alarmValue);
            }
            if ("疑似开挖".equals(alarmContentName)) {
                alarmValue += "mg";
                map.replace("alarmValue", alarmValue);
            }
        }

        // 告警值
        if (alarmContentNameStr.contains("井盖") || "2".equals(alarmTypeStr)) {
            map.replace("alarmValue", "--");
        }

        // 告警状态
        String statusStr = map.get("status").toString();
        map.put("statusName", EhcacheConstant.retBean().getDictNameByCodeCodeNum(statusStr, "alarmStatus"));

        // 工单状态
        if (ObjectUtil.isNotEmpty(map.get("jobStatus"))) {
            String jobStatusStr = map.get("jobStatus").toString();
            map.put("jobStatusName", EhcacheConstant.retBean().getJobStatusNameByCodeNum(jobStatusStr));
        }
    }

    @RequestMapping(value = "/export")
    public void exportAlarm(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {

        String keywords = httpServletRequest.getParameter("keywords");
        String beginTime = httpServletRequest.getParameter("beginTime");
        String endTime = httpServletRequest.getParameter("endTime");
        String statusStr = httpServletRequest.getParameter("status");
        String alarmTypeStr = httpServletRequest.getParameter("alarmType");
        String alarmContentStr = httpServletRequest.getParameter("alarmContentType");

        Page<Map<String, Object>> page = PageFactory.defaultPage();
        page.setMaxLimit((long) maxRowsExcel);
        page.setSize(maxRowsExcel);
        page.offset();
        page.setSearchCount(false);
        DataScope dataScope = iCommonPermissionService.getAuthService().getLoginUserDataScope();
        AuthUser currentUser = iCommonPermissionService.getAuthService().getLoginUser();
        if (!currentUser.getRoleTips().contains(sAdmin) && !currentUser.getRoleTips().contains(sOperator)) {
            alarmTypeStr = "1";
        }
        List<Map<String, Object>> alarmExpList = alarmRecordsService.alarmList(page, keywords, beginTime, endTime, statusStr, alarmTypeStr, alarmContentStr, dataScope);
        alarmExpList.forEach(this::alarmRecordWrapper);
        List<RecordExcelDto> recordExcelDtoList = new ArrayList<>();
        alarmExpList.stream().forEach(
                alarmExp -> {
                    RecordExcelDto recordExcelDto = mapToObjcet(alarmExp);
                    recordExcelDtoList.add(recordExcelDto);
                }
        );
        super.exportExcel(RecordExcelDto.class, recordExcelDtoList, DeviceExportEnum.HARMFULDATA_EXPORT.getFileName());
    }

    private RecordExcelDto mapToObjcet(Map<String, Object> alarmExp) {
        RecordExcelDto recordExcelDto = new RecordExcelDto();
        recordExcelDto.setWellCode(alarmExp.get("wellCode").toString());
        recordExcelDto.setDevcode(alarmExp.get("devcode").toString());
        recordExcelDto.setPosition(alarmExp.get("position") == null ? "" : alarmExp.get("position").toString());
        recordExcelDto.setAlarmTypeName(alarmExp.get("alarmTypeName") == null ? "" : alarmExp.get("alarmTypeName").toString());
        recordExcelDto.setAlarmContentName(alarmExp.get("alarmContentName") == null ? "" : alarmExp.get("alarmContentName").toString());
        recordExcelDto.setAlarmLevel(alarmExp.get("alarmLevel") == null ? "" : alarmExp.get("alarmLevel").toString());
        recordExcelDto.setAlarmValue(alarmExp.get("alarmValue") == null ? "" : alarmExp.get("alarmValue").toString());
        recordExcelDto.setDeptName(alarmExp.get("deptName") == null ? "" : alarmExp.get("deptName").toString());
        recordExcelDto.setLogTime(alarmExp.get("alarmTime").toString());
        return recordExcelDto;
    }

    /**
     * 取消报警，即关闭工单
     */
    @RequestMapping(value = "/cancelAlarm")
    @ResponseBody
    public Object cancelAlarm(@RequestParam(value = "id", required = true) Long id, //jobId
                              @RequestParam(value = "jobStatus", required = true) String jobStatus,
                              @RequestParam(value = "handleMessage", required = true) String handleMessage) {
        Map<String, Object> retMap = new HashMap<>();
        AuthUser currentUser = iCommonPermissionService.getAuthService().getLoginUser();
        boolean isCancel = alarmRecordsService.cancelAlarm(id, jobStatus, handleMessage, currentUser.getId());
        if (isCancel) {
            return ResponseData.success();
        } else {
            return ResponseData.error("failure");
        }
    }

    /**
     * 批量消警
     */
    @RequestMapping(value = "/batchCancel")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Object batchCancel(@RequestParam(value = "keywords", required = false) String keywords,
                              @RequestParam(value = "alarmType", required = false) String alarmType,
                              @RequestParam(value = "alarmContent", required = false) String alarmContent,
                              @RequestParam(value = "beginTime", required = false) String beginTime,
                              @RequestParam(value = "endTime", required = false) String endTime,
                              @RequestParam(value = "jobStatus", required = true) String jobStatus,
                              @RequestParam(value = "handleMessage", required = true) String handleMessage) {
        Map<String, Object> retMap = new HashMap<>();
        //根据查询条件查询alarm_record记录
        DataScope dataScope = iCommonPermissionService.getAuthService().getLoginUserDataScope();
        AuthUser currentUser = iCommonPermissionService.getAuthService().getLoginUser();
        List<AlarmRecords> alarmRecords = alarmRecordsService.alarmListNoPage(dataScope, keywords, alarmType, alarmContent, beginTime, endTime);
        //根据jobId调用closeJob
        for (AlarmRecords alarmRecord : alarmRecords) {
            alarmRecordsService.cancelAlarm(Long.valueOf(alarmRecord.getJobId()), jobStatus, handleMessage, currentUser.getId());
        }
        return ResponseData.success();
    }

}
