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

import com.baomidou.mybatisplus.plugins.Page;
import com.casic.missiles.core.base.response.ResponseData;
import com.casic.missiles.core.common.service.ICommonPermissionService;
import com.casic.missiles.core.datascope.DataScope;
import com.casic.missiles.core.shiro.ShiroUser;
import com.casic.missiles.core.util.ToolUtil;
import com.casic.missiles.modular.alarm.service.IAlarmRecordsService;
import com.casic.missiles.modular.system.model.AlarmRecords;
import com.casic.missiles.modular.system.warpper.AlarmRecordWarpper;
import com.casic.missiles.core.base.controller.BaseController;
import com.casic.missiles.core.common.constant.factory.PageFactory;
import org.json.JSONException;
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 org.hswebframework.expands.office.excel.ExcelIO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
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 BaseController {


    @Autowired
    private IAlarmRecordsService alarmRecordsService;
    @Autowired
    private ICommonPermissionService 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 = new PageFactory<Map<String,Object>>().defaultPage("alarmTime",false);
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();

        if (!currentUser.getRoleTips().contains(sAdmin) && !currentUser.getRoleTips().contains(sOperator)) {
            alarmTypeStr = "1";
        }
        List<Map<String,Object>> retList = alarmRecordsService.alarmList(page,keywords,beginTime,endTime,statusStr,alarmTypeStr,alarmContentStr,dataScope);


        new AlarmRecordWarpper(retList).warp();
        page.setRecords(retList);

        return ResponseData.success(super.packForBT(page));
    }


    @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 = new PageFactory<Map<String,Object>>().defaultPage("alarmTime",false);
        page.setLimit(maxRowsExcel);
        page.setSize(maxRowsExcel);
        page.setOffset(0);
        page.setSearchCount(false);

        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        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);
        new AlarmRecordWarpper(alarmExpList).warp();

        FileInputStream fileInputStream = null;
        if (ToolUtil.isEmpty(alarmExpList)) {
            fileInputStream =  new FileInputStream(templatePath+"/alarmRecEmpty.xlsx");
        } else {
            fileInputStream =  new FileInputStream(templatePath+"/alarmRecTemplate.xlsx");
        }


        try {
            httpServletResponse.setContentType("application/octet-stream");
            httpServletResponse.addHeader("Content-Disposition", " attachment;filename="+"alarmOverview.xlsx" );

            Map<String,Object> var = new HashMap<>();
            var.put("标题","报警一览表");
            var.put("list",alarmExpList);
            ExcelIO.writeTemplate(fileInputStream,httpServletResponse.getOutputStream(),var);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpServletResponse.getOutputStream().flush();
            httpServletResponse.getOutputStream().close();
            fileInputStream.close();
        };

    }

    /**
     * 取消报警，即关闭工单
     */
    @RequestMapping(value = "/cancelAlarm")
    @ResponseBody
    public Object cancelAlarm(@RequestParam(value = "id",required = true) int id, //jobId
                              @RequestParam(value = "jobStatus",required = true) String jobStatus,
                              @RequestParam(value = "handleMessage",required = true)String handleMessage){
        Map<String,Object> retMap = new HashMap<>();
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        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.getCurrUserDataScope();
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        List<AlarmRecords> alarmRecords = alarmRecordsService.alarmListNoPage(dataScope,keywords,alarmType,alarmContent,beginTime,endTime);
        //根据jobId调用closeJob
        for (AlarmRecords alarmRecord : alarmRecords) {
            alarmRecordsService.cancelAlarm(alarmRecord.getJobId(),jobStatus,handleMessage,currentUser.getId());
        }
        return ResponseData.success();
    }

}
