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

import com.baomidou.mybatisplus.plugins.Page;
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.IAlarmJobService;
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.apache.commons.lang.StringUtils;
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.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;

//import com.casic.missiles.core.base.response.ResponseData;

/**
 * 控制器
 *
 * @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;
    @Autowired
    private IAlarmJobService alarmJobService;

    @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;
    @Value("${smartcity.postUri}")
    private String sPostUri;

    /**
     * 获取分页列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object alarmList(@RequestParam(value = "offset", required = true) int offset,
                            @RequestParam(value = "limit", required = true) int limit, HttpServletRequest httpServletRequest) {
        Map<String, Object> retMap = new HashMap<>();
        boolean bSessionValid = false;
        bSessionValid = super.getSession().getAttribute("sessionFlag") == null ? false : (boolean) super.getSession().getAttribute("sessionFlag");
        if (!bSessionValid) {
            retMap.put("code", 505);
            retMap.put("message", "sessionExpired");
            return retMap;
        }
        Page<AlarmRecords> page = new PageFactory<AlarmRecords>().defaultPage("alarmTime", false);

        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");
//        EntityWrapper<AlarmRecords> query = new EntityWrapper<>();
//        page =  alarmRecordsService.selectPage(page,query);
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        List<AlarmRecords> retList = new ArrayList<>();
        System.out.println("roleTips:" + currentUser.getRoleTips().toString());
        if (currentUser.getRoleTips().contains(sAdmin) || currentUser.getRoleTips().contains(sOperator))
            retList = alarmRecordsService.alarmListAll(page, keywords, beginTime, endTime, statusStr, alarmTypeStr, alarmContentStr, dataScope);
        else
            retList = alarmRecordsService.alarmList(page, keywords, beginTime, endTime, statusStr, alarmTypeStr, alarmContentStr, dataScope);
        new AlarmRecordWarpper(retList).warp();
        page.setRecords(retList);
        retMap.put("code", 200);
        retMap.put("message", "success");
        retMap.put("data", super.packForBT(page));
        return retMap;
    }

    /**
     * 详情
     */
//    @RequestMapping(value = "/detail/{alarmRecordsId}")
//    @ResponseBody
//    public Object detail(@PathVariable("alarmRecordsId") String alarmRecordsId) {
//        ResultData<AlarmRecords> resultData = new ResultData<AlarmRecords>();
//        resultData.setCode(200);
//        resultData.setMessage("查询详情成功");
//        resultData.setData(alarmRecordsService.selectById(alarmRecordsId));
//        return resultData;
//    }
    @RequestMapping(value = "/export")
//    @ResponseBody
    public void exportAlarm(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {

        boolean bSessionValid = false;
        bSessionValid = super.getSession().getAttribute("sessionFlag") == null ? false : (boolean) super.getSession().getAttribute("sessionFlag");
        if (!bSessionValid) {
            return;
        }
        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<AlarmRecords> page = new PageFactory<AlarmRecords>().defaultPage("alarmTime", false);
        page.setLimit(maxRowsExcel);
        page.setSize(maxRowsExcel);
        page.setOffset(0);
        page.setSearchCount(false);
        System.out.println("exportInfo:" + page.toString());
        List<AlarmRecords> alarmExpList = new ArrayList<>();
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        System.out.println("roleTips:" + currentUser.getRoleTips().toString());
        if (currentUser.getRoleTips().contains(sAdmin) || currentUser.getRoleTips().contains(sOperator))
            alarmExpList = alarmRecordsService.alarmListAll(page, keywords, beginTime, endTime, statusStr, alarmTypeStr, alarmContentStr, dataScope);
        else
            alarmExpList = alarmRecordsService.alarmList(page, keywords, beginTime, endTime, statusStr, alarmTypeStr, alarmContentStr, dataScope);
//        alarmExpList = alarmRecordsService.alarmList(page,keywords,beginTime,endTime,statusStr,alarmTypeStr,alarmContentStr,dataScope);
        new AlarmRecordWarpper(alarmExpList).warp();
        FileInputStream fileInputStream = null;
        if (ToolUtil.isEmpty(alarmExpList)) {
//            GunsException gunsException = new GunsException(BizExceptionEnum.REQUEST_NULL);
//            gunsException.setMessage("无数据导出");
//            throw gunsException;
            fileInputStream = new FileInputStream(templatePath + "/alarmRecEmpty.xlsx");
        } else
            fileInputStream = new FileInputStream(templatePath + "/alarmRecTemplate.xlsx");


//        FileInputStream fileInputStream =  new FileInputStream(templatePath+"/alarmRecTemplate.xlsx");
//        Resource resource =  new ClassPathResource("config/temp/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 = "/batchCancel")
    @ResponseBody
    public Map<String, Object> batchCancel(@RequestParam(value = "handleMessage", required = false) String handleMessage) {
        Map<String, Object> retMap = new HashMap<>();
        if (super.getSession().getAttribute("sessionFlag") == null) {
            retMap.put("code", 505);
            retMap.put("message", "sessionExpired");
            return retMap;
        }
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        String deptIds = StringUtils.strip(dataScope.getDeptIds().toString(), "[]");
        retMap.put("code", 200);
        retMap.put("message", "success");

        List<String> devCodes = alarmJobService.batchCancel(deptIds, currentUser.getId(),handleMessage);
        if (ToolUtil.isEmpty(devCodes)) {
            retMap.put("code", 200);
            retMap.put("message", "failure");
        } else if (ToolUtil.isNotEmpty(sPostUri))
            alarmJobService.postUri(sPostUri, devCodes, null);

        return retMap;
    }


    /**
     * 关闭告警推送功能
     *
     * @param id
     * @param pushOpen
     * @return
     */
    @RequestMapping(value = "/pushOpen")
    @ResponseBody
    public Object pushOpen(@RequestParam(value = "id", required = true) Long id,
                           @RequestParam(value = "pushOpen", required = true) String pushOpen) {
        Map<String, Object> retMap = new HashMap<>();
        alarmRecordsService.pushOpen(id,pushOpen);

        retMap.put("code", 200);
        retMap.put("message", "success");

        return retMap;
    }

    public static void main(String[] args) throws JSONException {
//        System.out.println("test");
//        EntityWrapper entityWrapper = new EntityWrapper();
//        entityWrapper.setEntity(new AlarmRecords());
//        entityWrapper.where("id = {0}",123).like("name","test");
//        System.out.println(entityWrapper.getSqlSegment());
//
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("from","onePerson");
//        jsonObject.put("to","another");
//        jsonObject.put("time","2019-01-01");
//        System.out.println(jsonObject.toString());
    }
}
