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

import com.baomidou.mybatisplus.plugins.Page;
import com.casic.missiles.core.util.HttpClientUtils;
import com.casic.missiles.modular.alarm.service.IAlarmJobService;
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.EhcacheConstant;
import com.casic.missiles.core.util.ToolUtil;
import com.casic.missiles.modular.alarm.service.ISysDictService;
import com.casic.missiles.modular.system.model.AlarmJob;
import com.casic.missiles.modular.system.warpper.AlarmJobWarpper;
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.hswebframework.expands.office.excel.ExcelIO;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;



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

/**
 * 控制器
 *
 * @author dev
 * @Date 2019-05-17 10:48:36
 */
@Controller
@RequestMapping("/job")
public class AlarmJobController extends BaseController {


    @Autowired
    private IAlarmJobService alarmJobService;
    @Autowired
    private ICommonPermissionService iCommonPermissionService;
    @Autowired
    private ISysDictService iSysDictService;

    @Value("${smartcity.office.maxRowsExcel}")
    private  int maxRowsExcel;
    @Value("${smartcity.leaderRoleName}")
    private  String sLeader;
    @Value("${smartcity.memberRoleName}")
    private  String sMember;
    @Value("${smartcity.config.config-path}")
    private String templatePath;
    @Value("${smartcity.postUri}")
    private  String sPostUri;
    @Value("${smartcity.httpUri}")
    private  String sHttpUri;


    @RequestMapping(value = "/countByJobStatus")
    @ResponseBody
    public Map<String,Object> countByJobStatus(HttpServletRequest httpServletRequest) throws ParseException {
        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;
        }
        String startDate = httpServletRequest.getParameter("startDate");
        String endDate = httpServletRequest.getParameter("endDate");
        String formatStr;
        Date sDate,eDate;
        int spanDays=-1;

        if (ToolUtil.isNotEmpty(startDate) && ToolUtil.isNotEmpty(endDate))
        {
            if (startDate.length()==19)
            {
                formatStr="yyyy-MM-dd HH:mm:ss";
            }
            else {
                formatStr="yyyy-MM-dd";
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr);
            sDate =  simpleDateFormat.parse(startDate);
            eDate = simpleDateFormat.parse(endDate);
            spanDays= (int) ((eDate.getTime()-sDate.getTime() )/ (1000*3600*24));
        }

