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

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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.patrol.business.constants.XJConstant;
import com.yeejoin.amos.patrol.business.param.PlanTaskPageParam;
import com.yeejoin.amos.patrol.business.service.intfc.IPlanTaskService;
import com.yeejoin.amos.patrol.business.service.intfc.IPointService;
import com.yeejoin.amos.patrol.business.service.intfc.IRouteService;
import com.yeejoin.amos.patrol.business.util.CommonResponse;
import com.yeejoin.amos.patrol.business.util.CommonResponseUtil;
import com.yeejoin.amos.patrol.business.util.FileHelper;
import com.yeejoin.amos.patrol.business.util.PlanTaskPageParamUtil;
import com.yeejoin.amos.patrol.business.util.Toke;
import com.yeejoin.amos.patrol.business.vo.CodeOrderVo;
import com.yeejoin.amos.patrol.business.vo.PlanTaskVo;
import com.yeejoin.amos.patrol.business.vo.PointInputItemVo;
import com.yeejoin.amos.patrol.common.enums.PlanTaskDetailStatusEnum;
import com.yeejoin.amos.patrol.common.enums.PlanTaskFinishStatusEnum;
import com.yeejoin.amos.patrol.common.enums.TaskIsOrderEnum;
import com.yeejoin.amos.patrol.core.common.request.CommonPageable;
import com.yeejoin.amos.patrol.core.common.request.CommonRequest;
import com.yeejoin.amos.patrol.core.common.response.AppPointCheckRespone;
import com.yeejoin.amos.patrol.core.framework.Permission;
import com.yeejoin.amos.patrol.dao.entity.Point;
import com.yeejoin.amos.patrol.dao.entity.PointClassify;
import com.yeejoin.amos.patrol.exception.YeeException;
import com.yeejoin.amos.patrol.feign.RemoteSecurityService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

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

   /* @Autowired
    private OtherDeptService otherDeptService;*/
    @Autowired
    private IPlanTaskService planTaskService;
    @Autowired
    IPointService pointService;

    @Autowired
    private IRouteService routeService;


    @Autowired
    private RemoteSecurityService remoteSecurityService;
   /* @Autowired
    private IUserService userService;*/

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

    /**
     * 计划执行重做
     *
     * @param param
     * @return
     */
    @Permission
    @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("计划执行重做失败");
        }
    }

    @Permission
    @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) {
       // List<SUser> list = userService.findAll();
    	 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
     */
    @Permission
    @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("删除计划执行失败");
        }
    }

    /**
     * 执行计划导出
     */
    @Permission
    @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 = getLoginOrgCode(reginParams);
              String roleTypeName = getRoleTypeName(reginParams);
              HashMap<String, Object> paramMap = buildMybatisDaoCriterias(loginOrgCode, roleTypeName);
            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);
        }
    }

    @Permission
    @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
     */
    @Scheduled(cron = "${jobs.cron}")
    @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
     */
    @Permission
    @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
     */
    @Permission
    @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>();
            //LoginUserParam loginParam = CurUserCompanyCache.getInstance().getCurCompany(getUserId(), getToken());
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getLoginOrgCode(reginParams);
           /* if (ObjectUtils.isEmpty(loginParam)) {
                return CommonResponseUtil.failure("公司选择失效");
            }*/
            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
     */
    @Permission
    //@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
     */
    @Permission
   // @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());
        }
    }

    @Permission
    @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 queryRequests
     * @return
     */
    @Permission
    @ApiOperation(value = "根据用户条件查询所有计划任务(<font color='blue'>手机app</font>)", notes = "根据用户条件查询所有计划任务(<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/queryPlanTask", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse qryLoginUserPlanTask(
            @ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数", required = false, defaultValue = "current=0&pageSize=10或pageNumber0&pageSize=10") CommonPageable pageable) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getLoginOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        params = PlanTaskPageParamUtil.fillPlanTask(queryRequests, params);
       // LoginUserParam loginParam = CurUserCompanyCache.getInstance().getCurCompany(getUserId(), getToken());

        String deptId="";
        String uid="";
        if(XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName)){
            deptId =getDepartmentId(reginParams);
            if(deptId!=null&&!("").equals(deptId.trim()))
                params.put("departmentId",deptId);
        }else if(XJConstant.ROLE_NAME_PERSON.equals(roleTypeName)){
            uid=getUserId();
            if(uid!=null&&!("").equals(uid.trim()))
                params.put("userId",uid);
        }
        params.put("orgCode",loginOrgCode);
        params.put("pageSize", pageable.getPageSize());
        params.put("offset", pageable.getPageNumber() * pageable.getPageSize());
        if (ObjectUtils.isEmpty(params.get("orderBy"))) {
            params.put("orderBy", "beginTime desc");
        }
        if (params.get("orderBy").toString().contains("taskPlanNum")) {
            params.put("orderBy", params.get("orderBy") + ",beginTime asc");
        }
        try {
//            if (!(ObjectUtils.isEmpty(params.get("departmentId"))) && params.get("departmentId").toString().equals("-1")) {
//
//                List<LinkedHashMap<String, Object>> userList = otherDeptService.queryDeptUsers("-1",
//                        loginOrgCode);
//                List ids = new ArrayList<Long>();
//                for (LinkedHashMap<String, Object> linkedHashMap : userList) {
//                    ids.add(linkedHashMap.get("id"));
//                }
//                params.put("ids", ids);
//            }
            Page page = planTaskService.getPlanTasks(getToken(),getProduct(),getAppKey(),params);



			List<Map<String, Object>> li= page.getContent();
			List<Map<String, Object>> li1=new ArrayList<>();
			if(li!=null&&li.size()>0){
			        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				for (Map<String, Object> msg : li) {
				    String[] userIds=msg.get("userId").toString().split(",");
                    for (String userId: userIds) {
                        msg.put("userId",userId);
                    }
                    if(msg.get("checkDate")!=null)
					msg.put("checkDate",  sdf.format(sdf.parse(msg.get("checkDate").toString())));
					li1.add(msg);
				}
			}


			 Page< Map<String, Object>>  pd=new PageImpl<>(li1, page.getPageable(), page.getTotalElements());

            return CommonResponseUtil.success(pd);
        } catch (Exception e) {
        	e.printStackTrace();
            return CommonResponseUtil.failure(e.getMessage());
        }

    }


    public static Map<String, Object> objectToMap1(Object obj) throws IllegalAccessException {
      	 Map<String, Object> map = new HashMap<String,Object>();
      	if(obj!=null){
          Class<?> clazz = obj.getClass();
          for (Field field : clazz.getDeclaredFields()) {
              field.setAccessible(true);
              String fieldName = field.getName();
              Object value = nvl(field.get(obj));
              if("userId".equals(fieldName)){
           	   map.put(fieldName, Long.valueOf(value.toString()));
              }else{
           	   map.put(fieldName, value);
              }

          }
          return map;
      }
      return map;
      }

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


    /**
     * 查询任务列表
     */
    @Permission
    @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());
        }
    }

    @Permission
    @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 = getLoginOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        String departmentId = getDepartmentId(reginParams);
        PlanTaskPageParamUtil.fillPlanTask(queryRequests, params);
