package com.yeejoin.amos.supervision.business.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.yeejoin.amos.supervision.business.util.*;
import com.yeejoin.amos.supervision.business.vo.CodeOrderVo;
import com.yeejoin.amos.supervision.business.vo.PlanTaskVo;
import com.yeejoin.amos.supervision.business.vo.PointInputItemVo;
import com.yeejoin.amos.supervision.common.enums.*;
import com.yeejoin.amos.supervision.exception.YeeException;
import com.yeejoin.amos.supervision.feign.RemoteSecurityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.supervision.business.constants.XJConstant;
import com.yeejoin.amos.supervision.business.param.PlanTaskPageParam;
import com.yeejoin.amos.supervision.business.service.intfc.IPlanTaskService;
import com.yeejoin.amos.supervision.business.service.intfc.IPointService;
import com.yeejoin.amos.supervision.business.service.intfc.IRouteService;
import com.yeejoin.amos.supervision.core.common.request.CommonPageable;
import com.yeejoin.amos.supervision.core.common.request.CommonRequest;
import com.yeejoin.amos.supervision.core.common.response.AppPointCheckRespone;
import com.yeejoin.amos.supervision.dao.entity.Point;
import com.yeejoin.amos.supervision.dao.entity.PointClassify;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

@RestController
@RequestMapping(value = "/api/planTask")
@Api(tags = "计划执行api")
public class PlanTaskController extends AbstractBaseController {
    private final Logger log = LoggerFactory.getLogger(PlanTaskController.class);

    @Autowired
    private IPlanTaskService planTaskService;

    @Autowired
    IPointService pointService;

    @Autowired
    private IRouteService routeService;

    @Autowired
    private RemoteSecurityService remoteSecurityService;
    private String loginOrgCode;