        Map<String,Object> retObj = new HashMap<>();
        Map<String,Object> retMyObj = new HashMap<>();
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        String deptIds = StringUtils.strip(dataScope.getDeptIds().toString(),"[]");
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        if (!currentUser.getRoleTips().contains(sLeader)&&!currentUser.getRoleTips().contains(sMember))
        {
            retMap.put("code",505);
            retMap.put("message","noneRolePrevilege");
            return retMap;
        }
        retMyObj = alarmJobService.countMyJob(currentUser.getId(),currentUser.getDeptId(),spanDays,deptIds);
        if (currentUser.getRoleTips().contains(sLeader))
        {
            retObj = alarmJobService.countByJobStatus(currentUser.getDeptId(),spanDays);
            for (String key : retObj.keySet())
            {
                String sVal = retMyObj.get(key)+"/"+retObj.get(key);
                retMyObj.replace(key,sVal);
            }
        }
        retMap.put("code",200);
        retMap.put("message","success");
        retMap.put("data",retMyObj);
        return retMap;
    }

    /**
     * 获取分页列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object listPage(@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<AlarmJob> page = new PageFactory<AlarmJob>().defaultPage("createTime",false);

        String keywords = httpServletRequest.getParameter("keywords");
        String beginTime = httpServletRequest.getParameter("beginTime");
        String endTime = httpServletRequest.getParameter("endTime");
        String jobStatusStr =  httpServletRequest.getParameter("jobStatus");
        String alarmTypeStr = httpServletRequest.getParameter("alarmType");
        String alarmContentStr = httpServletRequest.getParameter("alarmContentType");
        long leaderId = 0L;

//        EntityWrapper<AlarmRecords> query = new EntityWrapper<>();
//        page =  alarmRecordsService.selectPage(page,query);
        List<AlarmJob> retList = new ArrayList<>();
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
//        String deptIds = StringUtils.strip(dataScope.getDeptIds().toString(),"[]");
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        if (currentUser.getRoleTips().contains(sLeader))
        {
            leaderId = currentUser.getId();
            if (ToolUtil.isNotEmpty(jobStatusStr)) {
                page.setOpenSort(Integer.valueOf(jobStatusStr) != 3);
            }
        }
        if (currentUser.getRoleTips().contains(sLeader)|| currentUser.getRoleTips().contains(sMember)){
//            retList = alarmJobService.jobListApp(page,keywords,beginTime,endTime,jobStatusStr,alarmTypeStr,alarmContentStr,currentUser.getDeptId(),currentUser.getId(),leaderId,dataScope);
            retList = alarmJobService.jobListGroup(page,keywords,beginTime,endTime,jobStatusStr,alarmTypeStr,alarmContentStr,currentUser.getId());

        }else{
//            retList = alarmJobService.jobList(page,keywords,beginTime,endTime,jobStatusStr,alarmTypeStr,alarmContentStr,dataScope);
            retList = alarmJobService.jobListScope(page,keywords,beginTime,endTime,jobStatusStr,alarmTypeStr,alarmContentStr,dataScope);

        }
        new AlarmJobWarpper(retList).warp();
        page.setRecords(retList);
        retMap.put("code",200);
        retMap.put("message","success");
        retMap.put("data",super.packForBT(page));
        return retMap;
    }


    @RequestMapping(value = "/export")
    public void exportJob(HttpServletRequest httpServletRequest
            , HttpServletResponse httpServletResponse) throws IOException {
        boolean bSessionValid = false;
        bSessionValid = super.getSession().getAttribute("sessionFlag")==null?false:(boolean)super.getSession().getAttribute("sessionFlag");
        if (!bSessionValid)
        {
            return;
        }

        Page<AlarmJob> page = new PageFactory<AlarmJob>().defaultPage("createTime",false);
        page.setLimit(maxRowsExcel);
        page.setSize(maxRowsExcel);
        page.setSearchCount(false);
        page.setOffset(0);

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

//        EntityWrapper<AlarmRecords> query = new EntityWrapper<>();
//        page =  alarmRecordsService.selectPage(page,query);
        List<AlarmJob> jobExpList = new ArrayList<>();
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        jobExpList = alarmJobService.jobList(page,keywords,beginTime,endTime,jobStatusStr,alarmTypeStr,alarmContentStr,dataScope);
        new AlarmJobWarpper(jobExpList).warp();
        FileInputStream fileInputStream = null;
        if (ToolUtil.isEmpty(jobExpList))
        {
//            GunsException gunsException = new GunsException(BizExceptionEnum.REQUEST_NULL);
//            gunsException.setMessage("无数据导出");
//            throw gunsException;
            fileInputStream = new FileInputStream(templatePath+"/jobRecEmpty.xlsx");
        }
        else
            fileInputStream = new FileInputStream(templatePath+"/jobRecTemplate.xlsx");
//        Resource resource =  new ClassPathResource("config/temp/jobRecTemplate.xlsx");
//        FileInputStream fileInputStream = new FileInputStream(templatePath+"/jobRecTemplate.xlsx");
        try
        {
            httpServletResponse.setContentType("application/octet-stream");
            httpServletResponse.addHeader("Content-Disposition", " attachment;filename="+"jobOverview.xlsx" );

            Map<String,Object> var = new HashMap<>();
            var.put("标题","工单一览表");
            var.put("list",jobExpList);
            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 = "/getJob")
    @ResponseBody
    public Map<String,Object> getJob(int id,HttpServletRequest httpServletRequest) {

        Map<String,Object> retMap = new HashMap<>();
        if (super.getSession().getAttribute("sessionFlag")==null)
        {
            retMap.put("code",505);
            retMap.put("message","sessionExpired");
            return retMap;
        }
//        ShiroUser currentUser = (ShiroUser) super.getSession().getAttribute("shiroUser");
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        //userId
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        retMap.put("code",200);
        retMap.put("message","success");
        if (!alarmJobService.getJob(id,currentUser.getId()))//userId
        {
            retMap.put("code",200);
            retMap.put("message","failure");
        }
        return retMap;
    }

    @RequestMapping(value = "/confirmJob")
    @ResponseBody
    public Map<String,Object> confirmJob(@RequestParam(value = "id",required = true) int id,
                                         @RequestParam(value = "firstState",required = true) String firstState,
                                         @RequestParam(value = "firstStatePhotos",required = true)String firstStatePhotos,
                                         @RequestParam(value = "needHandle",required = true)String needHandle)
    {
        Map<String,Object> retMap = new HashMap<>();
        if (super.getSession().getAttribute("sessionFlag")==null)
        {
            retMap.put("code",505);
            retMap.put("message","sessionExpired");
            return retMap;
        }
//        ShiroUser currentUser = (ShiroUser) super.getSession().getAttribute("shiroUser");
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        //userId
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        retMap.put("code",200);
        retMap.put("message","success");
        if (!alarmJobService.confirmJob(id,currentUser.getId(), firstState, firstStatePhotos, needHandle))//userId
        {
            retMap.put("code",200);
            retMap.put("message","failure");
        }
        return retMap;
    }

    @RequestMapping(value = "/transferJob")
    @ResponseBody
    public Map<String,Object> transferJob(@RequestParam(value = "id",required = true) int id,
                                          @RequestParam(value = "transferPerson",required = true)String transferPerson) throws JSONException {
        Map<String,Object> retMap = new HashMap<>();
        if (super.getSession().getAttribute("sessionFlag")==null)
        {
            retMap.put("code",505);
            retMap.put("message","sessionExpired");
            return retMap;
        }
//        ShiroUser currentUser = (ShiroUser) super.getSession().getAttribute("shiroUser");
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        //userId
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        retMap.put("code",200);
        retMap.put("message","success");
        String dbTime = iSysDictService.getDBtime();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("from",currentUser.getName());
        jsonObject.put("to", EhcacheConstant.retBean().getUsernameById(Long.valueOf(transferPerson)));
//        jsonObject.put("to",transferPerson);
        jsonObject.put("time",dbTime);
        if (!alarmJobService.transferJob(id,Long.valueOf(transferPerson),jsonObject.toString()))//userId transferred usrId????
        {
            retMap.put("code",200);
            retMap.put("message","failure");
        }
        return retMap;
    }

    @RequestMapping(value = "/saveJob")
    @ResponseBody
    public Map<String,Object> saveJob(@RequestParam(value = "id",required = true) int id,
                                      @RequestParam(value = "handleMessage",required = true)String handleMessage,
                                      @RequestParam(value = "handlePhotos",required = true)String handlePhotos)
    {
        Map<String,Object> retMap = new HashMap<>();
        if (super.getSession().getAttribute("sessionFlag")==null)
        {
            retMap.put("code",505);
            retMap.put("message","sessionExpired");
            return retMap;
        }
        //        ShiroUser currentUser = (ShiroUser) super.getSession().getAttribute("shiroUser");
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        //userId
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        retMap.put("code",200);
        retMap.put("message","success");
        if (!alarmJobService.saveJob(id,handleMessage,handlePhotos))//userId
        {
            retMap.put("code",200);
            retMap.put("message","failure");
        }
        return retMap;
    }

    @RequestMapping(value = "/overJob")
    @ResponseBody
    public Map<String,Object> overJob(@RequestParam(value = "id",required = true) int id,
                                      @RequestParam(value = "handleMessage",required = true)String handleMessage,
                                      @RequestParam(value = "handlePhotos",required = true)String handlePhotos)
    {
        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();
        retMap.put("code",200);
        retMap.put("message","success");
        boolean overJob = alarmJobService.overJob(id,currentUser.getId(),handleMessage,handlePhotos);
        if(!overJob) {
            retMap.put("code",200);
            retMap.put("message","failure");
        } else {
            String devCode = alarmJobService.selectById(id).getDevcode();
            // 消警通信，预留
            if(ToolUtil.isNotEmpty(sPostUri)){
                alarmJobService.postUri(sPostUri, devCode, null);
            }
            // 两套后台之间通信
            if(ToolUtil.isNotEmpty(sHttpUri)){
                alarmJobService.httptUri(sHttpUri,devCode,handleMessage,handlePhotos);
            }
        }
        return retMap;
    }

    @RequestMapping(value = "/overJobSync")
    @ResponseBody
    public Map<String,Object> overJobSync(@RequestParam(value = "devCode",required = true) String devCode,
                                          @RequestParam(value = "handleMessage",required = true)String handleMessage,
                                          @RequestParam(value = "handlePhotos",required = true)String handlePhotos){
        alarmJobService.overJobByDevCode(devCode,handleMessage,handlePhotos);
        Map<String,Object> retMap = new HashMap<>();
        retMap.put("code",200);
        retMap.put("message","success");
        return retMap;
    }


    @RequestMapping(value = "/handleJob")
    @ResponseBody
    public Map<String,Object> handleJob(@RequestParam(value = "id",required = true) int id)
    {
        Map<String,Object> retMap = new HashMap<>();

        if (super.getSession().getAttribute("sessionFlag")==null)
        {
            retMap.put("code",505);
            retMap.put("message","sessionExpired");
            return retMap;
        }
//        ShiroUser currentUser = (ShiroUser) super.getSession().getAttribute("shiroUser");
        ShiroUser currentUser = iCommonPermissionService.getCurrLoginUser();
        //userId
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        retMap.put("code",200);
        retMap.put("message","success");
        if (!alarmJobService.handleJob(id,currentUser.getId()))//userId
        {
            retMap.put("code",200);
            retMap.put("message","failure");
        }
        return retMap;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/info")
    @ResponseBody
    public Map<String,Object> jobInfo(@RequestParam(value = "id",required = true) int id) {
        Map<String,Object> retMap = new HashMap<>();
        if (super.getSession().getAttribute("sessionFlag")==null)
        {
            retMap.put("code",505);
            retMap.put("message","sessionExpired");
            return retMap;
        }
        List<AlarmJob> retList = new ArrayList<>();
        DataScope dataScope = iCommonPermissionService.getCurrUserDataScope();//datascope
        retList = alarmJobService.jobInfo(id,dataScope);
        new AlarmJobWarpper(retList).warp();
        retMap.put("code",200);
        retMap.put("message","success");
        retMap.put("data",retList);
        return retMap;
    }


}