//        params.put("orgCode",loginOrgCode);
        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);
        if (XJConstant.ROLE_NAME_PERSON.equals(roleTypeName.toUpperCase())) {
            return CommonResponseUtil.success(resp);
        }
        if (!ObjectUtils.isEmpty(reginParams.getDepartment())) {
            params.put("userDept",departmentId);
            Map<String, Object> deptResp = planTaskService.getPlanTaskStatisticsForApp(params);
            resp.put("department", deptResp);
            params.put("userDept", null);
        }

        if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName.toUpperCase())) {
            return CommonResponseUtil.success(resp);
        }
        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
     */
    @Permission
    @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
     */
    @Permission
    @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
     */
    @Permission
    //@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 = getLoginOrgCode(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
//     */
//    @Permission
//    @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);
////            if (ObjectUtils.isEmpty(result)) {
////                return CommonResponseUtil.failure("查询巡检点时间戳数据失败");
////            }
//            return CommonResponseUtil.success(result);
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return CommonResponseUtil.failure(e.getMessage());
//        }
//    }


    /**
     * 业务查询巡检点时间戳数据
     * @param userId
     * @param createDate
     * @return
     */
    @Permission
    @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);
//            if (ObjectUtils.isEmpty(result)) {
//                return CommonResponseUtil.failure("查询巡检点时间戳数据失败");
//            }
            return CommonResponseUtil.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }


    /**
     * 业务查询巡检点时间戳数据（业务大屏）
     * @param userId
     * @param createDate
     * @return
     */
    @Permission
    @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);
//            if (ObjectUtils.isEmpty(result)) {
//                return CommonResponseUtil.failure("查询巡检点时间戳数据失败");
//            }
            return CommonResponseUtil.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }
}