    /**
     * 计划执行查询
     *
     * @param queryRequests
     * @param commonPageable
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "计划执行查询", notes = "计划执行查询")
    @RequestMapping(value = "/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse getPlanTaskList(
            @ApiParam(value = "查询条件") @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, null);
        PlanTaskPageParam params = new PlanTaskPageParam();
        PlanTaskPageParamUtil.fillChkInfoParam(queryRequests, commonPageable, params, paramMap);
        Page<HashMap<String, Object>> list = planTaskService.getPlanTaskInfo(params);
        return CommonResponseUtil.success(list);
    }

    /**
     * 计划执行重做
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "计划执行重做", notes = "计划执行重做")
    @RequestMapping(value = "/regenPlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse planTaskReGen(
            @ApiParam(value = "巡检计划", required = true) @RequestBody HashMap<String, Object> param) {
        if (param.get("planId") == null) {
            throw new YeeException("计划编号不能为空");
        }
        if (param.get("beginDate") == null) {
            throw new YeeException("开始日期能为空");
        }
        if (param.get("endDate") == null) {
            throw new YeeException("结束日期不能为空");
        }
        if (param.get("changeFlag") == null) {
            throw new YeeException("是否记为合格不能为空");
        }
        try {
            planTaskService.reGenPlanTask(param);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("计划执行重做失败");
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "初始化统计数据", notes = "始化统计数据")
    @RequestMapping(value = "/resetPlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse resetPlanTask(@ApiParam(value = "组织编码", required = false) @RequestParam(required = true) String orgCode) {
        ReginParams reginParams = getSelectedOrgInfo();
        String companyId = reginParams.getCompany().getSequenceNbr().toString();
        Toke toke = new Toke();
        toke.setAppKey(getAppKey());
        toke.setProduct(getProduct());
        toke.setToke(getToken());
        List<AgencyUserModel> list = remoteSecurityService.listUserByCompanyId(getToken(), getProduct(), getAppKey(), companyId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (AgencyUserModel u : list) {
            try {
                planTaskService.reformStatisticsPlanTask("2019-01-01", sdf.format(new Date()), u.getUserId() + "", orgCode);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        return CommonResponseUtil.success();
    }

    /**
     * 计划执行删除
     *
     * @param strArry
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "计划执行删除", notes = "计划执行删除")
    @RequestMapping(value = "/deletePlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse planTaskDelete(@ApiParam(value = "计划id数组", required = true) @RequestBody String[] strArry) {
        try {
            planTaskService.planTaskDet(strArry);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("删除计划执行失败");
        }
    }

    /**
     * 执行计划导出
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "执行计划导出", notes = "执行计划导出")
    @PostMapping(value = "/reportPlanTask", produces = "application/vnd.ms-excel;charset=UTF-8")
    public void planTaskReport(
            @ApiParam(value = "导出参数", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
            HttpServletResponse response) {
        try {
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getOrgCode(reginParams);
            HashMap<String, Object> paramMap = buildMybatisDaoCriterias(loginOrgCode, null);
            PlanTaskPageParam params = new PlanTaskPageParam();
            PlanTaskPageParamUtil.fillChkInfoParam(queryRequests, null, params, paramMap);
            List<PlanTaskVo> list = planTaskService.planTaskReport(getToken(), getProduct(), getAppKey(), params);
            String fileName = "计划执行" + new Date().getTime();
            FileHelper.exportExcel(list, "计划执行", "计划执行", PlanTaskVo.class, fileName + ".xls", response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导出巡检记录", notes = "导出巡检记录")
    @RequestMapping(value = "/exportSelectPlanTask", method = RequestMethod.GET)
    public void exportSelectPlanTask(
            @ApiParam(value = "查询条件", required = false) @RequestParam(required = false) Long[] ids,
            HttpServletResponse response) {
        List<PlanTaskVo> list = planTaskService.getPlanTaskListByIds(getToken(), getProduct(), getAppKey(), ids);
        String fileName = "巡检记录" + System.currentTimeMillis();
        FileHelper.exportExcel(list, "计划执行", "计划执行", PlanTaskVo.class, fileName + ".xls", response);
    }

    /**
     * 定时查询任务状态
     *
     * @return
     */
    @ApiOperation(value = "定时执行任务表生成(<font color='blue'>release</font>)", notes = "定时执行任务表生成")
    @RequestMapping(value = "/queryOmission", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse pushCarData() {
        try {
            planTaskService.taskExecution(null);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure();
        }
    }

    /**
     * 模拟定时任务调起服务
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "模拟定时任务调起服务", notes = "模拟定时任务调起服务")
    @RequestMapping(value = "/schJobTest", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse schJobTest(@ApiParam(value = "跑批日期格式yyyyMMdd", required = false) @RequestParam(required = false) String runDate) {
        try {
            planTaskService.taskExecution(runDate);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure();
        }
    }

    /**
     * 根据点查询用户权限所有巡检执行计划
     *
     * @param dataType   数据类型
     * @param serial     巡检点编号
     * @param planTaskId 巡检任务Id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据点查询用户权限所有巡检执行计划(<font color='blue'>手机app</font>)", notes = "根据点查询用户权限所有巡检执行计划(<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/queryPlanTaskBySerial", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse qryPlanTaskByPoint(
            @ApiParam(value = "数据类型", required = false) @RequestParam(required = true) int dataType,
            @ApiParam(value = "巡检点编号", required = true) @RequestParam(required = true) String serial,
            @ApiParam(value = "参数", required = false) @RequestParam(required = false) Long planTaskId) {
        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getOrgCode(reginParams);
            params.put("orgCode", loginOrgCode);
            String pointNo = serial;
            params.put("pointNo", pointNo);
            Point point = pointService.queryPointByPointNo(params);
            // 1.通用校验
            if (point == null) {
                return CommonResponseUtil.failure("巡检点不存在");
            }
            long pointId = point.getId();
            // 2.计划巡检校验
            if (planTaskId != null) {
                // 1.校验当前点的执行情况，不能重复巡检及超时巡检
                params.put("planTaskId", planTaskId);
                List<CodeOrderVo> list = planTaskService.queryCodeOrderVo(params);
                if (ObjectUtils.isEmpty(list)) {
                    return CommonResponseUtil.failure("该计划已刷新，请重新选择！！！");
                }
                if (list.get(0).getStatus() == PlanTaskFinishStatusEnum.OVERTIME.getValue()) {
                    return CommonResponseUtil.failure("任务已超时！");
                }
                if (list.get(0).getStatus() == PlanTaskFinishStatusEnum.FINISHED.getValue()) {
                    return CommonResponseUtil.failure("任务已结束！");
                }
                //2.顺序执行->按照点planTaskId，查询出所有点并按照orderNo排序,判断上一个点的执行情况
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getPointId() == pointId) {
                        if (!PlanTaskDetailStatusEnum.NOTSTARTED.getValue().equals(list.get(i).getIsFinish())) {
                            return CommonResponseUtil.failure("任务已结束！");
                        }
                        if (TaskIsOrderEnum.ISORDER.getValue().equals(list.get(0).getInOrder())) {
                            if (i > 0 && PlanTaskDetailStatusEnum.NOTSTARTED.getValue().equals(list.get(i - 1).getIsFinish())) {
                                return CommonResponseUtil.failure("请按顺序执行！");
                            }
                        }
                    }
                }
            }
            return CommonResponseUtil.success(point);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("巡检点查询失败");
        }
    }

    /**
     * 查询任务点详情
     *
     * @param planTaskId
     * @param pointId
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(value = "根据计划任务ID和点ID初始化巡检页面(<font color='blue'>手机app</font>)", notes = "根据计划任务ID和点ID初始化巡检页面((<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/initPlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse qryPlanTaskDetailById(
            @ApiParam(value = "巡检计划任务ID") @RequestParam(required = false) Long planTaskId,
            @ApiParam(value = "巡检点id", required = true) @RequestParam(required = true) Long pointId) {
        try {
            Map<String, Object> response = new HashMap<String, Object>();
            if (planTaskId != null && planTaskId > 0) {
                Point point = pointService.queryPointById(pointId);
                if (!XJConstant.IS_FIXED_YES.equals(point.getIsFixed())) {
                    // 1.校验当前点的执行情况，不能重复巡检及超时巡检
                    HashMap<String, Object> params = new HashMap<String, Object>();
                    params.put("planTaskId", planTaskId);
                    List<CodeOrderVo> list = planTaskService.queryCodeOrderVo(params);
                    if (ObjectUtils.isEmpty(list)) {
                        return CommonResponseUtil.failure("该计划已刷新，请重新选择！！！");
                    }
                    if (list.get(0).getStatus() == PlanTaskFinishStatusEnum.OVERTIME.getValue()) {
                        return CommonResponseUtil.failure("任务已超时！");
                    }
                    if (list.get(0).getStatus() == PlanTaskFinishStatusEnum.FINISHED.getValue()) {
                        return CommonResponseUtil.failure("任务已结束！");
                    }
                    //2.顺序执行->按照点planTaskId，查询出所有点并按照orderNo排序,判断上一个点的执行情况
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getPointId().longValue() == pointId) {
                            if (!PlanTaskDetailStatusEnum.NOTSTARTED.getValue().equals(list.get(i).getIsFinish())) {
                                return CommonResponseUtil.failure("任务已结束！");
                            }
                            if (TaskIsOrderEnum.ISORDER.getValue().equals(list.get(0).getInOrder())) {
                                if (i > 0 && PlanTaskDetailStatusEnum.NOTSTARTED.getValue().equals(list.get(i - 1).getIsFinish())) {
                                    return CommonResponseUtil.failure("请按顺序执行！");
                                }
                            }
                        }
                    }
                }
                Map taskDetail = planTaskService.findPlanTaskByTaskIdAndPointId(planTaskId, pointId);
                taskDetail.put("shotMaxNumber", point.getShotMaxNumber());
                taskDetail.put("shotMinNumber", point.getShotMinNumber());
                response.put("planTask", taskDetail);
                List<PointInputItemVo> inputItems = routeService
                        .listRoutePointInputItem(Long.valueOf(taskDetail.get("routeId").toString()), pointId);
                List<Map<String, Object>> pointClassify = pointService.queryPointClassifyByRouteIdAndPointId(
                        Long.valueOf(taskDetail.get("routeId").toString()), pointId);
                pointClassify.removeAll(Collections.singleton(null));
                response.put("class", pointClassify);
                response.put("checkItem", inputItems);
                return CommonResponseUtil.success(response);
            } else {
                Point point = pointService.queryPointById(pointId);
                List<PointInputItemVo> inputItems = pointService.queryPointClassInputItem(pointId);
                response.put("checkItem", inputItems);
                List<PointClassify> catalogs = pointService.queryPointClassify(pointId);
                response.put("class", catalogs);
                response.put("point", point);
                return CommonResponseUtil.success(response);
            }
        } catch (Exception e) {
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

    /**
     * 查询任务点详情
     *
     * @param planTaskId
     * @param pointId
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    // @Authorization(ingore = true)
    @ApiOperation(value = "根据计划任务ID和点ID初始化巡检页面(<font color='blue'>手机app</font>)", notes = "根据计划任务ID和点ID初始化巡检页面((<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/v2/initPlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse qryPlanTaskDetailByIdInVersion2(
            @ApiParam(value = "巡检计划任务ID") @RequestParam(required = false) Long planTaskId,
            @ApiParam(value = "巡检点id", required = true) @RequestParam(required = true) Long pointId) {
        try {
            Map<String, Object> response = new HashMap<String, Object>();
            if (planTaskId != null && planTaskId > 0) {
                Point point = pointService.queryPointById(pointId);
                if (!XJConstant.IS_FIXED_YES.equals(point.getIsFixed())) {
                    // 1.校验当前点的执行情况，不能重复巡检及超时巡检
                    HashMap<String, Object> params = new HashMap<String, Object>();
                    params.put("planTaskId", planTaskId);
                    List<CodeOrderVo> list = planTaskService.queryCodeOrderVo(params);
                    if (ObjectUtils.isEmpty(list)) {
                        return CommonResponseUtil.failure("该计划已刷新，请重新选择！！！");
                    }
                    if (list.get(0).getStatus() == PlanTaskFinishStatusEnum.OVERTIME.getValue()) {
                        return CommonResponseUtil.failure("任务已超时！");
                    }
                    if (list.get(0).getStatus() == PlanTaskFinishStatusEnum.FINISHED.getValue()) {
                        return CommonResponseUtil.failure("任务已结束！");
                    }
                    //2.顺序执行->按照点planTaskId，查询出所有点并按照orderNo排序,判断上一个点的执行情况
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getPointId().longValue() == pointId) {
                            if (!PlanTaskDetailStatusEnum.NOTSTARTED.getValue().equals(list.get(i).getIsFinish())) {
                                return CommonResponseUtil.failure("任务已结束！");
                            }
                            if (TaskIsOrderEnum.ISORDER.getValue().equals(list.get(0).getInOrder())) {
                                if (i > 0 && PlanTaskDetailStatusEnum.NOTSTARTED.getValue().equals(list.get(i - 1).getIsFinish())) {
                                    return CommonResponseUtil.failure("请按顺序执行！");
                                }
                            }
                        }
                    }
                }
                Map taskDetail = planTaskService.findPlanTaskByTaskIdAndPointId(planTaskId, pointId);
                taskDetail.put("shotMaxNumber", point.getShotMaxNumber());
                taskDetail.put("shotMinNumber", point.getShotMinNumber());
                response.put("planTask", taskDetail);
                Long routeId = Long.valueOf(taskDetail.get("routeId").toString());
                List<PointInputItemVo> inputItems = routeService.listRoutePointInputItem(routeId, pointId);
                List<Map<String, Object>> pointClassify = pointService.queryPointClassifyByRouteIdAndPointId(routeId, pointId);
                pointClassify.removeAll(Collections.singleton(null));
                response.put("class", pointClassify);
                response.put("checkItem", pointService.getClassifyRiskDescMap(inputItems));
                log.info(JSONObject.toJSONString(response));
                return CommonResponseUtil.success(response);
            } else {
                Point point = pointService.queryPointById(pointId);
                JSONObject inputItems = pointService.getClassifyRiskDescMap(pointId);
                response.put("checkItem", inputItems);
                List<PointClassify> catalogs = pointService.queryPointClassify(pointId);
                response.put("class", catalogs);
                response.put("point", point);
                log.info(JSONObject.toJSONString(response));
                return CommonResponseUtil.success(response);
            }
        } catch (Exception e) {
            log.error("请求异常", e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "根据计划任务ID查询计划任务详情和任务点(<font color='blue'>手机app</font>)", notes = "根据计划任务ID查询计划任务详情和任务点(<font color='blue'>手机app</font>)")
//    @RequestMapping(value = "/queryPlanTaskById", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
//    public CommonResponse qryPlanTaskById(
//            @ApiParam(value = "巡检计划任务ID", required = true) @RequestParam(required = true) Long planTaskId) {
//        try {
//            Map<String, Object> response = new HashMap<String, Object>();
//            Map task = planTaskService.queryPlanTaskById(planTaskId);
//            if (ObjectUtils.isEmpty(task) || ObjectUtils.isEmpty(task.get("planTaskId"))) {
//                return CommonResponseUtil.failure("该计划已刷新，请重新选择！！！");
//            }
//            List points = planTaskService.getPlanTaskPoints(planTaskId);
//
////            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
////            task.put("checkDate",  task.get("checkDate").toString());
//            String[] userIds = task.get("userId").toString().split(",");
//            for (String userId : userIds) {
//                task.put("userId", userId);
//            }
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            task.put("checkDate", sdf.format(task.get("checkDate") != null ? sdf.parse(task.get("checkDate").toString()) : new Date()));
//            response.put("planTask", task);
//            response.put("points", points);
//            return CommonResponseUtil.success(response);
//        } catch (Exception e) {
//            return CommonResponseUtil.failure(e.getMessage());
//        }
//
//    }

    /**
     * 查询任务列表
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "消防监督任务查询-mobile", notes = "根据用户条件查询所有计划任务")
    @RequestMapping(value = "/queryPlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public ResponseModel qryLoginUserPlanTask(
            @ApiParam(value = "人员") @RequestParam(value = "userId", required = false) Long userId,
            @ApiParam(value = "开始日期") @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(value = "结束日期") @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(value = "检查状态") @RequestParam(value = "finishStatus", required = false) Integer finishStatus,
            @ApiParam(value = "排序条件") @RequestParam(value = "orderBy", defaultValue = "1") String orderBy,
            @ApiParam(value = "被检查单位") @RequestParam(value = "companyId", required = false) String companyId,
            @ApiParam(value = "检查人员") @RequestParam(value = "executorId", required = false) Long executorId,
            @ApiParam(value = "任务类型") @RequestParam(value = "taskType", required = false) String taskType,
            @ApiParam(value = "当前页") @RequestParam(value = "pageNumber") int pageNumber,
            @ApiParam(value = "页大小") @RequestParam(value = "pageSize") int pageSize) throws Exception {
        HashMap<String, Object> params = new HashMap<String, Object>();
//        ReginParams reginParams = getSelectedOrgInfo();
//        String loginOrgCode = getOrgCode(reginParams);
//        Map<String, Object> authMap = Bean.BeantoMap(reginParams.getPersonIdentity());
//        params.putAll(authMap);
        params.put("userId", userId);
        params.put("companyId", companyId);
        params.put("orgCode", loginOrgCode);
        params.put("taskType", taskType);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("executorId", executorId);
        params.put("finishStatus", finishStatus);
        params.put("orderBy", OrderByEnum.getEumByCode(orderBy).getOderBy());
        CommonPageable pageable = new CommonPageable(pageNumber, pageSize);
        return ResponseHelper.buildResponse(planTaskService.getPlanTasks(params, pageable));
    }

    /**
     * 根据用户统计待办任务数量
     *
     * @param userId 用户id
     * @return 统计数量
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "消防监督待办任务查询-mobile", notes = "根据用户查询执行中的任务")
    @GetMapping("/countWaitingTaskByUser")
    public CommonResponse countWaitingTaskByUser(
            @ApiParam(value = "用户ID") @RequestParam("userId") String userId
    ) {
        try {
            return CommonResponseUtil.success(planTaskService.countWaitingTaskByUser(userId));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据检查任务ID查询计划任务详情和任务点(<font color='blue'>手机app</font>)", notes = "根据检查任务ID查询计划任务详情和任务点(<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/detail", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public ResponseModel qryPlanTaskDetailById(
            @ApiParam(value = "检查计划任务ID", required = true) @RequestParam Long planTaskId,
            @ApiParam(value = "人员") @RequestParam(value = "userId", required = false) Long userId,
            @ApiParam(value = "开始日期") @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(value = "结束日期") @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(value = "检查状态") @RequestParam(value = "finishStatus", required = false) Integer finishStatus,
            @ApiParam(value = "排序条件") @RequestParam(value = "orderBy", defaultValue = "1") String orderBy,
            @ApiParam(value = "被检查单位") @RequestParam(value = "companyId", required = false) String companyId,
            @ApiParam(value = "检查人员") @RequestParam(value = "executorId", required = false) Long executorId,
            @ApiParam(value = "任务类型") @RequestParam(value = "taskType", required = false) String taskType,
            @ApiParam(value = "当前页", required = true) @RequestParam(value = "pageNumber") int pageNumber,
            @ApiParam(value = "页大小", required = true) @RequestParam(value = "pageSize") int pageSize
    ) {
        ResponseModel result = null;
        try {
            Map<String, Object> response = new HashMap<String, Object>();
            Map task = planTaskService.queryPlanTaskById(planTaskId);
            if (ObjectUtils.isEmpty(task) || ObjectUtils.isEmpty(task.get("planTaskId"))) {
                result = ResponseHelper.buildResponse("该计划已刷新，请重新选择！！！");
            } else {
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("userId", userId);
                params.put("companyId", companyId);
                params.put("orgCode", loginOrgCode);
                params.put("taskType", taskType);
                params.put("startTime", startTime);
                params.put("endTime", endTime);
                params.put("executorId", executorId);
                params.put("finishStatus", finishStatus);
                params.put("planTaskId", planTaskId);
                params.put("orderBy", OrderByEnum.getEumByCode(orderBy).getOderBy());
                CommonPageable pageable = new CommonPageable(pageNumber, pageSize);
                Page<Map<String, Object>> points = planTaskService.getPlanTaskPoints(params, pageable);
                response.put("planTask", task);
                response.put("points", points);
                result = ResponseHelper.buildResponse(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Object nvl(Object param) {
        return param != null ? param : null;
    }

    /**
     * 查询任务列表
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取用户当前所正在进行中和尚未开始的任务个数(<font color='blue'>手机app</font>)", notes = "获取用户当前所欲呕正在进行中和尚未开始的任务个数(<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/queryPlanTaskCount", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse hasPlanTask() {
        try {
            int count = planTaskService.getCurrentPlanTaskCount(getUserId());
            return CommonResponseUtil.success(count);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/queryPlanTaskStatistics", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "查询用户计划任务统计(<font color='blue'>手机app</font>)", notes = "查询用户计划任务统计(<font color='blue'>手机app</font>)<br />font color='blue'>参数： startTime, endTime </font>")
    public CommonResponse queryPlanTaskStatistics(
            @ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        HashMap<String, Object> resp = new HashMap<String, Object>();
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        PlanTaskPageParamUtil.fillPlanTask(queryRequests, params);
        params.put("userId", getUserId());
        if (queryRequests != null && queryRequests.size() > 0) {
            for (int i = 0; i < queryRequests.size(); i++) {
                String name = queryRequests.get(i).getName();
                if ("startTime".equals(name)) {
                    params.put("startTime", queryRequests.get(i).getValue());
                } else if ("endTime".equals(name)) {
                    params.put("endTime", queryRequests.get(i).getValue());
                }
            }
        }
        Map<String, Object> userResp = planTaskService.getPlanTaskStatisticsForApp(params);
        resp.put("user", userResp);
        params.put("userId", null);
        params.put("orgCode", loginOrgCode);
        Map<String, Object> orgResp = planTaskService.getPlanTaskStatisticsForApp(params);
        resp.put("company", orgResp);
        params.put("orgCode", null);
        return CommonResponseUtil.success(resp);
    }

    /**
     * 根据任务id和点id获取“未开始”任务点详情
     *
     * @param planTaskId
     * @param pointId
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据任务id和点id获取“未开始”任务点详情(<font color='blue'>手机app</font>)", notes = "根据任务id和点id获取“未开始”任务点详情(<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/queryPointPlanTaskDetail", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryPointPlanTaskDetail(
            @ApiParam(value = "巡检计划任务ID", required = true) @RequestParam(required = true) Long planTaskId,
            @ApiParam(value = "巡检点ID", required = true) @RequestParam(required = true) Long pointId) {
        try {
            AppPointCheckRespone result = planTaskService.queryPointPlanTaskDetail(getToken(), getProduct(), getAppKey(), planTaskId, pointId);
            if (ObjectUtils.isEmpty(result)) {
                return CommonResponseUtil.failure("该计划巡检点已更新，请退回重新选择");
            }
            return CommonResponseUtil.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

    /**
     * 根据任务id和点id获取“未开始”任务点详情
     *
     * @param planTaskId
     * @param pointId
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据任务id和点id获取“未开始”任务点详情(<font color='blue'>手机app</font>)", notes = "根据任务id和点id获取“未开始”任务点详情(<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/v2/queryPointPlanTaskDetail", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryPointPlanTaskDetailInVersion2(
            @ApiParam(value = "巡检计划任务ID", required = true) @RequestParam(required = true) Long planTaskId,
            @ApiParam(value = "巡检点ID", required = true) @RequestParam(required = true) Long pointId) {
        try {
            AppPointCheckRespone result = planTaskService.queryPointPlanTaskDetailInVersion2(getToken(), getProduct(), getAppKey(), planTaskId, pointId);
            if (ObjectUtils.isEmpty(result)) {
                return CommonResponseUtil.failure("该计划巡检点已更新，请退回重新选择");
            }
            return CommonResponseUtil.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

    /**
     * 离线同步计划
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(value = "获取离线巡检数据", notes = "取离线巡检数据")
    @RequestMapping(value = "/queryLeavePlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryLeavePlanTask() {
        String userId = getUserId();
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        params.put("orgCode", loginOrgCode);
        return CommonResponseUtil.success(planTaskService.queryLeavePlanTask(params));
    }


    /**
     * 业务查询巡检点时间戳数据
     *
     * @param userId
     * @param createDate
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "业务查询巡检点时间戳数据", notes = "业务查询巡检点时间戳数据")
    @RequestMapping(value = "/queryPlanTaskTimeAxis", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryPlanTaskTimeAxis(
            @ApiParam(value = "用户id", required = false) @RequestParam(required = false) Long userId,
            @ApiParam(value = "天数", required = false) @RequestParam(required = false) Integer createDate) {
        try {
            List<Map<String, Object>> result = planTaskService.queryPlanTaskTimeAxis(userId, createDate);
            return CommonResponseUtil.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }


    /**
     * 业务查询巡检点时间戳数据（业务大屏）
     *
     * @param userId
     * @param createDate
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "业务查询巡检点时间戳数据", notes = "业务查询巡检点时间戳数据")
    @RequestMapping(value = "/queryTimeAxis", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryTimeAxis(
            @ApiParam(value = "用户id", required = false) @RequestParam(required = false) Long userId,
            @ApiParam(value = "天数", required = false) @RequestParam(required = false) Integer createDate) {
        try {
            List<Map<String, Object>> result = planTaskService.queryTimeAxis(userId, createDate);
            return CommonResponseUtil.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "防火监督任务排序条件", notes = "防火监督任务排序条件")
    @RequestMapping(value = "/orderBy/list", method = RequestMethod.GET)
    public ResponseModel getOrderByList() {
        return ResponseHelper.buildResponse(OrderByEnum.getEnumList());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "防火监督检查类型条件", notes = "防火监督检查类型条件")
    @RequestMapping(value = "/checkType/list", method = RequestMethod.GET)
    public ResponseModel getCheckTypeList() {
        return ResponseHelper.buildResponse(CheckTypeSuEnum.getEnumList());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "防火监督检查任务条件", notes = "防火监督检查任务条件")
    @RequestMapping(value = "/planTaskFinishStatus/list", method = RequestMethod.GET)
    public ResponseModel getPlanTaskFinishStatusList() {
        return ResponseHelper.buildResponse(PlanTaskFinishStatusEnum.getEnumList());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "防火监督检查任务详情条件", notes = "防火监督检查任务详情条件")
    @RequestMapping(value = "/planTaskDetailIsStatus/list", method = RequestMethod.GET)
    public ResponseModel getPlanTaskDetailIsStatusList() {
        return ResponseHelper.buildResponse(PlanTaskDetailIsFinishEnum.getEnumList());
    }
}
