package com.ruoyi.web.controller.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisRepository;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExcelUtil;
import com.ruoyi.common.zqt.ZQTHttpHelper;
import com.ruoyi.common.zqt.ZQTPageModel;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.vo.GridWgBean;
import com.ruoyi.system.domain.other.BsCommon;
import com.ruoyi.system.domain.other.BsCommonExample;
import com.ruoyi.system.domain.system.SysUserRole;
import com.ruoyi.system.domain.task.*;
import com.ruoyi.system.domain.task.dto.*;
import com.ruoyi.system.domain.task.enums.TkStatusEnum;
import com.ruoyi.system.domain.task.request.TaskAssignedRequest;
import com.ruoyi.system.domain.task.request.TkResetRequest;
import com.ruoyi.system.domain.task.utils.WorkMSGUtils;
import com.ruoyi.system.domain.task.utils.WxUtil;
import com.ruoyi.system.domain.task.vo.LeaderPojo;
import com.ruoyi.system.mapper.grid.GridRegionExtMapper;
import com.ruoyi.system.mapper.grid.GridRegionMapper;
import com.ruoyi.system.mapper.system.SysUserRoleMapper;
import com.ruoyi.system.mapper.task.TkCommonTaskMapper;
import com.ruoyi.system.mapper.task.ext.TkCommonQianpiExtMapper;
import com.ruoyi.system.mapper.task.ext.TkCommonTaskExtMapper;
import com.ruoyi.system.service.grid.GridItemDailyFacadeService;
import com.ruoyi.system.service.grid.GridItemDailyService;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.system.service.grid.GridRegionUserService;
import com.ruoyi.system.service.other.BsCommonService;
import com.ruoyi.system.service.other.impl.FlpzService;
import com.ruoyi.system.service.system.ISysDeptService;
import com.ruoyi.system.service.system.ISysRoleService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.system.service.task.*;
import com.ruoyi.web.controller.task.request.StartTaskRequest;
import com.ruoyi.web.controller.task.request.TaskCommonListRequest;
import com.ruoyi.web.controller.task.vo.TodayTaskNumVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.text.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Api(tags = "工单 日常任务")
@RestController
@RequestMapping("/api/task/common")
public class CommonTaskController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonTaskController.class);

    @Autowired
    TkCommonTaskService tkCommonTaskService;
    @Autowired
    TkCommonTaskDynamicService tkCommonTaskDynamicService;
    @Autowired
    TkCommonAssignedService tkCommonAssignedService;
    @Autowired
    TkCommonLeaderService tkCommonLeaderService;
    @Autowired
    private TkCommonQianpiExtMapper tkCommonQianpiExtMapper;
    @Autowired
    private GridItemDailyService bsRcsxbService;
    @Autowired
    private TkRoundMatterService tkRoundMatterService;
    @Autowired
    private GridRegionService bsWgxxbService;
    @Autowired
    TkCommonTaskMapper tkCommonTaskMapper;
    @Autowired
    TkCommonTaskExtMapper tkCommonTaskExtMapper;
    @Autowired
    TkCommonTextService tkCommonTextService;
    @Autowired
    GridRegionUserService bsWgxxUserService;
    @Autowired
    TkCommonReceiveService tkCommonReceiveService;
    @Autowired
    GridRegionExtMapper extendGridRegionMapper;
    @Autowired
    TkRoundTaskService tkRoundTaskService;

    @Autowired
    TkRoundSubtaskService tkRoundSubtaskService;

    @Autowired
    TkRoundPlanService tkRoundPlanService;

    @Autowired
    private GridRegionMapper bsWgxxbMapper;

    @Autowired
    private DiyService diyService;

    @Value("${app.sms.enable}")
    private boolean smsEnable;
    @Value("${app.sms.switch}")
    private boolean smsswitch;

    @Autowired
    private GridItemDailyFacadeService bsRcsxService;

    @Autowired
    private BsCommonService bsCommonService;

    @Autowired
    private TkCommonDiaoduService tkCommonDiaoduService;

    @Autowired
    RedisRepository redisRepository;

    @Autowired
    FlpzService flpzService;

    @Value("${app.wx.dy.appId}")
    private String dyAppId;

    @Value("${app.wx.dy.appSecret}")
    private String dyAppSecret;

    @Value("${app.mgrdata.url}")
    private String managedataUrl;

    @Resource
    private TaskService taskService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysRoleService sysRoleService;

    @Autowired
    private WorkMSGUtils workMSGUtils;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ISysDeptService deptService;

    /*当前状态*/
//    任务发布    0
//    任务指派    10
//          指派了      12
//          退回任务    16
    //申请退回   17
//    任务处理（点了接受任务后）    20
//            申请延时  22
//            延时同意  24
//            延时拒绝  26
//    核查任务（点了开始处理后）    30
//          已经指派                34
//          核查任务不通关 36
//    评价任务（点了核查通过后）    40
//          评价任务后，完成状态  50

    ExecutorService threadPool = Executors.newFixedThreadPool(20);

    private static int DSOld = 9145;

    /**
     * 日常任务发布
     *
     * @param tkCommonTask
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult add(@RequestBody TkCommonTask tkCommonTask) {
        tkCommonTask.setReleaseUserId(this.getUserId());
        tkCommonTask.setReleaseUserName(this.getLoginUser().getUser().getNickName());
        tkCommonTask.setCreateBy(this.getUserId());
        String taskId = taskService.add(tkCommonTask);
        return AjaxResult.success("success","保存成功").put("projectId",taskId);
    }


    /**
     * 上报上级接口
     *
     * @param id            任务id
     * @param loginUserRole 任务上报到哪一级。3三级 2二级 1一级 0中心
     * @return
     */
    @RequestMapping(value = "reportLeader", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult reportLeader(String id, String loginUserId,
                               String loginUserName, String loginUserRole,
                               String loginUserGrid) {

        //获取任务信息
        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        //创建上报实体类
        TkCommonReport tkCommonReport = new TkCommonReport();
        tkCommonReport.setId(UUID.randomUUID().toString());
        tkCommonReport.setCommonTkId(tkCommonTask.getId());
        tkCommonReport.setCreateTime(new Date());
        if (loginUserRole.equals("2")) {
            tkCommonTask.setStandby2("0");
            tkCommonReport.setTolevel("0");
        } else {
            tkCommonTask.setStandby2(Integer.parseInt(loginUserRole) - 1 + "");
            tkCommonReport.setTolevel(Integer.parseInt(loginUserRole) - 1 + "");
        }
        try {
            //数据 上报上级的接收人数据 所以当前登录角色为2级 就查询中心的用户。
            AjaxResult result2 = new AjaxResult();//根据角色获取用户们
            if (loginUserRole.equals("2")) {
                sysRoleService.getUserByRoleCode("centerman", result2);
            } else if (loginUserRole.equals("3")) {
                sysRoleService.getUserByRoleCode("twogrid", result2);
            } else {//其他登录角色等级为  1级的  也是上报给中心
                sysRoleService.getUserByRoleCode("centerman", result2);
            }
            if (tkCommonTaskService.reportLeader(tkCommonTask, tkCommonReport, loginUserName, loginUserGrid, loginUserId,result2) == 0) {
                return AjaxResult.error(400,"上报出错");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(400,"上报出错");
        }
        return AjaxResult.success("上报成功");
    }

    /**
     * 自行处理接口
     * 上报上级后的自行处理接口
     *
     * @param id
     * @param loginUserId
     * @param loginUserName
     * @param loginUserRole
     * @param loginUserGrid
     * @return
     */
    @RequestMapping(value = "solveBySelf", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult solveBySelf(String id, String loginUserId,
                              String loginUserName, String loginUserRole,
                              String loginUserGrid) {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date assignedEndTime = null;
        try {
            String format = sdf.format(new Date());
            assignedEndTime = sdf.parse(format);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取任务信息
        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        tkCommonTask.setTkStatus(20);//任务处理状态是20
        tkCommonTask.setAssignedUserId(loginUserId);
        tkCommonTask.setAssignedUserName(loginUserName);
        tkCommonTask.setPerformUserId(loginUserId);
        tkCommonTask.setPerformUserName(loginUserName);
        tkCommonTask.setAssignedEndTime(new Date());//处理完成时间


        //指派信息
        TkCommonAssigned tkCommonAssigned = new TkCommonAssigned();//任务指派实体类
        tkCommonAssigned.setId(UUID.randomUUID().toString());
        tkCommonAssigned.setCommonTkId(id);
        tkCommonAssigned.setAssignedUserId(loginUserId);//指派人id
        tkCommonAssigned.setAssignedUserName(loginUserName);//指派人姓名
        tkCommonAssigned.setAssignedEndTime(assignedEndTime);
        tkCommonAssigned.setAssignedRole(Integer.parseInt(loginUserRole));//指派人角色等级
        tkCommonAssigned.setBeassignedUserId(loginUserId);//被指派人用户id
        tkCommonAssigned.setBeassignedUserName(loginUserName);//被指派人用户名
        tkCommonAssigned.setBeassignedRole(Integer.parseInt(loginUserRole));//被指派人角色等级
        tkCommonAssigned.setCreateTime(new Date());

        TkCommonAssignedExample tkCommonAssignedExample = new TkCommonAssignedExample();
        TkCommonAssignedExample.Criteria criteria = tkCommonAssignedExample.createCriteria();
        criteria.andCommonTkIdEqualTo(id);
        //查询有关联任务id 的数据
        List<TkCommonAssigned> tkCommonAssigneds = tkCommonAssignedService.selectByExample(tkCommonAssignedExample);
        if (tkCommonAssigneds.size() > 0) {//
            int status = tkCommonAssigneds.get(tkCommonAssigneds.size() - 1).getAssignedStatus();//取出最后一条
            tkCommonAssigned.setAssignedStatus(status + 1);//取出最后一条数据的状态+1
        } else {
            tkCommonAssigned.setAssignedStatus(1);//没数据就设为 1
        }
        try {
            int i = tkCommonTaskService.solveBySelf(tkCommonTask, loginUserName, loginUserGrid, tkCommonAssigned);
            if (i == 0) {
                throw new ServiceException("自行处理出错",400);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("自行处理出错",400);
        }
        return AjaxResult.success("自行处理成功");
    }

    @ApiOperation("任务查询")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult commonTasklist(@ModelAttribute TaskCommonListRequest request) {
        if (request == null){
            request = new TaskCommonListRequest();
        }
        ZQTPageModel<TkCommonTask> result = new ZQTPageModel<TkCommonTask>();
        try {
            PageInfo<TkCommonTask> page = tkCommonTaskService.selectList(request.params(),request.getPageNum(),request.getPageSize());

            if (page.getList().size() > 0) {
                for (int i = 0; i < page.getList().size(); i++) {
                    if (StringUtils.isNotBlank(page.getList().get(i).getQprIds())){
                        List<SysUser> users = sysUserService.listByIds(Arrays.asList(page.getList().get(i).getQprIds().split(",")));
                        page.getList().get(i).setQprNames(users.stream().map(SysUser::getNickName).collect(Collectors.joining(",")));
                    }
                    //查询是否有催办记录
                    boolean check = tkCommonTaskService.checkCuiBan(page.getList().get(i).getId());
                    page.getList().get(i).setCuiban(check);

                }
            }

            //分页
            result.setItemList(page.getList());
            //总记录数
            result.setRecordCount(page.getTotal());
            //总页数
            result.setPageCount(page.getPages());
            //当前页
            result.setCurPage(page.getPageNum());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询出错",400);
        }
        return AjaxResult.success(result);
    }


    /**
     * 工单统计
     *
     * @param releaseStartTime
     * @param releaseEndTime
     * @param wgCode
     * @return
     */
    @RequestMapping(value = "countAllTypeTask", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult countAllTypeTask(
            @RequestParam(required = false) String releaseStartTime, @RequestParam(required = false) String releaseEndTime, @RequestParam(required = false) String wgCode
    ) {
        Map<String, Object> data = new HashedMap();
        if (StringUtils.isNotBlank(wgCode)) {
            data.put("wgCode", wgCode);
        }
        if (releaseStartTime != null && releaseStartTime != "" && releaseEndTime != null && releaseEndTime != "") {//创建开始时间
            data.put("releaseStartTime", releaseStartTime);
            data.put("releaseEndTime", releaseEndTime);
        }
        //上报工单
        int allCount = tkCommonTaskExtMapper.countAllTypeTask(data);
        //已完成工单
        data.put("tkStatus", 1);
        int completedCount = tkCommonTaskExtMapper.countAllTypeTask(data);
        //待处理工单
        data.put("tkStatus", 5);
        int pendingCount = tkCommonTaskExtMapper.countAllTypeTask(data);
        //处理中工单
        data.put("tkStatus", 4);
        int processingCount = tkCommonTaskExtMapper.countAllTypeTask(data);
        //待核查工单
        data.put("tkStatus", 3);
        int checkCount = tkCommonTaskExtMapper.countAllTypeTask(data);
        Map<String, Object> res = new HashedMap();
        res.put("allCount", allCount);
        res.put("completedCount", completedCount);
        res.put("pendingCount", pendingCount);
        res.put("processingCount", processingCount);
        res.put("checkCount", checkCount);
        return AjaxResult.success(res);
    }


    /**
     * 任务详情接口
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "taskDetail", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getTaskDetail(@RequestParam String id, @RequestParam String loginUserId) {

        try {
            TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
            //获取任务动态
            TkCommonTaskDynamicExample tkCommonTaskDynamicExample = new TkCommonTaskDynamicExample();
            TkCommonTaskDynamicExample.Criteria criteria = tkCommonTaskDynamicExample.createCriteria();
            criteria.andCommonTkIdEqualTo(tkCommonTask.getId());
            tkCommonTaskDynamicExample.setOrderByClause("create_time desc");
            List<TkCommonTaskDynamic> tkCommonTaskDynamics = tkCommonTaskDynamicService.selectByExample(tkCommonTaskDynamicExample);
            //塞入任务动态
            tkCommonTask.setTkCommonTaskDynamics(tkCommonTaskDynamics);

            //获取转督办信息
            TkCommonLeaderExample TkCommonLeaderExample = new TkCommonLeaderExample();
            TkCommonLeaderExample.Criteria criteria1 = TkCommonLeaderExample.createCriteria();
            criteria1.andTkIdEqualTo(tkCommonTask.getId());
            List<TkCommonLeader> tkCommonLeaders = tkCommonLeaderService.selectByExample(TkCommonLeaderExample);
            //塞入转督办信息
            tkCommonTask.setTkCommonLeaders(tkCommonLeaders);

            //塞入领导签批信息
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("tkId", id);
            map.put("loginUserId", loginUserId);
            List<TkCommonQianpi> tkCommonQianpis = tkCommonQianpiExtMapper.qianpiList(map);
            tkCommonTask.setTkCommonQianpi(tkCommonQianpis);

            if (StringUtils.isNotBlank(tkCommonTask.getGuishuCode())) {
                //塞入归属类型
                BsCommonExample bsCommonExample = new BsCommonExample();
                BsCommonExample.Criteria criteria2 = bsCommonExample.createCriteria();
                criteria2.andIdEqualTo(tkCommonTask.getGuishuCode());
                List<BsCommon> bsCommons = bsCommonService.selectByExample(bsCommonExample);
                if (bsCommons != null && bsCommons.size() > 0) {
                    tkCommonTask.setGuishuName(bsCommons.get(0).getName());
                }
            }


            //查询最后一条指派人信息
            List<TkCommonAssigned> tkCommonAssigneds = getTkCommonAssigneds(id);
            if (tkCommonAssigneds.size() > 0) {
                //塞入最后一个被指派人id
                tkCommonTask.setAssBeassignedUserId(tkCommonAssigneds.stream().map(TkCommonAssigned::getBeassignedUserId).collect(Collectors.joining(",")));
                //塞入最后一个被指派人角色等级
                tkCommonTask.setAssBeassignedRole(tkCommonAssigneds.stream().map(TkCommonAssigned::getBeassignedRole).map(String::valueOf).collect(Collectors.joining(",")));
                tkCommonTask.setAssBeassignedUserName(tkCommonAssigneds.stream().map(TkCommonAssigned::getBeassignedUserName).map(String::valueOf).collect(Collectors.joining(",")));

                //塞入最后一个指派人id
                tkCommonTask.setAssAssignedUserId(tkCommonAssigneds.get(0).getAssignedUserId());
                //塞入最后一个指派人姓名
                tkCommonTask.setAssAssignedUserName(tkCommonAssigneds.get(0).getAssignedUserName());
                //塞入最后一个被指派说明
                tkCommonTask.setAssAssignedNode(tkCommonAssigneds.get(0).getAssignedNode());
                //塞入最后一个指派的时间
                tkCommonTask.setAssAssignedCreatetime(tkCommonAssigneds.get(0).getCreateTime());
            } else {
                //塞入最后一个指派人id
                tkCommonTask.setAssAssignedUserId(tkCommonTask.getAssignedUserId());
                //塞入最后一个指派人姓名
                tkCommonTask.setAssAssignedUserName(tkCommonTask.getAssignedUserName());
            }

            //塞入当前工单的判定是否被确认的
            tkCommonTask.setLeaderZSValue(getReceiveType(tkCommonTask, 1, loginUserId));//领导指示是否被确认
            tkCommonTask.setZDBValue(getReceiveType(tkCommonTask, 2, loginUserId));//转督办是否被确认
            tkCommonTask.setCSValue(getReceiveType(tkCommonTask, 3, loginUserId));//抄送是否被确认


            //用户微信小程序和app展示反馈所用
            if (tkCommonTask.getIsZhuanzhifa() == null) {
                tkCommonTask.setFeedback(tkCommonTask.getPerformNode());
            }
            //是否转执法 0未转 1转
            if (tkCommonTask.getIsZhuanzhifa() != null && tkCommonTask.getIsZhuanzhifa() == 1) {
                if (tkCommonTask.getIsZhifalian() != null && tkCommonTask.getIsZhifalian() == 0) {
                    tkCommonTask.setFeedback("转执法局处理");
                }
                if (tkCommonTask.getIsZhifalian() != null && tkCommonTask.getIsZhifalian() == 1) {
                    tkCommonTask.setFeedback(tkCommonTask.getZhifashuoming());
                }
            }
            if (StringUtils.isNotBlank(tkCommonTask.getQprIds())){
                List<SysUser> users = sysUserService.listByIds(Arrays.asList(tkCommonTask.getQprIds().split(",")));
                tkCommonTask.setQprNames(users.stream().map(SysUser::getNickName).collect(Collectors.joining(",")));
            }
            this.button(tkCommonTask);
            return AjaxResult.success(tkCommonTask);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(400,"查询出错");
        }
    }

    private void button(TkCommonTask tkCommonTask){
        String loginUserId = this.getUserId();
        if (tkCommonTask.getTkStatus() >= 40){
            //领导核查后只能闭环
            return;
        }
        //是否能指派部门
        if (StringUtils.isNotBlank(tkCommonTask.getQprIds()) && tkCommonTask.getQprIds().contains(loginUserId)) {
            //签批人可指派部门
            tkCommonTask.setCanAssignedDept(true);
        }
        //是否能指派处理人
        List<SysDept> depts = StringUtils.isBlank(tkCommonTask.getAssignedDeptIds()) ? Collections.emptyList()
                : deptService.selectDeptByIds(Arrays.stream(tkCommonTask.getAssignedDeptIds().split(",")).map(Long::valueOf).collect(Collectors.toList()));
        List<String> deptAssignedUserIds = depts.stream().flatMap(new Function<SysDept, Stream<String>>() {
            @Override
            public Stream<String> apply(SysDept sysDept) {
                if (StringUtils.isBlank(sysDept.getTaskAssignedUserIds())){
                    return null;
                }
                return Arrays.stream(sysDept.getTaskAssignedUserIds().split(","));
            }
        }).collect(Collectors.toList());
        tkCommonTask.setAssignedDeptUserIds(deptAssignedUserIds);
        if (deptAssignedUserIds.contains(loginUserId)){
            //部门工单处理人可指派工单
            tkCommonTask.setCanAssigned(true);
        }
        if (TkStatusEnum.t_17.getCode().equals(tkCommonTask.getTkStatus()) && loginUserId.equals(tkCommonTask.getAssignedUserId())){
            //指派人才有接收退回的按钮
            tkCommonTask.setCanAcceptBack(true);
        }
    }

    private boolean getReceiveType(TkCommonTask tkCommonTask, int type, String loginUserId) {
        TkCommonReceiveExample tkCommonReceiveExample = new TkCommonReceiveExample();
        TkCommonReceiveExample.Criteria criteria2 = tkCommonReceiveExample.createCriteria();
        criteria2.andCommonTkIdEqualTo(tkCommonTask.getId());
        criteria2.andTypeEqualTo(type);
        criteria2.andUserIdEqualTo(loginUserId);
        criteria2.andStatusEqualTo("0");//未解决
        List<TkCommonReceive> tkCommonReceives = tkCommonReceiveService.selectByExample(tkCommonReceiveExample);
        if (tkCommonReceives.size() > 0) {
            return true;
        }
        return false;
    }


    /**
     * 任务指派接口
     */
    @RequestMapping(value = "assigned", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult assigned(@RequestBody TaskAssignedRequest request) {
        try {
            if (tkCommonAssignedService.assigned(request) == 0) {
                return AjaxResult.error(400,"指派出错");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("指派出错",400);
        }
        return AjaxResult.success("指派成功");
    }

    /**
     * 任务指派部门接口
     */
    @RequestMapping(value = "assignedDept", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult assignedDept(@RequestBody TaskAssignedDeptRequest request) {
        request.setLoginUserId(this.getUserId());
        request.setLoginUserName(this.getLoginUser().getUser().getNickName());
        tkCommonAssignedService.assignedDept(request);
        return AjaxResult.success("指派成功");
    }

    /**
     * 替换附件
     *
     * @param tkCommonTask
     * @return
     */
    @RequestMapping(value = "replaceFile", method = RequestMethod.POST)
    @ResponseBody
    public String replaceFile(@RequestBody TkCommonTask tkCommonTask) {
        if (tkCommonTask == null || StringUtils.isBlank(tkCommonTask.getId())
                || StringUtils.isBlank(tkCommonTask.getFilePath())) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "替换失败：缺少必要参数"));
        }
        TkCommonTask task = tkCommonTaskService.selectByPrimaryKey(tkCommonTask.getId());
        if (task == null) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "替换失败：找不到当前工单"));
        }
        task.setFilePath(tkCommonTask.getFilePath());
        int index = tkCommonTaskService.updateByPrimaryKey(task);
        if (index == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "替换失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "替换成功"));
    }

    /**
     * 替换依据
     *
     * @param tkCommonTask
     * @return
     */
    @RequestMapping(value = "replacePicture", method = RequestMethod.POST)
    @ResponseBody
    public String replacePicture(@RequestBody TkCommonTask tkCommonTask) {
        if (tkCommonTask == null || StringUtils.isBlank(tkCommonTask.getId())
                || StringUtils.isBlank(tkCommonTask.getPerformPicture())) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "替换失败：缺少必要参数"));
        }
        TkCommonTask task = tkCommonTaskService.selectByPrimaryKey(tkCommonTask.getId());
        if (task == null) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "替换失败：找不到当前工单"));
        }
        task.setPerformPicture(tkCommonTask.getPerformPicture());
        int index = tkCommonTaskService.updateByPrimaryKey(task);
        if (index == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "替换失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "替换成功"));
    }

    /**
     * 接受拒绝任务接口
     *
     * @param id                  任务id
     * @param loginUserId         当前登录人id
     * @param loginUserName       当前登录人用户名
     * @param loginUserBelongGrid 当前登录人网格
     * @param isAgree             是否同意
     * @return
     */
    @RequestMapping(value = "agreeTask", method = RequestMethod.POST)
    @ResponseBody
    public String agreeTask(String id,
                            String loginUserId, String loginUserName,
                            String loginUserBelongGrid,
                            boolean isAgree, String returnReason) {

        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        String node = "";
        String back = "";
        if (isAgree) {//接收任务
            tkCommonTask.setTkStatus(20);//接收任务
            tkCommonTask.setPerformUserId(loginUserId);//保存执行人。接收以后，执行人就是当前登录人
            tkCommonTask.setPerformUserName(loginUserName);
            node = "接受了任务";
            back = "接受任务";
        } else {//退回任务
            tkCommonTask.setTkStatus(17);//退回任务
            node = "申请退回了任务";
            back = "申请退回任务";
        }
        if (tkCommonTaskService.agreeTask(tkCommonTask, id, loginUserName, loginUserBelongGrid, null, node, isAgree, returnReason, loginUserId) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", back + "出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", back + "成功"));
    }


    /**
     * 接受退回 和拒绝退回
     *
     * @param id                  任务id
     * @param loginUserId         当前登录人id
     * @param loginUserName       当前登录人用户名
     * @param loginUserBelongGrid 当前登录人网格
     * @param isAgree             是否同意
     * @return
     */
    @RequestMapping(value = "agreeBack", method = RequestMethod.POST)
    @ResponseBody
    public String agreeBack(String id,
                            String loginUserId, String loginUserName,
                            String loginUserBelongGrid,
                            boolean isAgree, String returnReason) {

        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        String node = "";
        String back = "";
        if (isAgree) {//接收退回  任务到待指派状态
            tkCommonTask.setTkStatus(16);//待指派状态
            node = "接受退回任务";
            back = "接受退回任务";
        } else {//退回任务
            tkCommonTask.setTkStatus(12);//拒绝退回 任务到已指派状态
            node = "拒绝退回了任务";
            back = "拒绝退回任务";
        }
        if (tkCommonTaskService.agreeBack(tkCommonTask, id, loginUserName, loginUserBelongGrid, null, node, isAgree, returnReason, loginUserId) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", back + "出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", back + "成功"));
    }


    /**
     * 开始任务（完成任务）
     * @return
     */
    @RequestMapping(value = "startTask", method = RequestMethod.POST)
    @ResponseBody
    public String startTask(@Valid @RequestBody StartTaskRequest request) {
        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(request.getId());
        if (tkCommonTask.getHandleType() == 0) {
            tkCommonTask.setTkStatus(50);//任务核查阶段
        } else {
            tkCommonTask.setTkStatus(30);//任务核查阶段
        }
        tkCommonTask.setPerformUserId(request.getLoginUserId());//执行人
        tkCommonTask.setPerformUserName(request.getLoginUserName());//执行人用户名
        tkCommonTask.setPerformPicture(request.getPerformPicture());//处理图片
        tkCommonTask.setPerformNode(request.getPerformNode());//处理说明

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date assignedTime = null;
        try {
            String format = sdf.format(new Date());
            assignedTime = sdf.parse(format);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tkCommonTask.setAssignedTime(assignedTime);//完成任务的时间


        //数据 上报上级的接收人数据 所以当前登录角色为2级 就查询中心的用户。
        AjaxResult result2 = new AjaxResult();//根据角色获取用户们
        sysRoleService.getUserByRoleCode("twogrid",  result2);

        if (tkCommonTaskService.startTask(
                tkCommonTask, request.getId(), request.getLoginUserName(), request.getLoginUserBelongGrid(), null,
                "任务处理完成", request.getLoginUserRole(), request.getLoginUserId(), result2, request.getLoginWgCode(),
                request.getLoginUserRole()) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务处理出错"));
        }

        //更新受理意见的接口如下：（在《投诉监管》处理任务时进行调用）
        if (StringUtils.isNotBlank(tkCommonTask.getFormId())) {
            accomplishTask(request.getId(), "text", 1);
        }

        //如果是12345工单 核查人设为签批人
        if (tkCommonTask.getComeFrom()!=null && tkCommonTask.getComeFrom() == 3 && StringUtils.isNotBlank(tkCommonTask.getQprId())){
            String verificationUserId = tkCommonTask.getQprIds().split(",")[0];
            SysUser sysUser = sysUserService.selectUserById(verificationUserId);
            String verificationUserName = sysUser.getNickName();
            String verificationEndTime = LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            return this.verificationPerson(
                    tkCommonTask.getId(),request.getLoginUserId(),request.getLoginUserName(),request.getLoginUserBelongGrid(),
                    verificationUserId,verificationUserName,verificationEndTime,null
            );
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "任务处理成功"));
    }


    /**
     * 跳过核查
     */
    @RequestMapping(value = "jumpOverHecha", method = RequestMethod.POST)
    @ResponseBody
    public String jumpOverHecha(String id,
                                String loginUserId, String loginUserName, String loginUserBelongGrid) {

        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        String node = "";
        tkCommonTask.setVerificationUserId(loginUserId);
        tkCommonTask.setVerificationUserName(loginUserName);
        tkCommonTask.setVerificationEndTime(new Date());
        tkCommonTask.setVerificationNode("");
        tkCommonTask.setZpVerificationUserId(loginUserId);
        tkCommonTask.setZpVerificationUserName(loginUserName);
        tkCommonTask.setVerificationStatus(0);//核查状态 0通过 1不通过
        tkCommonTask.setTkStatus(40);//核查通过 即是评价状态了
        node = "跳过核查";


        if (tkCommonTaskService.jumpOverHecha(tkCommonTask, id, loginUserName, loginUserBelongGrid, null, node, loginUserId) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", node + "出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", node + "成功"));
    }

    /**
     * 指派核查人
     *
     * @param id                   任务id
     * @param loginUserId          登录人id
     * @param loginUserName        登录人姓名
     * @param loginUserBelongGrid  登录人网格
     * @param verificationUserId   核查人id
     * @param verificationUserName 核查人姓名
     * @param verificationEndTime  核查完成期限
     * @param verificationNode     核查说明
     * @return
     */
    @RequestMapping(value = "verificationPerson", method = RequestMethod.POST)
    @ResponseBody
    public String verificationPerson(String id,
                                     String loginUserId, String loginUserName, String loginUserBelongGrid,
                                     String verificationUserId, String verificationUserName,
                                     String verificationEndTime, String verificationNode) {

        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        tkCommonTask.setVerificationUserId(verificationUserId);
        tkCommonTask.setVerificationUserName(verificationUserName);
        tkCommonTask.setVerificationEndTime(DateUtil.getDate(verificationEndTime,DateUtil.DATATIMEF_STR));
        tkCommonTask.setVerificationNode(verificationNode);
        tkCommonTask.setZpVerificationUserId(loginUserId);
        tkCommonTask.setZpVerificationUserName(loginUserName);
        tkCommonTask.setTkStatus(34);
        String verificationUserBelongGrid = "";
        List<GridRegionUser> gridRegionUsers = bsWgxxUserService.getPermissionWgCodes(verificationUserId);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(gridRegionUsers)){
            GridRegionExample bsWgxxbExample = new GridRegionExample();
            bsWgxxbExample.createCriteria().andWgCodeIn(
                    gridRegionUsers.stream().map(GridRegionUser::getWgId).collect(Collectors.toList())
            );
            List<GridRegion> gridRegions = bsWgxxbService.selectByExample(bsWgxxbExample);
            verificationUserBelongGrid = gridRegions.stream().map(GridRegion::getWgName).collect(Collectors.joining(","));
        }
        //指派了核查人【网格2】雷佳瑶2号
        String node = "指派了核查人【" + verificationUserBelongGrid + "】" + verificationUserName;
        if (tkCommonTaskService.verificationPerson(tkCommonTask, id, loginUserName, loginUserBelongGrid, null, node, loginUserId) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "指派出错"));
        }
        //发送短信
        try {
            if (smsswitch) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", verificationUserName);
                map.put("address", verificationUserBelongGrid);
                map.put("taskId", id);
                map.put("type", "核查");
                map.put("taskName", tkCommonTask.getTkName());
                //根据用户id获取用户信息
                SysUser userInfo = sysUserService.selectUserById(verificationUserId);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        workMSGUtils.sendDXSMS(userInfo, map);
                    }
                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("指派短信发送失败");
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "指派成功"));
    }

    /**
     * 核查任务
     *
     * @param id
     * @param loginUserId
     * @param loginUserName
     * @param loginUserBelongGrid
     * @param verificationResult
     * @param verificationNode
     * @return
     */
    @RequestMapping(value = "verificationTask", method = RequestMethod.POST)
    @ResponseBody
    public String verificationTask(String id,
                                   String loginUserId, String loginUserName, String loginUserBelongGrid,
                                   boolean verificationResult, String verificationNode, String hechapic) {

        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        tkCommonTask.setVerificationNode(verificationNode);//覆盖核查任务
        tkCommonTask.setVerificationTime(new Date());//核查完成时间
        tkCommonTask.setHechaPic(hechapic);//核查图片

        String node = "";
        if (verificationResult) {//true 核查通过  false核查不通过
            tkCommonTask.setVerificationStatus(0);
            tkCommonTask.setTkStatus(40);//核查通过 即是评价状态了
            node = "核查通过";
        } else {
            tkCommonTask.setVerificationStatus(1);
            tkCommonTask.setTkStatus(36);
            node = "核查不通过";
        }

        if (tkCommonTaskService.verificationPerson2(tkCommonTask, id, loginUserName, loginUserBelongGrid, null, node, loginUserId) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", node + "出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", node + "成功"));

    }

    /**
     * 任务评价
     *
     * @param id
     * @param loginUserId
     * @param loginUserName
     * @param loginUserBelongGrid
     * @param score
     * @param end_node
     * @return
     */
    @RequestMapping(value = "evaluationTask", method = RequestMethod.POST)
    @ResponseBody
    public String evaluationTask(String id,
                                 String loginUserId, String loginUserName, String loginUserBelongGrid,
                                 int score, String end_node) {

        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        tkCommonTask.setTkScore(score);
        tkCommonTask.setEndNode(end_node);
        tkCommonTask.setTkStatus(50);//结束状态
        tkCommonTask.setEndTime(new Date());//评价时间
        tkCommonTask.setPjPersonId(loginUserId);
        tkCommonTask.setPjPersonName(loginUserName);


        if (tkCommonTaskService.verificationTask(tkCommonTask, id, loginUserName, loginUserBelongGrid, null, "评价了任务") == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务评价出错"));
        }

        try {
            if (tkCommonTask.getComeFrom() != null && tkCommonTask.getComeFrom() == 12) {
                TkCommonDiaoduExample tkCommonDiaoduExample = new TkCommonDiaoduExample();
                TkCommonDiaoduExample.Criteria criteria = tkCommonDiaoduExample.createCriteria();
                criteria.andDdTkidEqualTo(tkCommonTask.getId());
                List<TkCommonDiaodu> tkCommonDiaodus = tkCommonDiaoduService.selectByExample(tkCommonDiaoduExample);
                if (tkCommonDiaodus.size() > 0) {
                    TkCommonDiaodu tkCommonDiaodu = tkCommonDiaodus.get(0);
                    tkCommonDiaodu.setDdTkstatus("1");
                    tkCommonDiaoduService.updateByPrimaryKey(tkCommonDiaodu);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("修改调度状态出错");
        }


        return JSON.toJSONString(AjaxResult.build(200, "success", "任务评价成功"));

    }

    /**
     * 删除任务 逻辑删除，只有任务状态为0的才可以删除。
     * 1删除  2hst
     *
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public String deleteTask(String id, String type) {
        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        String backnode = "";
        if (StringUtils.isNotBlank(type)) {
            if (type.equals("1")) {
                tkCommonTask.setStandby1("1");//逻辑删除，存在备用字段1里面
                backnode = "删除";
            } else if (type.equals("2")) {
                tkCommonTask.setIsHst(1);//hst，存在备用字段1里面
                backnode = "转入";
            }
        }

        try {
            int i = tkCommonTaskService.updateByPrimaryKey(tkCommonTask);
            if (i == 0) {
                return JSON.toJSONString(AjaxResult.build(400, "fail", backnode + "出错"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", backnode + "出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", backnode + "成功"));
    }

    /**
     * 有效无效接口
     *
     * @return
     */
    @RequestMapping(value = "panding", method = RequestMethod.POST)
    @ResponseBody
    public String panding(String id, String loginUserId, String loginUserName,
                          String loginUserBelongGrid, String reason) {
        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);

        tkCommonTask.setIsYouxiao(1);//无效
        tkCommonTask.setTkStatus(50);
        try {
            int i = tkCommonTaskService.panding(tkCommonTask, loginUserName, loginUserBelongGrid, null, "当前订单判定为无效", reason);
            if (i == 0) {
                return JSON.toJSONString(AjaxResult.build(400, "fail", "判定出错"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "判定出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "判定成功"));
    }


    /**
     * 工单评分
     *
     * @return
     */
    @RequestMapping(value = "pingfen", method = RequestMethod.POST)
    @ResponseBody
    public String pingfen(String id, String loginUserId, String loginUserName,
                          String loginUserBelongGrid, String reason, int pingfen) {
        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        tkCommonTask.setPingfen(pingfen);
        tkCommonTask.setPingfenreason(reason);
        System.out.println(reason + "," + pingfen);
        try {
            int i = tkCommonTaskService.pingfen(tkCommonTask, loginUserName, loginUserBelongGrid, null, "评分完成", reason + "  分数：" + pingfen + "分");
            if (i == 0) {
                return JSON.toJSONString(AjaxResult.build(400, "fail", "评分出错"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "评分出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "评分成功"));
    }


    /**
     * 领导指示
     * id 任务id
     * loginUserId 登录人id
     * loginUserName 登录人姓名
     * leaders 督办
     *
     * @return
     */
    @RequestMapping(value = "zhishi", method = RequestMethod.POST)
    @ResponseBody
    public String zhishi(@RequestBody LeaderPojo pojo) {
        if (tkCommonTaskService.saveReceiveAndDynaAndMSG(pojo, 1) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "领导指示出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "领导指示成功"));
    }

    /**
     * 转督办
     */
    @RequestMapping(value = "leader", method = RequestMethod.POST)
    @ResponseBody
    public String leader(@RequestBody LeaderPojo pojo) {

        if (tkCommonTaskService.saveReceiveAndDynaAndMSG(pojo, 2) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "转督办出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "转督办成功"));
    }

    /**
     * 留言
     */
    @RequestMapping(value = "leaveMessage", method = RequestMethod.POST)
    @ResponseBody
    public String leaveMessage(@RequestBody LeaderPojo pojo) {

        if (tkCommonTaskService.leaveMessage(pojo) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "留言出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "留言成功"));
    }


    /**
     * 确认领导指示
     * id 任务id
     * loginUserId 登录人id
     * loginUserName 登录人姓名
     * leaders 督办
     *
     * @return
     */
    @RequestMapping(value = "leaderQR", method = RequestMethod.POST)
    @ResponseBody
    public String leaderQR(String id, String loginUserId, String loginUserName,
                           String loginUserBelongGrid, String reason) {
        TkCommonReceiveExample tkCommonReceiveExample = new TkCommonReceiveExample();
        TkCommonReceiveExample.Criteria criteria = tkCommonReceiveExample.createCriteria();
        criteria.andCommonTkIdEqualTo(id);
        criteria.andUserIdEqualTo(loginUserId);
        criteria.andTypeEqualTo(1);//1 领导指示  2 转督办
        criteria.andStatusNotEqualTo("1");
        List<TkCommonReceive> tkCommonReceives = tkCommonReceiveService.selectByExample(tkCommonReceiveExample);
        if (tkCommonReceives.size() > 0) {
            for (TkCommonReceive tkCommonReceive : tkCommonReceives) {
                tkCommonReceive.setStatus("1");
                tkCommonReceiveService.updateByPrimaryKey(tkCommonReceive);
            }
        }


        if (tkCommonTaskService.querenDy(id, loginUserName, loginUserBelongGrid, "确认领导指示", reason) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "领导指示出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "领导指示成功"));
    }

    /**
     * 确认转督办
     * id 任务id
     * loginUserId 登录人id
     * loginUserName 登录人姓名
     * leaders 督办
     *
     * @return
     */
    @RequestMapping(value = "ZDBQR", method = RequestMethod.POST)
    @ResponseBody
    public String ZDBQR(String id, String loginUserId, String loginUserName,
                        String loginUserBelongGrid, String reason) {
        TkCommonReceiveExample tkCommonReceiveExample = new TkCommonReceiveExample();
        TkCommonReceiveExample.Criteria criteria = tkCommonReceiveExample.createCriteria();
        criteria.andCommonTkIdEqualTo(id);
        criteria.andUserIdEqualTo(loginUserId);
        criteria.andTypeEqualTo(2);//转督办
        criteria.andStatusNotEqualTo("1");
        List<TkCommonReceive> tkCommonReceives = tkCommonReceiveService.selectByExample(tkCommonReceiveExample);
        if (tkCommonReceives.size() > 0) {
            for (TkCommonReceive tkCommonReceive : tkCommonReceives) {
                tkCommonReceive.setStatus("1");
                tkCommonReceiveService.updateByPrimaryKey(tkCommonReceive);
            }
        }


        if (tkCommonTaskService.querenDy(id, loginUserName, loginUserBelongGrid, "确认转督办", reason) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "转督办出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "转督办成功"));
    }


    /**
     * 确认抄送
     * id 任务id
     * loginUserId 登录人id
     * loginUserName 登录人姓名
     * leaders 督办
     *
     * @return
     */
    @RequestMapping(value = "CSQR", method = RequestMethod.POST)
    @ResponseBody
    public String CSQR(String id, String loginUserId, String loginUserName,
                       String loginUserBelongGrid, String reason) {
        TkCommonReceiveExample tkCommonReceiveExample = new TkCommonReceiveExample();
        TkCommonReceiveExample.Criteria criteria = tkCommonReceiveExample.createCriteria();
        criteria.andCommonTkIdEqualTo(id);
        criteria.andUserIdEqualTo(loginUserId);
        criteria.andTypeEqualTo(3);//抄送
        criteria.andStatusNotEqualTo("1");
        List<TkCommonReceive> tkCommonReceives = tkCommonReceiveService.selectByExample(tkCommonReceiveExample);
        if (tkCommonReceives.size() > 0) {
            for (TkCommonReceive tkCommonReceive : tkCommonReceives) {
                tkCommonReceive.setStatus("1");
                tkCommonReceiveService.updateByPrimaryKey(tkCommonReceive);
            }
        }


        if (tkCommonTaskService.querenDy(id, loginUserName, loginUserBelongGrid, "确认抄送", reason) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "确认抄送出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "确认抄送成功"));
    }


    /**
     * 根据巡查任务的事项id获取事项详情
     *
     * @return
     */
    @RequestMapping(value = "roundMatter", method = RequestMethod.GET)
    @ResponseBody
    public String roundMatter(String tkRoundMatterId) {
        try {
            TkRoundMatter tkRoundMatter = tkRoundMatterService.selectByPrimaryKey(tkRoundMatterId);
            GridItemDaily bsRcsxb = bsRcsxbService.selectByPrimaryKey(tkRoundMatter.getStandby1());
            if (bsRcsxb != null) {
                tkRoundMatter.setYlzd4(bsRcsxb.getYlzd4());
                tkRoundMatter.setYlzd5(bsRcsxb.getYlzd5());
                tkRoundMatter.setSjfl(bsRcsxb.getSjfl());
            }

            return JSON.toJSONString(AjaxResult.build(200, "success", tkRoundMatter));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "查询出错"));
        }
    }


    /**
     * 催办
     *
     * @param id
     * @param loginUserId
     * @param loginUserName
     * @param loginUserBelongGrid
     * @return
     */
    @RequestMapping(value = "cuiBan", method = RequestMethod.POST)
    @ResponseBody
    public String CuiBan(String id,
                         String loginUserId, String loginUserName,
                         String loginUserBelongGrid, String cuiBanReason) {

        //存入动态，发送通知。
        try {
            int i = tkCommonTaskService.saveDynamic2(id, loginUserName, loginUserBelongGrid, null, "催办了工作", cuiBanReason);
            if (i == 0) {
                return JSON.toJSONString(AjaxResult.build(400, "fail", "催办出错"));
            }
            //发送短信
            try {
                if (smsEnable) {
                    TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("name", tkCommonTask.getPerformUserName());
                    map.put("address", "");
                    map.put("taskId", id);
                    map.put("type", "处理");
                    map.put("taskName", tkCommonTask.getTkName());
                    //根据用户id获取用户信息
                    List<String> userIds = new ArrayList<>();
                    userIds.add(tkCommonTask.getPerformUserId());
                    //发送通知
                    workMSGUtils.sendMsg(loginUserId, loginUserName, userIds, cuiBanReason, tkCommonTask.getMatterType(), tkCommonTask.getId());
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("催办短信发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "催办出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "催办成功"));

    }


    /**
     * 协调协助
     * id 任务id
     * loginUserId 登录人id
     * loginUserName 登录人姓名
     *
     * @return
     */
    @RequestMapping(value = "xietiao", method = RequestMethod.POST)
    @ResponseBody
    public String xietiao(@RequestBody LeaderPojo pojo) {
        JSONArray ja = JSONArray.parseArray(JSONObject.toJSONString(pojo.getLeaders()));

        if (tkCommonTaskService.insertXieTiao(pojo.getId(), pojo.getLoginUserId(), ja, pojo.getLoginUserName(), pojo.getLoginUserBelongGrid()) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "协调协助出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "协调协助成功"));
    }


    /**
     * 领导签批
     * id 任务id
     * loginUserId 登录人id
     * loginUserName 登录人姓名
     *
     * @return
     */
    @RequestMapping(value = "qianPi", method = RequestMethod.POST)
    @ResponseBody
    public String qianPi(@RequestBody LeaderPojo pojo) {
        JSONArray ja = JSONArray.parseArray(JSONObject.toJSONString(pojo.getLeaders()));

        if (tkCommonTaskService.insertQianPi(pojo.getId(), pojo.getNote(), pojo.getLoginUserId(), ja, pojo.getLoginUserName(), pojo.getLoginUserBelongGrid()) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "领导签批出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "领导签批成功"));
    }


    /**
     * 申请延时
     *
     * @param id
     * @param loginUserId
     * @param loginUserName
     * @param loginUserBelongGrid
     * @return
     */
    @RequestMapping(value = "applyDelay", method = RequestMethod.POST)
    @ResponseBody
    public String applyDelay(String id,
                             String loginUserId, String loginUserName,
                             String loginUserBelongGrid, String delayTime) {

        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        tkCommonTask.setTkStatus(22);//申请延期状态
        tkCommonTask.setStandby4(delayTime);//申请延时时间(未同意时暂时存储，同意后覆盖完成期限时间）
        int i = tkCommonTaskService.applyDelay(tkCommonTask, loginUserName, loginUserBelongGrid, loginUserId);
        if (i == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "申请延期出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "申请延期成功"));
    }


    /**
     * 同意拒绝延时
     *
     * @param id
     * @param loginUserId         登录人id
     * @param loginUserName       登录人用户名
     * @param loginUserBelongGrid 登录人所属网格
     * @param isAgree             true 同意  false 拒绝
     * @return
     */
    @RequestMapping(value = "agreeDelay", method = RequestMethod.POST)
    @ResponseBody
    public String agreeDelay(String id,
                             String loginUserId, String loginUserName,
                             String loginUserBelongGrid, boolean isAgree) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;


        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        TkCommonAssigned tkCommonAssigned = null;
        //获取最后一条指派记录
        List<TkCommonAssigned> tkCommonAssigneds = getTkCommonAssigneds(id);//获取指派表信息
        String node = "";
        if (isAgree) {//同意延时
            node = "延时同意";
            tkCommonTask.setTkStatus(24);//设置同意状态
            try {
                date = sdf.parse(tkCommonTask.getStandby4());
            } catch (Exception e) {
                e.printStackTrace();
            }
            tkCommonTask.setAssignedEndTime(date);//任务表 执行完成时间  覆盖执行时间


            if (tkCommonAssigneds.size() > 0) {
                tkCommonAssigned = tkCommonAssigneds.get(0);
                tkCommonAssigned.setAssignedEndTime(date);//覆盖指派表的 执行时间
            }

        } else {//拒绝延时
            node = "延时拒绝";
            tkCommonTask.setTkStatus(26);
        }

        if (tkCommonTaskService.agreeDelay(tkCommonTask, tkCommonAssigned, loginUserName, loginUserBelongGrid, node, loginUserId, isAgree, tkCommonAssigneds.get(0).getBeassignedUserId()) == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", node + "出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", node + "成功"));

    }


    /**
     * 回收站列表
     *
     * @param tkName
     * @param comeFrom type 1查询回收站  2查询hst
     * @return
     */
    @RequestMapping(value = "recycle", method = RequestMethod.POST)
    @ResponseBody
    public String recycle(String tkName, String comeFrom, String createTime, String loginUserId,
                          int pageNum, int pageSize, String type) {

        TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
        if (StringUtils.isNotBlank(tkName)) {
            criteria.andTkNameLike("%" + tkName + "%");
        }
        if (comeFrom != null) {
            criteria.andComeFromEqualTo(Integer.parseInt(comeFrom));
        }


        if (StringUtils.isNotBlank(createTime)) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                criteria.andReleaseTimeEqualTo(sdf.parse(createTime));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(type)) {
            if (type.equals("1")) {
                criteria.andStandby1EqualTo("1");//搜索删除的数据
                if (StringUtils.isNotBlank(loginUserId)) criteria.andReleaseUserIdEqualTo(loginUserId);
            } else if (type.equals("2")) {
                criteria.andIsHstEqualTo(1);
            }
        }


        tkCommonTaskExample.setOrderByClause("create_time desc");
        PageHelper.startPage(pageNum, pageSize);
        List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
        int recordCount = tkCommonTaskService.countByExample(tkCommonTaskExample);//总记录数

        ZQTPageModel<TkCommonTask> result = new ZQTPageModel<>();
        //分页
        result.setItemList(tkCommonTasks);
        //总记录数
        result.setRecordCount(recordCount);
        //总页数
        result.setPageCount((recordCount + pageSize - 1) / pageSize);
        //当前页
        result.setCurPage(recordCount == 0 ? 0 : pageNum);
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }


    /**
     * 任务还原
     *
     * @return
     */
    @RequestMapping(value = "revert", method = RequestMethod.POST)
    @ResponseBody
    public String revert(String ids) {
        String[] p = ids.split(",");
        List<String> strsToList1 = Arrays.asList(p);
        TkCommonTaskExample TkCommonTaskExample = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteria = TkCommonTaskExample.createCriteria();
        criteria.andIdIn(strsToList1);
        List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(TkCommonTaskExample);
        if (tkCommonTasks.size() == 0) {
            return JSON.toJSONString(AjaxResult.build(200, "success", "未找到数据"));
        }
        int i = tkCommonTaskService.revert(tkCommonTasks);
        if (i == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务还原出错"));
        }

        return JSON.toJSONString(AjaxResult.build(200, "success", "任务还原成功"));
    }


    /**
     * 任务从hst工单到正常工单
     *
     * @return
     */
    @RequestMapping(value = "backPuTong", method = RequestMethod.POST)
    @ResponseBody
    public String backPuTong(String ids) {
        String[] p = ids.split(",");
        List<String> strsToList1 = Arrays.asList(p);
        TkCommonTaskExample TkCommonTaskExample = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteria = TkCommonTaskExample.createCriteria();
        criteria.andIdIn(strsToList1);
        List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(TkCommonTaskExample);
        if (tkCommonTasks.size() == 0) {
            return JSON.toJSONString(AjaxResult.build(200, "success", "未找到数据"));
        }
        int i = tkCommonTaskService.backPuTong(tkCommonTasks);
        if (i == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务还原出错"));
        }

        return JSON.toJSONString(AjaxResult.build(200, "success", "任务还原成功"));
    }

    /**
     * 任务删除
     *
     * @return
     */
    @RequestMapping(value = "delete2", method = RequestMethod.POST)
    @ResponseBody
    public String delete2(String ids, String type) {
        String[] split = ids.split(",");
        if (StringUtils.isNotBlank(type) && type.equals("1")) {
            try {
                if (split.length > 0) {
                    for (int i = 0; i < split.length; i++) {
                        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(split[i]);
                        tkCommonTask.setStandby1("1");
                        tkCommonTask.setIsHst(0);
                        tkCommonTaskService.updateByPrimaryKey(tkCommonTask);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return JSON.toJSONString(AjaxResult.build(400, "fail", "任务删除出错"));
            }
        } else {
            try {
                int i = tkCommonTaskService.delete2(split);
                if (i == 0) {
                    return JSON.toJSONString(AjaxResult.build(400, "fail", "任务删除出错"));
                }
            } catch (Exception e) {
                e.printStackTrace();
                return JSON.toJSONString(AjaxResult.build(400, "fail", "任务删除出错"));
            }
        }


        return JSON.toJSONString(AjaxResult.build(200, "success", "任务删除成功"));
    }


    /**
     * 根据subtaskId 获取任务详情
     *
     * @param roundSubtaskId
     * @return
     */
    @RequestMapping(value = "getTaskBySubtaskId", method = RequestMethod.GET)
    @ResponseBody
    public String getTaskBySubtaskId(String roundSubtaskId) {

        try {
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andRoundSubtaskIdEqualTo(roundSubtaskId);
            criteria.andStandby1EqualTo("0");
            TkCommonTask tkCommonTask = tkCommonTaskService.selectFirstByExample(tkCommonTaskExample);
            return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTask));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务获取出错"));
        }

    }

    @RequestMapping(value = "getTaskByUserId", method = RequestMethod.GET)
    @ResponseBody
    public String getTaskByUserId(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10") int pageSize, String userId, String roleCode, Integer matterType) {

        try {
            Map<String, Object> map = new HashedMap();
            map.put("roleCode", roleCode);
            map.put("userId", userId);
            if (matterType != null) {
                map.put("matterType", matterType);
            }
            map.put("currIndex", (pageNum - 1) * pageSize);
            map.put("pageSize", pageSize);
            List<Map<String, Object>> taskByUserId = tkCommonTaskService.getTaskByUserId(map);
            return JSON.toJSONString(AjaxResult.build(200, "success", taskByUserId));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务获取出错"));
        }

    }

    /**
     * 根据网格id 任务名称 获取日常任务列表  新增接口
     *
     * @param wgCode
     * @param type   1城乡综合网格、2企业网格、3资产网格
     * @return
     */
    @RequestMapping(value = "getTaskListByWgCodeAndName", method = RequestMethod.GET)
    @ResponseBody
    public String getTaskListByWgCodeAndName(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "10") int pageSize, String wgCode, String tkName, Integer type) {
        try {
            ZQTPageModel<TkCommonTask> result = new ZQTPageModel<>();
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andWgCodeLike("%" + wgCode + "%");
            if (tkName != null) {
                criteria.andTkNameLike("%" + tkName + "%");
            }
            criteria.andStandby1EqualTo("0");
            if (type != null) {
                criteria.andMatterTypeEqualTo(type);
            }

            tkCommonTaskExample.setOrderByClause("create_time desc");


            List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExampleForStartPage(tkCommonTaskExample, pageNum, pageSize);

            int count = tkCommonTaskService.countByExample(tkCommonTaskExample);
            result.setItemList(tkCommonTasks);
            result.setRecordCount(count);
            result.setCurPage(pageNum);
            result.setPageCount((count + pageSize - 1) / pageSize);
            return JSON.toJSONString(AjaxResult.build(200, "success", result));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务获取出错"));
        }
    }

    /**
     * 待办任务详情接口/指派未处理  新增接口
     *
     * @param userId
     * @param matterType 1城乡综合网格、2企业网格、3资产网格
     * @return
     */
    @RequestMapping(value = "toDoTask", method = RequestMethod.GET)
    @ResponseBody
    public String toDoTask(String userId, Integer matterType) {

        try {
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andTkStatusEqualTo(12);//已指派未接受
            criteria.andPerformUserIdEqualTo(userId);
            if (matterType != null) {
                criteria.andMatterTypeEqualTo(matterType);
            }
            criteria.andStandby1EqualTo("0");
            tkCommonTaskExample.setOrderByClause("create_time desc");
            List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
            return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务获取出错"));
        }

    }


    /**
     * 待办任务数量接口
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "toDoTaskCount", method = RequestMethod.GET)
    @ResponseBody
    public String toDoTaskCount(String userId) {

        try {
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andTkStatusEqualTo(12);//已指派未接受
            criteria.andPerformUserIdEqualTo(userId);
            criteria.andStandby1EqualTo("0");
            int daiban = tkCommonTaskService.countByExample(tkCommonTaskExample);//待办数量
            Map<String, Object> leaderMap = new HashMap<String, Object>();
            leaderMap.put("userId", userId);
            Integer duban = tkCommonTaskExtMapper.getLeaderCount(leaderMap);

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("daiban", daiban);
            map.put("duban", duban);
            return JSON.toJSONString(AjaxResult.build(200, "success", map));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务获取出错"));
        }

    }

    private int returnyouxiao(String userId, Date startTime, Date endTime, int type) {
        TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
        if (type == 1) {
            criteria.andIsYouxiaoEqualTo(0);//有效工单
        } else if (type == 2) {
            criteria.andIsYouxiaoEqualTo(1);//无效工单
        }
        criteria.andIsHstEqualTo(0);
        criteria.andStandby1EqualTo("0");
        criteria.andReleaseUserIdEqualTo(userId);
        if (startTime != null && endTime == null) {
            criteria.andReleaseTimeEqualTo(startTime);
        }
        if (startTime != null && endTime != null) {
            criteria.andReleaseTimeBetween(startTime, endTime);
        }


        return tkCommonTaskService.countByExample(tkCommonTaskExample);
    }

    private int returnhst(String userId, Date startTime, Date endTime) {
        TkCommonTaskExample tkCommonTaskExamplehst = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteriahst = tkCommonTaskExamplehst.createCriteria();
        criteriahst.andIsHstEqualTo(1);//hst工单库
        criteriahst.andStandby1EqualTo("0");
        criteriahst.andReleaseUserIdEqualTo(userId);
        if (startTime != null && endTime == null) {
            criteriahst.andReleaseTimeEqualTo(startTime);
        }
        if (startTime != null && endTime != null) {
            criteriahst.andReleaseTimeBetween(startTime, endTime);
        }
        return tkCommonTaskService.countByExample(tkCommonTaskExamplehst);
    }

    private int returnscore(String userId, Date startTime, Date endTime, int type) {
        TkCommonTaskExample tkCommonTaskExample2score = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteria2score = tkCommonTaskExample2score.createCriteria();
        criteria2score.andStandby1EqualTo("0");
        criteria2score.andReleaseUserIdEqualTo(userId);
        if (type == 1) {
            criteria2score.andPingfenLessThanOrEqualTo(3);
            criteria2score.andPingfenNotEqualTo(0);
        } else if (type == 2) {
            criteria2score.andPingfenEqualTo(4);
        } else if (type == 3) {
            criteria2score.andPingfenEqualTo(5);
        }

        if (startTime != null && endTime == null) {
            criteria2score.andReleaseTimeEqualTo(startTime);
        }
        if (startTime != null && endTime != null) {
            criteria2score.andReleaseTimeBetween(startTime, endTime);
        }
        return tkCommonTaskService.countByExample(tkCommonTaskExample2score);
    }

    /**
     * 评分标准接口
     *
     * @param userId      用户id
     * @param wgCodeThree 网格code（三级）
     * @param wgCodeTwo   网格code（二级）
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @return
     */
    @RequestMapping(value = "scoreStandard", method = RequestMethod.GET)
    @ResponseBody
    public String scoreStandard(String userId, String userName, String wgCodeThree, String wgCodeTwo, Date startTime, Date endTime) {
        try {
            List<Map<String, Object>> list = new ArrayList<>();

            int youxiao = 0;
            int hst = 0;
            int wuxiao = 0;
            int taskzhiliang1score = 0;
            int taskzhiliang2score = 0;
            int taskzhiliang3score = 0;
            if (StringUtils.isNotBlank(userId)) {
                Map<String, Object> map = new HashMap<String, Object>();
                youxiao = returnyouxiao(userId, startTime, endTime, 1);
                wuxiao = returnyouxiao(userId, startTime, endTime, 2);
                hst = returnhst(userId, startTime, endTime);
                taskzhiliang1score = returnscore(userId, startTime, endTime, 1);
                taskzhiliang2score = returnscore(userId, startTime, endTime, 2);
                taskzhiliang3score = returnscore(userId, startTime, endTime, 3);


                map.put("userId", userId);//用户id
                map.put("userName", userName);//用户名
                map.put("youxiao", youxiao);//有效工单
                map.put("wuxiao", wuxiao);//无效工单
                map.put("hst", hst);//hst
                map.put("taskzhiliang1score", taskzhiliang1score);//1分数量
                map.put("taskzhiliang2score", taskzhiliang2score);//2分数量
                map.put("taskzhiliang3score", taskzhiliang3score);//3分数量
                list.add(map);
            } else if (StringUtils.isNotBlank(wgCodeThree)) {
                List<Map<String, String>> userIdsByWgCodeThree = getUserIdsByWgCode(wgCodeThree, 1);
                if (userIdsByWgCodeThree != null && userIdsByWgCodeThree.size() > 0) {
                    for (int i = 0; i < userIdsByWgCodeThree.size(); i++) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        youxiao = returnyouxiao(userIdsByWgCodeThree.get(i).get("userId"), startTime, endTime, 1);
                        wuxiao = returnyouxiao(userIdsByWgCodeThree.get(i).get("userId"), startTime, endTime, 2);
                        hst = returnhst(userIdsByWgCodeThree.get(i).get("userId"), startTime, endTime);
                        taskzhiliang1score = returnscore(userIdsByWgCodeThree.get(i).get("userId"), startTime, endTime, 1);
                        taskzhiliang2score = returnscore(userIdsByWgCodeThree.get(i).get("userId"), startTime, endTime, 2);
                        taskzhiliang3score = returnscore(userIdsByWgCodeThree.get(i).get("userId"), startTime, endTime, 3);
                        map.put("userId", userIdsByWgCodeThree.get(i).get("userId"));
                        map.put("userName", userIdsByWgCodeThree.get(i).get("userName"));
                        map.put("youxiao", youxiao);//有效工单
                        map.put("wuxiao", wuxiao);//有效工单
                        map.put("hst", hst);//hst
                        map.put("taskzhiliang1score", taskzhiliang1score);//1分数量
                        map.put("taskzhiliang2score", taskzhiliang2score);//2分数量
                        map.put("taskzhiliang3score", taskzhiliang3score);//3分数量
                        list.add(map);
                    }
                }
            } else if (StringUtils.isNotBlank(wgCodeTwo)) {
                List<Map<String, String>> userIdsByWgCodeTwo = getUserIdsByWgCode(wgCodeTwo, 2);
                if (userIdsByWgCodeTwo != null && userIdsByWgCodeTwo.size() > 0) {
                    for (int i = 0; i < userIdsByWgCodeTwo.size(); i++) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        youxiao = returnyouxiao(userIdsByWgCodeTwo.get(i).get("userId"), startTime, endTime, 1);
                        wuxiao = returnyouxiao(userIdsByWgCodeTwo.get(i).get("userId"), startTime, endTime, 2);
                        hst = returnhst(userIdsByWgCodeTwo.get(i).get("userId"), startTime, endTime);
                        taskzhiliang1score = returnscore(userIdsByWgCodeTwo.get(i).get("userId"), startTime, endTime, 1);
                        taskzhiliang2score = returnscore(userIdsByWgCodeTwo.get(i).get("userId"), startTime, endTime, 2);
                        taskzhiliang3score = returnscore(userIdsByWgCodeTwo.get(i).get("userId"), startTime, endTime, 3);
                        map.put("userId", userIdsByWgCodeTwo.get(i).get("userId"));
                        map.put("userName", userIdsByWgCodeTwo.get(i).get("userName"));
                        map.put("youxiao", youxiao);//有效工单
                        map.put("wuxiao", wuxiao);//有效工单
                        map.put("hst", hst);//hst
                        map.put("taskzhiliang1score", taskzhiliang1score);//1分数量
                        map.put("taskzhiliang2score", taskzhiliang2score);//2分数量
                        map.put("taskzhiliang3score", taskzhiliang3score);//3分数量
                        list.add(map);
                    }
                }
            }


            return JSON.toJSONString(AjaxResult.build(200, "success", list));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "数量获取出错"));
        }

    }


    private List<Map<String, String>> getUserIdsByWgCode(String wgCode, int type) {
        //三级网格 就是查三级网格下的人
        //查询网格下的网格员
        GridRegionUserExample bsWgxxUserExample2 = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria2 = bsWgxxUserExample2.createCriteria();
        if (type == 1) {
            criteria2.andWgIdEqualTo(wgCode);
        } else {
            criteria2.andWgIdLike(wgCode + "%");
        }
        criteria2.andIsValidEqualTo("1");
        List<GridRegionUser> bsWgxxUsers2 = bsWgxxUserService.selectByExample(bsWgxxUserExample2);
        List<Map<String, String>> userIds = new ArrayList<Map<String, String>>();
        if (bsWgxxUsers2 != null && bsWgxxUsers2.size() > 0) {
            for (int i = 0; i < bsWgxxUsers2.size(); i++) {
                Map<String, String> map = new HashedMap();
                map.put("userId", bsWgxxUsers2.get(i).getUserId());
                map.put("userName", bsWgxxUsers2.get(i).getYlzd1());
                userIds.add(map);
            }
        }
        return userIds;
    }


    /**
     * 根据网格code(镇、村、地块) 查询 日常任务的 总数、处理中任务数量、已完成任务数量
     *
     * @return
     */
    @RequestMapping(value = "taskNum", method = RequestMethod.GET)
    @ResponseBody
    public String taskNum(String wgCode) {

        try {
            Map<String, Integer> map = new HashedMap();
            //已完成
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andWgCodeEqualTo(wgCode);
            criteria.andTkStatusEqualTo(50);//已完成
            criteria.andStandby1EqualTo("0");
            List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
            map.put("finished", tkCommonTasks.size());//塞入已完成
            //未完成
            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andWgCodeEqualTo(wgCode);
            criteria2.andTkStatusNotEqualTo(50);//未完成
            criteria2.andStandby1EqualTo("0");
            List<TkCommonTask> tkCommonTasks2 = tkCommonTaskService.selectByExample(tkCommonTaskExample2);
            map.put("unfinished", tkCommonTasks2.size());//塞入未完成

            //所有
            map.put("all", tkCommonTasks.size() + tkCommonTasks2.size());//塞入未完成

            return JSON.toJSONString(AjaxResult.build(200, "success", map));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务数量获取出错"));
        }

    }


    /**
     * 年度任务工单状态统计
     * 获取所有任务数量、已办结数量（按时办结+逾期办结）、未办结数量（逾期未办结、正常处理）、
     *
     * @return
     */
    @RequestMapping(value = "allTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String allTaskNum() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowTime = "";
        try {
            nowTime = sdf.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date releaseStartTime = DateUtils.getCurrYearFirst();//今年开始时间
        Date releaseEndTime = DateUtils.getCurrYearLast();//今年结束时间

        try {
            Map<String, Integer> map = new HashedMap();
            //所有任务数量
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            criteria.andReleaseTimeBetween(releaseStartTime, releaseEndTime);
            map.put("all", tkCommonTaskService.countByExample(tkCommonTaskExample));//所有任务数量
            //已办结数量
            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andStandby1EqualTo("0");
            criteria2.andTkStatusEqualTo(50);
            criteria2.andReleaseTimeBetween(releaseStartTime, releaseEndTime);
            map.put("endAll", tkCommonTaskService.countByExample(tkCommonTaskExample2));
            //按时办结
            Map<String, Object> onTimeMap = new HashMap<String, Object>();
            onTimeMap.put("releaseStartTime", releaseStartTime);
            onTimeMap.put("releaseEndTime", releaseEndTime);
            Integer onTimeCount = tkCommonTaskExtMapper.selectOnTimeCount(onTimeMap);
            map.put("onTimeCount", onTimeCount);
            //逾期办结
            Map<String, Object> notOnTimeMap = new HashMap<String, Object>();
            notOnTimeMap.put("releaseStartTime", releaseStartTime);
            notOnTimeMap.put("releaseEndTime", releaseEndTime);
            Integer notOnTimeCount = tkCommonTaskExtMapper.selectNotOnTimeCount(notOnTimeMap);
            map.put("notOnTimeCount", notOnTimeCount);
            //未办结数量
            TkCommonTaskExample tkCommonTaskExample3 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria3 = tkCommonTaskExample3.createCriteria();
            criteria3.andStandby1EqualTo("0");
            criteria3.andTkStatusLessThan(50);
            criteria3.andReleaseTimeBetween(releaseStartTime, releaseEndTime);
            map.put("notEndAll", tkCommonTaskService.countByExample(tkCommonTaskExample3));
            //逾期未办结
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("nowTime", nowTime);
            map2.put("releaseStartTime", releaseStartTime);
            map2.put("releaseEndTime", releaseEndTime);
            Integer notOnTimeNotOverCount = tkCommonTaskExtMapper.selectNotOnTimeNotOverCount(map2);
            map.put("notOnTimeNotOverCount", notOnTimeNotOverCount);
            //正常处理
            Integer zhengchangcl = tkCommonTaskExtMapper.zhengchangcl(map2);
            map.put("zhengchangcl", zhengchangcl);

            return JSON.toJSONString(AjaxResult.build(200, "success", map));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务数量获取出错"));
        }

    }

    @RequestMapping(value = "allTaskNumDS", method = RequestMethod.GET)
    @ResponseBody
    public String allTaskNumDS() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowTime = "";
        try {
            nowTime = sdf.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date releaseStartTime = DateUtils.getCurrYearFirst();//今年开始时间
        Date releaseEndTime = DateUtils.getCurrYearLast();//今年结束时间

        try {
            Map<String, Integer> map = new HashedMap();
            //所有任务数量
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            criteria.andCreateTimeBetween(releaseStartTime, releaseEndTime);
            map.put("all", DSOld + tkCommonTaskService.countByExample(tkCommonTaskExample));//所有任务数量
            //已办结数量
            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andStandby1EqualTo("0");
            criteria2.andTkStatusEqualTo(50);
            criteria2.andCreateTimeBetween(releaseStartTime, releaseEndTime);
            map.put("endAll", DSOld + tkCommonTaskService.countByExample(tkCommonTaskExample2));
            //按时办结
            Map<String, Object> onTimeMap = new HashMap<String, Object>();
            onTimeMap.put("releaseStartTime", releaseStartTime);
            onTimeMap.put("releaseEndTime", releaseEndTime);
            Integer onTimeCount = tkCommonTaskExtMapper.selectOnTimeCount(onTimeMap);
            map.put("onTimeCount", DSOld + onTimeCount);
            //逾期办结
            Map<String, Object> notOnTimeMap = new HashMap<String, Object>();
            notOnTimeMap.put("releaseStartTime", releaseStartTime);
            notOnTimeMap.put("releaseEndTime", releaseEndTime);
            Integer notOnTimeCount = tkCommonTaskExtMapper.selectNotOnTimeCount(notOnTimeMap);
            map.put("notOnTimeCount", notOnTimeCount);
            //未办结数量
            TkCommonTaskExample tkCommonTaskExample3 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria3 = tkCommonTaskExample3.createCriteria();
            criteria3.andStandby1EqualTo("0");
            criteria3.andTkStatusLessThan(50);
            criteria3.andCreateTimeBetween(releaseStartTime, releaseEndTime);
            map.put("notEndAll", tkCommonTaskService.countByExample(tkCommonTaskExample3));
            //逾期未办结
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("nowTime", nowTime);
            map2.put("releaseStartTime", releaseStartTime);
            map2.put("releaseEndTime", releaseEndTime);
            Integer notOnTimeNotOverCount = tkCommonTaskExtMapper.selectNotOnTimeNotOverCount(map2);
            map.put("notOnTimeNotOverCount", notOnTimeNotOverCount);
            //正常处理
            Integer zhengchangcl = tkCommonTaskExtMapper.zhengchangcl(map2);
            map.put("zhengchangcl", DSOld + zhengchangcl);

            return JSON.toJSONString(AjaxResult.build(200, "success", map));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务数量获取出错"));
        }

    }


    /**
     * 任务分类统计
     *
     * @return
     */
    @RequestMapping(value = "taskTypeStatistical", method = RequestMethod.GET)
    @ResponseBody
    public String taskTypeStatistical() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String year = sdf.format(new Date());
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
        String monthno = sdf2.format(new Date());
        List<DayAndNums> list = new ArrayList<DayAndNums>();
        try {
            ArrayList<Date> test = getDateList(7);

            SimpleDateFormat format = new SimpleDateFormat("MM/dd");
            System.out.println("----" + JSONObject.toJSONString(test));
            for (int i = 0; i < Integer.parseInt(monthno); i++) {
                Map<String, Object> month = new HashedMap();
                month.put("mm", i + 1);
                Map<String, Object> stringObjectMap = tkCommonTaskExtMapper.taskTypeStatistical(month);
                DayAndNums dayAndNums = new DayAndNums();
                dayAndNums.setMonth(i + 1 + "");
                if (stringObjectMap == null) {
                    stringObjectMap = new HashedMap();
                    stringObjectMap.put("cx", 0);
                    stringObjectMap.put("qy", 0);
                    stringObjectMap.put("zc", 0);
                }
                dayAndNums.setNums(stringObjectMap);
                list.add(dayAndNums);
            }

            Collections.reverse(list); // 倒叙

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务数量获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }


    /**
     * 任务工单列表
     * 近五条任务
     *
     * @return
     */
    @RequestMapping(value = "nearFiveTaskList", method = RequestMethod.GET)
    @ResponseBody
    public String nearFiveTaskList() {
        List<TkCommonTask> tkCommonTasks = new ArrayList<TkCommonTask>();
        try {
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            tkCommonTaskExample.setOrderByClause("create_time desc limit 0,5");
            tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
            if (tkCommonTasks != null && tkCommonTasks.size() > 0) {
                for (TkCommonTask tkCommonTask : tkCommonTasks) {
                    //1已完成  2待评价 3待核查  4处理中 5待处理 6待指派  7待延时
                    if (tkCommonTask.getTkStatus() > 40) {
                        tkCommonTask.setZt("已完成");
                    } else if (tkCommonTask.getTkStatus() == 40) {
                        tkCommonTask.setZt("待评价");
                    } else if (tkCommonTask.getTkStatus() >= 30 && tkCommonTask.getTkStatus() < 40) {
                        tkCommonTask.setZt("待核查");
                    } else if (tkCommonTask.getTkStatus() >= 20 && tkCommonTask.getTkStatus() < 30) {
                        tkCommonTask.setZt("处理中");
                    } else if (tkCommonTask.getTkStatus() > 10 && tkCommonTask.getTkStatus() < 20 && tkCommonTask.getTkStatus() != 16) {
                        tkCommonTask.setZt("待处理");
                    } else if (tkCommonTask.getTkStatus() == 10 || tkCommonTask.getTkStatus() == 10) {
                        tkCommonTask.setZt("待指派");
                    } else if (tkCommonTask.getTkStatus() == 32) {
                        tkCommonTask.setZt("待延时");
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务列表获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));
    }


    /**
     * 网格处置排行
     *
     * @return
     */
    @RequestMapping(value = "wgczph", method = RequestMethod.GET)
    @ResponseBody
    public String wgczph() {
        List<Wgczph> wgczphs = new ArrayList<Wgczph>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            DecimalFormat df = new DecimalFormat("######0.00");
            List<Map<String, Object>> wgczphList = tkCommonTaskExtMapper.wgczph(map);
            if (wgczphList.size() > 0) {
                for (int i = 0; i < wgczphList.size(); i++) {
                    Wgczph wgczph = new Wgczph();
                    wgczph.setParentName(wgczphList.get(i).get("parentName").toString());//网格名
                    wgczph.setAllNum(Double.parseDouble(wgczphList.get(i).get("allNum").toString()));//所有数量
                    TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
                    TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
                    criteria.andTkStatusEqualTo(50);
                    criteria.andStandby1EqualTo("0");
                    criteria.andWgParentNameEqualTo(wgczphList.get(i).get("parentName").toString());
                    int i1 = tkCommonTaskService.countByExample(tkCommonTaskExample);
                    wgczph.setEndNum(i1);
                    wgczph.setCompletionInt(Double.parseDouble(df.format(((wgczph.getEndNum() / wgczph.getAllNum()) * 100))));
                    wgczph.setCompletionStr(df.format(((wgczph.getEndNum() / wgczph.getAllNum()) * 100)) + "%");
                    wgczphs.add(wgczph);
                }
                //根据完成比例倒叙
                Collections.sort(wgczphs, new Comparator<Wgczph>() {

                    public int compare(Wgczph o1, Wgczph o2) {

                        // 按照学生的年龄进行降序排列
                        if (o1.getCompletionInt() > o2.getCompletionInt()) {
                            return -1;
                        }
                        if (o1.getCompletionInt() == o2.getCompletionInt()) {
                            return 0;
                        }
                        return 1;
                    }
                });
                //排行
                for (int i = 0; i < wgczphs.size(); i++) {
                    if (i == 0) {
                        wgczphs.get(i).setRank(1);
                    } else {
                        if (wgczphs.get(i).getCompletionInt() == wgczphs.get(i - 1).getCompletionInt()) {
                            wgczphs.get(i).setRank(wgczphs.get(i - 1).getRank());
                        } else {
                            wgczphs.get(i).setRank(wgczphs.get(i - 1).getRank() + 1);
                        }
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", wgczphs));
    }


    /**
     * 创建数量排行
     *
     * @return
     */
    @RequestMapping(value = "cjsl", method = RequestMethod.GET)
    @ResponseBody
    public String cjsl() {
        List<Wgczph> wgczphs = new ArrayList<Wgczph>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            DecimalFormat df = new DecimalFormat("######0.00");
            List<Map<String, Object>> wgczphList = tkCommonTaskExtMapper.wgczph(map);
            if (wgczphList.size() > 0) {
                for (int i = 0; i < wgczphList.size(); i++) {
                    Wgczph wgczph = new Wgczph();
                    wgczph.setParentName(wgczphList.get(i).get("parentName").toString());//网格名
                    wgczph.setAllNum(Double.parseDouble(wgczphList.get(i).get("allNum").toString()));//所有数量
                    wgczphs.add(wgczph);
                }
                //根据完成比例倒叙
                Collections.sort(wgczphs, new Comparator<Wgczph>() {

                    public int compare(Wgczph o1, Wgczph o2) {

                        // 按照学生的年龄进行降序排列
                        if (o1.getAllNum() > o2.getAllNum()) {
                            return -1;
                        }
                        if (o1.getAllNum() == o2.getAllNum()) {
                            return 0;
                        }
                        return 1;
                    }
                });

            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", wgczphs));
    }


    /**
     * 任务高发区域排名
     *
     * @return
     */
    @RequestMapping(value = "rwgfqy", method = RequestMethod.GET)
    @ResponseBody
    public String rwgfqy() {
        List<Wgczph> wgczphs = new ArrayList<Wgczph>();
        Date releaseStartTime = DateUtils.getCurrYearFirst();
        Date releaseEndTime = DateUtils.getCurrYearLast();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("releaseStartTime", releaseStartTime);
            map.put("releaseEndTime", releaseEndTime);

            List<Map<String, Object>> wgczphList = new ArrayList<Map<String, Object>>();

            GridRegionExample bsWgxxbExample = new GridRegionExample();
            GridRegionExample.Criteria criteria = bsWgxxbExample.createCriteria();
            criteria.andLevelEqualTo("3");
            int thireeGridNum = bsWgxxbService.countByExample(bsWgxxbExample);

            //如果有网格分三级走if  只有两级网格走else
            if (thireeGridNum > 0) {
                wgczphList = tkCommonTaskExtMapper.wgczph(map);
            } else {
                wgczphList = tkCommonTaskExtMapper.wgczphTwoGrid(map);
            }


            if (wgczphList.size() > 0) {
                for (int i = 0; i < wgczphList.size(); i++) {
                    Wgczph wgczph = new Wgczph();
                    wgczph.setParentName(wgczphList.get(i).get("parentName").toString());//网格名
                    wgczph.setAllNum(Double.parseDouble(wgczphList.get(i).get("allNum").toString()));//所有数量
                    wgczph.setParentId(wgczphList.get(i).get("parentId").toString());
                    wgczphs.add(wgczph);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", wgczphs));
    }

    @RequestMapping(value = "rwgfqyDS", method = RequestMethod.GET)
    @ResponseBody
    public String rwgfqyDS() {
        List<Wgczph> wgczphs = new ArrayList<Wgczph>();
        Date releaseStartTime = DateUtils.getCurrYearFirst();
        Date releaseEndTime = DateUtils.getCurrYearLast();

        List<Map.Entry<String, Integer>> result = new ArrayList<>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("releaseStartTime", releaseStartTime);
            map.put("releaseEndTime", releaseEndTime);

            List<Map<String, Object>> wgczphList = new ArrayList<Map<String, Object>>();

            GridRegionExample bsWgxxbExample = new GridRegionExample();
            GridRegionExample.Criteria criteria = bsWgxxbExample.createCriteria();
            criteria.andLevelEqualTo("3");
            int thireeGridNum = bsWgxxbService.countByExample(bsWgxxbExample);

            //如果有网格分三级走if  只有两级网格走else
            if (thireeGridNum > 0) {
                wgczphList = tkCommonTaskExtMapper.wgczph(map);
            } else {
                wgczphList = tkCommonTaskExtMapper.wgczphTwoGrid(map);
            }

            Map<String, Integer> DSOldWg = new HashMap<>();
            DSOldWg.put("市政设施运行管理科", 1245);
            DSOldWg.put("综合执法局园林绿化管理科", 417);
            DSOldWg.put("川埠村", 386);
            DSOldWg.put("公园路社区", 348);
            DSOldWg.put("湖渎社区", 339);
            DSOldWg.put("丁蜀镇_督察在线", 272);
            DSOldWg.put("佳禾绿化有限公司", 262);
            DSOldWg.put("任墅村", 256);
            DSOldWg.put("紫砂村", 245);
            DSOldWg.put("洛涧村", 240);
            DSOldWg.put("洑东村", 233);
            DSOldWg.put("丁蜀建设局", 229);
            DSOldWg.put("白宕居委", 194);
            DSOldWg.put("查林村", 181);
            DSOldWg.put("丁山社区", 173);
            DSOldWg.put("画溪社区", 170);
            DSOldWg.put("塍里村", 169);
            DSOldWg.put("汤渡社区", 169);
            DSOldWg.put("蠡墅社区", 168);
            DSOldWg.put("建新村", 166);
            DSOldWg.put("潜洛村", 166);
            DSOldWg.put("西望村", 162);
            DSOldWg.put("周墅社区", 156);
            DSOldWg.put("大港村", 150);
            DSOldWg.put("蜀山社区", 149);
            DSOldWg.put("浦南村", 147);
            DSOldWg.put("张泽村", 146);
            DSOldWg.put("南河社区", 141);
            DSOldWg.put("三洞桥村", 139);
            DSOldWg.put("双桥村", 135);
            DSOldWg.put("潘南社区", 126);
            DSOldWg.put("赵庄社区", 126);
            DSOldWg.put("双庙村", 121);
            DSOldWg.put("洋渚村", 117);
            DSOldWg.put("定溪村", 113);
            DSOldWg.put("陶渊村", 101);
            DSOldWg.put("洋岸村", 99);
            DSOldWg.put("施荡村", 92);
            DSOldWg.put("方钱村", 91);
            DSOldWg.put("北塘村", 89);
            DSOldWg.put("渭渎村", 89);
            DSOldWg.put("上坝村", 87);
            DSOldWg.put("大浦村", 86);
            DSOldWg.put("汤庄村", 86);
            DSOldWg.put("毛旗村", 85);
            DSOldWg.put("龙溪社区", 78);
            DSOldWg.put("蜀北社区", 67);
            DSOldWg.put("丁蜀镇区", 39);
            DSOldWg.put("禾宇绿化有限公司", 37);
            DSOldWg.put("宜兴建设局", 18);
            DSOldWg.put("佳园绿化有限公司", 14);
            DSOldWg.put("华东（工业园）绿化有限公司", 9);
            DSOldWg.put("宜兴园林绿化有限公司", 8);
            DSOldWg.put("大埔村", 7);
            DSOldWg.put("华东（大浦张泽）绿化有限公司", 6);

            Map<String, Object> wgIds = new HashMap<>();

            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria1 = example.createCriteria();
            List<GridRegion> bsWgxxbs = bsWgxxbService.selectByExample(example);

            for (GridRegion bsWgxxb : bsWgxxbs) {
                wgIds.put(bsWgxxb.getWgName(), bsWgxxb.getWgCode());
            }

            for (int i = 0; i < wgczphList.size(); i++) {
                Map<String, Object> mapTemp = wgczphList.get(i);

                if (DSOldWg.containsKey(mapTemp.get("parentName"))) {
                    DSOldWg.put(mapTemp.get("parentName") + "", Integer.valueOf(mapTemp.get("allNum") + "") + DSOldWg.get(mapTemp.get("parentName")));
                } else {
                    DSOldWg.put(mapTemp.get("parentName") + "", Integer.valueOf(mapTemp.get("allNum") + ""));
                }
            }
            result = new ArrayList<Map.Entry<String, Integer>>(DSOldWg.entrySet());

            Collections.sort(result, new Comparator<Map.Entry<String, Integer>>() {
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return (o2.getValue() - o1.getValue());
                }
            });

            for (int i = 0; i < result.size(); i++) {
                Map.Entry<String, Integer> temp = result.get(i);
                Wgczph wgczph = new Wgczph();
                wgczph.setParentName(temp.getKey() + "");//网格名
                wgczph.setAllNum(Double.parseDouble(temp.getValue() + ""));//所有数量
                if (wgIds.containsKey(temp.getKey())) {
                    wgczph.setParentId(wgIds.get(temp.getKey()) + "");
                }

                wgczphs.add(wgczph);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", wgczphs));
    }


    /**
     * 近三月日常数量趋势
     *
     * @return
     */
    @RequestMapping(value = "nearThreeMonthCount", method = RequestMethod.GET)
    @ResponseBody
    public String nearThreeMonthCount(String wgCode) {
        String mon = "";
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        try {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            for (int i = 0; i < 3; i++) {
                Calendar c = Calendar.getInstance();
                c.setTime(new Date());
                c.add(Calendar.MONTH, 0 - i);//当前月
                Date m = c.getTime();
                mon = format.format(m);
                String[] split = mon.split("-");
                Date firstDayOfMonth1 = getFirstDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Date lastDayOfMonth1 = getLastDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Map<String, Object> map = new HashMap<String, Object>();
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
                map.put("firstDayOfMonth1", format2.format(firstDayOfMonth1));
                map.put("lastDayOfMonth1", format2.format(lastDayOfMonth1));
                map.put("wgCode", wgCode);
                Map<String, Object> stringObjectMap = tkCommonTaskExtMapper.nearThreeMonthCount(map);
                if (stringObjectMap.get("endNum") == null) {
                    stringObjectMap.put("endNum", 0);
                }
                stringObjectMap.put("month", mon);
                ret.add(stringObjectMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }

    /**
     * 每个网格内当年度内最近6个月的工单上报数量和完成数量
     *
     * @return
     */
    @RequestMapping(value = "nearSixMonthCountByWgCode", method = RequestMethod.GET)
    @ResponseBody
    public String nearSixMonthCountByWgCode(String wgCode) {
        String mon = "";
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();

        //查询网格的等级
        GridRegionExample bsWgxxbExample = new GridRegionExample();
        bsWgxxbExample.createCriteria().andWgCodeEqualTo(wgCode);
        List<GridRegion> bsWgxxbs = bsWgxxbService.selectByExample(bsWgxxbExample);
        if (bsWgxxbs == null || bsWgxxbs.size() == 0) {
            return JSON.toJSONString(AjaxResult.build(200, "网格数据为空", ret));
        }
        String level = bsWgxxbs.get(0).getLevel();

        try {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            for (int i = 0; i < 6; i++) {
                Calendar c = Calendar.getInstance();
                c.setTime(new Date());
                c.add(Calendar.MONTH, 0 - i);//当前月
                Date m = c.getTime();
                mon = format.format(m);
                String[] split = mon.split("-");
                Date firstDayOfMonth1 = getFirstDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Date lastDayOfMonth1 = getLastDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Map<String, Object> map = new HashMap<String, Object>();
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
                map.put("firstDayOfMonth1", format2.format(firstDayOfMonth1));
                map.put("lastDayOfMonth1", format2.format(lastDayOfMonth1));
                if (level.equals("2")) {
                    //如果查询2级网格的数量，那么任务表就得查wg_parent_code=code
                    map.put("wgParentCode", wgCode);
                } else {
                    //如果查询3级网格的数量，那么任务就得查wg_code=code
                    map.put("wgCode", wgCode);
                }
                Map<String, Object> stringObjectMap = tkCommonTaskExtMapper.nearThreeMonthCount(map);
                if (stringObjectMap.get("endNum") == null) {
                    stringObjectMap.put("endNum", 0);
                }
                stringObjectMap.put("month", mon);
                ret.add(stringObjectMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    /**
     * 网格满意度排名
     *
     * @return
     */
    @RequestMapping(value = "manyiRank", method = RequestMethod.GET)
    @ResponseBody
    public String manyiRank() {
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            ret = tkCommonTaskService.manyiRank(map);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    @RequestMapping(value = "zhuanzhifajv", method = RequestMethod.GET)
    @ResponseBody
    public String zhuanzhifajv(String id) {
        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        tkCommonTask.setIsZhuanzhifa(1);//1就是转执法局


        try {
            int i = tkCommonTaskService.zhuanzhifajv(tkCommonTask);
            if (i == 0) {
                return JSON.toJSONString(AjaxResult.build(400, "fail", "转执法局出错"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "转执法局出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "转执法局成功"));
    }

    /**
     * 工单满意度统计（平均星级、平均满意度百分比）
     *
     * @return
     */
    @RequestMapping(value = "personManYiTJ", method = RequestMethod.GET)
    @ResponseBody
    public String personManYiTJ(String userId) {
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("performUserId", userId);
            ret = tkCommonTaskService.personManYiTJ(map);
            if (ret != null && ret.size() > 0) {
                Map<String, Object> bac = ret.get(0);
                TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
                TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
                criteria.andReleaseUserIdEqualTo(userId);
                criteria.andStandby1EqualTo("0");
                int ljgd = tkCommonTaskService.countByExample(tkCommonTaskExample);
                bac.put("ljgd", ljgd);//累计工单

                TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
                TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
                criteria2.andReleaseUserIdEqualTo(userId);
                criteria2.andStandby1EqualTo("0");
                criteria2.andTkStatusGreaterThanOrEqualTo(40);
                int ljbj = tkCommonTaskService.countByExample(tkCommonTaskExample2);
                bac.put("ljbj", ljbj);//累计办结
                if (ljgd == 0 || ljbj == 0) {
                    bac.put("bjl", 0);//累计办结
                } else {
                    DecimalFormat df = new DecimalFormat("0.00");
                    bac.put("bjl", df.format((double) ljbj / (double) ljgd));//累计办结
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }

    /**
     * 获取日常任务数、完成日常任务数、按时完成日常完成任务数量
     * 日常任务各个来源的数量
     *
     * @param month  月份
     * @param userId 用户id
     * @return
     */
    @RequestMapping(value = "allCommonTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String allCommonTaskNum(int year, int month, String userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //获取最小时间
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, month - 1);
            int firstDay = cal.getMinimum(Calendar.DATE);
            cal.set(Calendar.DAY_OF_MONTH, firstDay);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String firstday = format.format(cal.getTime());


            //获取最大时间
            Calendar cal2 = Calendar.getInstance();
            cal2.set(Calendar.YEAR, year);
            cal2.set(Calendar.MONTH, month);
            int lastDay = cal.getMinimum(Calendar.DATE);
            cal2.set(Calendar.DAY_OF_MONTH, lastDay);
            String lastday = format.format(cal2.getTime());


            //创建日常任务数
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andReleaseUserIdEqualTo(userId);
            criteria.andCreateTimeGreaterThanOrEqualTo(format.parse(firstday));//大于等于
            criteria.andCreateTimeLessThan(format.parse(lastday));//小于
            criteria.andStandby1EqualTo("0");
            map.put("createTaskCount", tkCommonTaskService.countByExample(tkCommonTaskExample));

            //完成日常任务数
            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
//            criteria2.andReleaseUserIdEqualTo(userId);
            criteria2.andPerformUserIdEqualTo(userId);//执行人用户id
            criteria2.andCreateTimeGreaterThanOrEqualTo(format.parse(firstday));//大于等于
            criteria2.andCreateTimeLessThan(format.parse(lastday));//小于
            criteria2.andTkStatusGreaterThanOrEqualTo(40);//审核通过  待评价
            criteria2.andStandby1EqualTo("0");
            List<TkCommonTask> tkCommonTasks2 = tkCommonTaskService.selectByExample(tkCommonTaskExample2);
            map.put("endTaskCount", tkCommonTasks2.size());

            //按时完成日常任务的数量
            List<TkCommonTask> onTimeTask = new ArrayList<TkCommonTask>();
            if (tkCommonTasks2.size() > 0) {
                for (TkCommonTask tkT : tkCommonTasks2) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    if (tkT.getVerificationTime() == null) {
                        break;
                    }
                    String s = sdf.format(tkT.getVerificationTime());
                    Date date = sdf.parse(s);
                    if (tkT.getAssignedEndTime().getTime() >= date.getTime()) {//完成时间 大于 核查时间
                        onTimeTask.add(tkT);
                    }
                }
            }
            map.put("onTimeTaskCount", onTimeTask.size());//按时完成的数量

            //日常任务各个来源的数量
            Map<String, Object> map2 = new HashMap<String, Object>();

            TkCommonTaskExample tkCommonTaskExample3 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria3 = tkCommonTaskExample3.createCriteria();
            criteria3.andReleaseUserIdEqualTo(userId);
            criteria3.andCreateTimeGreaterThanOrEqualTo(format.parse(format.format(cal.getTime())));//大于等于
            criteria3.andCreateTimeLessThan(format.parse(format.format(cal2.getTime())));//小于
            criteria3.andStandby1EqualTo("0");
            criteria3.andMatterTypeEqualTo(1);
            map2.put("城乡综合网格", tkCommonTaskService.countByExample(tkCommonTaskExample3));//城乡综合
            TkCommonTaskExample tkCommonTaskExample4 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria4 = tkCommonTaskExample4.createCriteria();
            criteria4.andReleaseUserIdEqualTo(userId);
            criteria4.andCreateTimeGreaterThanOrEqualTo(format.parse(format.format(cal.getTime())));//大于等于
            criteria4.andCreateTimeLessThan(format.parse(format.format(cal2.getTime())));//小于
            criteria4.andStandby1EqualTo("0");
            criteria4.andMatterTypeEqualTo(2);
            map2.put("企业网格", tkCommonTaskService.countByExample(tkCommonTaskExample4));//企业网格
            TkCommonTaskExample tkCommonTaskExample5 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria5 = tkCommonTaskExample5.createCriteria();
            criteria5.andReleaseUserIdEqualTo(userId);
            criteria5.andCreateTimeGreaterThanOrEqualTo(format.parse(format.format(cal.getTime())));//大于等于
            criteria5.andCreateTimeLessThan(format.parse(format.format(cal2.getTime())));//小于
            criteria5.andStandby1EqualTo("0");
            criteria5.andMatterTypeEqualTo(3);
            map2.put("资产网格", tkCommonTaskService.countByExample(tkCommonTaskExample5));//资产网格

            map.put("matterType", map2);


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务数量获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", map));
    }


    /**
     * 近7天的日常任务数量
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping(value = "nearSevenTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String nearSevenTaskNum(String userId) {
        List<DayAndNums> list = new ArrayList<DayAndNums>();
        try {
            ArrayList<Date> test = getDateList(7);

            SimpleDateFormat format = new SimpleDateFormat("MM/dd");
            System.out.println("----" + JSONObject.toJSONString(test));

            if (test.size() > 0) {
                int i = 7;//计数器
                for (Date da : test) {
                    TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
                    TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
                    criteria.andReleaseUserIdEqualTo(userId);
                    criteria.andReleaseTimeEqualTo(da);
                    criteria.andStandby1EqualTo("0");
                    List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
                    DayAndNums dayAndNums = new DayAndNums();
                    dayAndNums.setDay(format.format(da));
                    dayAndNums.setValue(tkCommonTasks.size());
                    list.add(dayAndNums);
                    i--;
                }
            }

            Collections.reverse(list); // 倒叙

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务数量获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }


    /**
     * 每个网格内当年度内最近77天的工单上报数量和完成数量
     *
     * @return
     */
    @RequestMapping(value = "nearSevenDayCountByWgCode", method = RequestMethod.GET)
    @ResponseBody
    public String nearSevenDayCountByWgCode(String wgCode) {
        String mon = "";
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();

        //查询网格的等级
        GridRegionExample bsWgxxbExample = new GridRegionExample();
        bsWgxxbExample.createCriteria().andWgCodeEqualTo(wgCode);
        List<GridRegion> bsWgxxbs = bsWgxxbService.selectByExample(bsWgxxbExample);
        if (bsWgxxbs == null || bsWgxxbs.size() == 0) {
            return JSON.toJSONString(AjaxResult.build(200, "网格数据为空", ret));
        }
        String level = bsWgxxbs.get(0).getLevel();


        try {
            ArrayList<Date> test = getDateList(7);
            if (test.size() > 0) {


            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (Date da : test) {
                Map<String, Object> map = new HashMap<String, Object>();
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
                map.put("time", format2.format(da));
                if (level.equals("2")) {
                    //如果查询2级网格的数量，那么任务表就得查wg_parent_code=code
                    map.put("wgParentCode", wgCode);
                } else {
                    //如果查询3级网格的数量，那么任务就得查wg_code=code
                    map.put("wgCode", wgCode);
                }
                Map<String, Object> stringObjectMap = tkCommonTaskExtMapper.nearSevenDayCountByWgCode(map);
                if (stringObjectMap.get("endNum") == null) {
                    stringObjectMap.put("endNum", 0);
                }
                stringObjectMap.put("day", format.format(da));
                ret.add(stringObjectMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    /**
     * 各村（居）工单统计  溧阳大屏
     *
     * @return
     */
    @RequestMapping(value = "taskCountByWgcode", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountByWgcode() {
        Map<String, Object> map = new HashedMap();
        List<Map<String, Object>> countSec = tkCommonTaskService.taskCountBySecWgcode(map);//待办列表
        List<Map<String, Object>> countThi = tkCommonTaskService.taskCountByThirdWgcode(map);//待办列表
        try {


            for (Map<String, Object> sec : countSec) {
                for (Map<String, Object> thi : countThi) {
                    if (sec.get("wg_code").toString().equals(thi.get("wg_code").toString())) {
                        if (sec.get("banjieNum") == null) {
                            sec.put("banjieNum", 0);
                        }
                        if (sec.get("daibanNum") == null) {
                            sec.put("daibanNum", 0);
                        }
                        if (thi.get("banjieNum") == null) {
                            thi.put("banjieNum", 0);
                        }
                        if (thi.get("daibanNum") == null) {
                            thi.put("daibanNum", 0);
                        }
                        int daibanNumSec = Integer.parseInt(sec.get("daibanNum").toString());
                        int banjieNumSec = Integer.parseInt(sec.get("banjieNum").toString());
                        int daibanNumThi = Integer.parseInt(thi.get("daibanNum").toString());
                        int banjieNumThi = Integer.parseInt(thi.get("banjieNum").toString());
                        sec.put("banjieNum", banjieNumSec + banjieNumThi);
                        sec.put("daibanNum", daibanNumSec + daibanNumThi);


                        double daibanNum = Double.parseDouble(sec.get("daibanNum").toString());
                        double banjieNum = Double.parseDouble(sec.get("banjieNum").toString());
                        if (daibanNum + banjieNum == 0) {
                            sec.put("banjielv", 0);
                        } else {
                            sec.put("banjielv", banjieNum / (daibanNum + banjieNum));
                        }
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "接口出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", countSec));
    }


    /**
     * 各村（居）工单统计  溧阳大屏包含综治
     *
     * @return
     */
    @RequestMapping(value = "taskCountByWgcodeAndZZ", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountByWgcodeAndZZ(String wgCode) {
        Map<String, Object> map = new HashedMap();
        map.put("wgCode", wgCode);

        List<Map<String, Object>> countSec = tkCommonTaskService.taskCountBySecWgcode(map);//待办列表
        List<Map<String, Object>> countThi = tkCommonTaskService.taskCountByThirdWgcode(map);//待办列表

        try {


            for (Map<String, Object> sec : countSec) {
                for (Map<String, Object> thi : countThi) {
                    if (sec.get("wg_code").toString().equals(thi.get("wg_code").toString())) {
                        if (sec.get("banjieNum") == null) {
                            sec.put("banjieNum", 0);
                        }
                        if (sec.get("daibanNum") == null) {
                            sec.put("daibanNum", 0);
                        }
                        if (thi.get("banjieNum") == null) {
                            thi.put("banjieNum", 0);
                        }
                        if (thi.get("daibanNum") == null) {
                            thi.put("daibanNum", 0);
                        }
                        int daibanNumSec = Integer.parseInt(sec.get("daibanNum").toString());
                        int banjieNumSec = Integer.parseInt(sec.get("banjieNum").toString());
                        int daibanNumThi = Integer.parseInt(thi.get("daibanNum").toString());
                        int banjieNumThi = Integer.parseInt(thi.get("banjieNum").toString());
                        sec.put("banjieNum", banjieNumSec + banjieNumThi);
                        sec.put("daibanNum", daibanNumSec + daibanNumThi);


                        double daibanNum = Double.parseDouble(sec.get("daibanNum").toString());
                        double banjieNum = Double.parseDouble(sec.get("banjieNum").toString());
                        if (daibanNum + banjieNum == 0) {
                            sec.put("banjielv", 0);
                        } else {
                            sec.put("banjielv", banjieNum / (daibanNum + banjieNum));
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "接口出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", countSec));
    }


    /**
     * 事项分类登记占比（三个优先级
     *
     * @return
     */
    @RequestMapping(value = "groupByMatterType", method = RequestMethod.GET)
    @ResponseBody
    public String groupByMatterType() {
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> map = new HashedMap();
            List<Map<String, Object>> count = tkCommonTaskService.groupByMatterType(map);
            System.out.println(count);
            if (count != null && count.size() > 0) {
                for (Map<String, Object> matter : count) {
                    map = new HashedMap();
                    map.put("parentMatterId", matter.get("parent_mattetr_id"));
                    List<Map<String, Object>> maps = tkCommonTaskService.groupByPriority(map);
                    System.out.println("aa");
                    ret.addAll(maps);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "接口出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }

    /**
     * 近7天事项趋势  溧阳大屏
     *
     * @return
     */
    @RequestMapping(value = "nearSevenMatter", method = RequestMethod.GET)
    @ResponseBody
    public String nearSevenMatter() {
        List<DayAndNums> list = new ArrayList<DayAndNums>();
        try {
            ArrayList<Date> test = getDateList(7);

            SimpleDateFormat format = new SimpleDateFormat("MM/dd");
            System.out.println("----" + JSONObject.toJSONString(test));

            if (test.size() > 0) {
                for (Date da : test) {
                    TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
                    TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
                    criteria.andReleaseTimeEqualTo(da);
                    criteria.andStandby1EqualTo("0");
                    List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
                    DayAndNums dayAndNums = new DayAndNums();
                    dayAndNums.setMonth(format.format(da));
                    dayAndNums.setType("新增数");
                    dayAndNums.setNum(tkCommonTasks.size());
                    list.add(dayAndNums);

                    tkCommonTaskExample = new TkCommonTaskExample();
                    TkCommonTaskExample.Criteria criteria1 = tkCommonTaskExample.createCriteria();
                    criteria1.andAssignedEndTimeBetween(DateUtils.getStartTime(da), DateUtils.getEndTime(da));
                    criteria1.andStandby1EqualTo("0");
                    tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
                    dayAndNums = new DayAndNums();
                    dayAndNums.setMonth(format.format(da));
                    dayAndNums.setType("办结数");
                    dayAndNums.setNum(tkCommonTasks.size());
                    list.add(dayAndNums);
                }
            }

            Collections.reverse(list); // 倒叙

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "接口出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }

    /**
     * 近7天事项趋势  包含综治
     *
     * @return
     */
    @RequestMapping(value = "nearSevenMatterMix", method = RequestMethod.GET)
    @ResponseBody
    public String nearSevenMatterMix() {
        List<DayAndNums> list = new ArrayList<DayAndNums>();
        try {
            ArrayList<Date> test = getDateList(7);

            SimpleDateFormat format = new SimpleDateFormat("MM/dd");
            System.out.println("----" + JSONObject.toJSONString(test));

            if (test.size() > 0) {
                for (Date da : test) {
                    TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
                    TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
                    criteria.andReleaseTimeEqualTo(da);
                    criteria.andStandby1EqualTo("0");
                    List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);

                    int zzBjNum = 0;

                    DayAndNums dayAndNums = new DayAndNums();
                    dayAndNums.setMonth(format.format(da));
                    dayAndNums.setType("新增数");
                    int tempInt1 = CollectionUtils.isEmpty(tkCommonTasks) ? 0 : tkCommonTasks.size();
                    dayAndNums.setNum(tempInt1 + zzBjNum);
                    list.add(dayAndNums);

                    tkCommonTaskExample = new TkCommonTaskExample();
                    TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample.createCriteria();
                    criteria2.andAssignedEndTimeBetween(DateUtils.getStartTime(da), DateUtils.getEndTime(da));
                    criteria2.andStandby1EqualTo("0");
                    tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);

                    int zzNum = 0;

                    dayAndNums = new DayAndNums();
                    dayAndNums.setMonth(format.format(da));
                    dayAndNums.setType("办结数");
                    int tempInt2 = CollectionUtils.isEmpty(tkCommonTasks) ? 0 : tkCommonTasks.size();
                    dayAndNums.setNum(tempInt2 + zzNum);
                    list.add(dayAndNums);
                }
            }

            Collections.reverse(list); // 倒叙

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "接口出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }


    /**
     * 获取事项分类为企业的数量
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping(value = "qiyeNum", method = RequestMethod.GET)
    @ResponseBody
    public String qiyeNum(String userId) {
        int qiyeNum = 0;
        try {


            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andReleaseUserIdEqualTo(userId);
            criteria.andMatterTypeEqualTo(2);
            criteria.andStandby1EqualTo("0");
            qiyeNum = tkCommonTaskService.countByExample(tkCommonTaskExample);


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务数量获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", qiyeNum));
    }


    /**
     * 任务异常统计
     *
     * @return
     */
    @RequestMapping(value = "qichangAbnormalNum", method = RequestMethod.GET)
    @ResponseBody
    public String qichangAbnormalNum() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String year = sdf.format(new Date());
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
        String monthno = sdf2.format(new Date());
        List<DayAndNums> list = new ArrayList<DayAndNums>();
        try {
            ArrayList<Date> test = getDateList(7);

            SimpleDateFormat format = new SimpleDateFormat("MM/dd");
            System.out.println("----" + JSONObject.toJSONString(test));
            for (int i = 0; i < Integer.parseInt(monthno); i++) {
                Map<String, Object> month = new HashedMap();
                month.put("mm", i + 1);
                Map<String, Object> stringObjectMap = tkCommonTaskExtMapper.qiyeAbnormalNum(month);
                DayAndNums dayAndNums = new DayAndNums();
                dayAndNums.setMonth(i + 1 + "");
                if (stringObjectMap == null) {
                    stringObjectMap = new HashedMap();
                    stringObjectMap.put("hbNum", 0);
                    stringObjectMap.put("ajNum", 0);
                    stringObjectMap.put("otherNum", 0);
                }
                dayAndNums.setNums(stringObjectMap);
                list.add(dayAndNums);
            }

            Collections.reverse(list); // 倒叙

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务数量获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }


    /**
     * 导出
     *
     * @param pageNum       当前页数
     * @param pageSize      一页几行
     * @param unfinished    未完成
     * @param finished      已完成
     * @param perform       我执行的
     * @param release       我创建的
     * @param verification  我审核的
     * @param leader        领导交办
     * @param priorityType  优先级 0普通-1重要-2紧急
     * @param tkStatus      任务状态 1已完成  2待评价 3待核查  4处理中 5待处理 6待指派  7待延时
     * @param releaseTime   创建时间
     * @param comeFrom      来源 0城乡综合网格、1企业网格、2资产网格
     * @param nameOrId      任务名字 或者 任务tkid
     * @param loginUserId   登录人id
     * @param loginUserName 登录人姓名
     * @param loginUserRole 3三级 2二级 1一级 0中心
     * @return
     */
    @RequestMapping(value = "export", method = RequestMethod.POST)
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody TaskCommonListRequest exportRequest) {
        List<TkCommonTask> sysTestList = tkCommonTaskService.selectListByExport(exportRequest.params());
        sysTestList = sysTestList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getId() + ";"))), ArrayList::new));
        this.ListSort(sysTestList);//排序
        //excel标题
        String[] title = {"任务名称", "发布人", "优先级", "所属村", "所属网格", "工单内容", "任务地址", "发布时间", "事项大类", "事项分类", "督办人", "任务方式", "工单编号", "处理人", "处理单位", "处理状态"};

        //sheet名
        String sheetName = "日常任务表";
        String[][] content = new String[sysTestList.size()][9];
        for (int i = 0; i < sysTestList.size(); i++) {
            try {

                content[i] = new String[title.length];
                TkCommonTask obj = sysTestList.get(i);
                content[i][0] = obj.getTkName();
                content[i][1] = obj.getReleaseUserName();
                if (obj.getPriorityType() != null) {
                    if (obj.getPriorityType() == 0) {//普通0-1重要-2紧急
                        content[i][2] = "普通";
                    } else if (obj.getPriorityType() == 1) {
                        content[i][2] = "重要";//优先级
                    } else if (obj.getPriorityType() == 2) {
                        content[i][2] = "紧急";//优先级
                    }
                } else {
                    content[i][2] = "普通";//优先级
                }

                content[i][3] = obj.getWgParentName();//所属村
                content[i][4] = obj.getBelongGrid();
                content[i][5] = obj.getTkDetail();//工单内容
                content[i][6] = obj.getTkAddress();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateNowStr = sdf.format(obj.getReleaseTime());
                content[i][7] = dateNowStr;
                content[i][8] = obj.getParentMattetrName();//事项大类
                content[i][9] = obj.getMatterName();
                content[i][10] = obj.getStandby3();//督办人
                if (obj.getHandleType() == 0) {//处理方式-0自行处理-1上报上级-2上报中心-3指派下级
                    content[i][11] = "自行处理";
                } else if (obj.getHandleType() == 1) {
                    content[i][11] = "上报上级";
                } else if (obj.getHandleType() == 2) {
                    content[i][11] = "上报中心";
                } else if (obj.getHandleType() == 3) {
                    content[i][11] = "指派下级";
                }
                content[i][12] = obj.getTkId();//工单编号
                content[i][13] = obj.getPerformUserName();//处理人
                content[i][14] = obj.getPerformUnit();//处理单位
                String s = tastStatus(obj.getTkStatus());
                content[i][15] = s;//处理状态

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {


            //excel文件名
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            String fileName = dateFormat.format(date) + ".xls";


            this.setResponseHeader(response, request, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private String tastStatus(int tkStatus) {
        String sLabel = "";
        if (tkStatus > 40)
            sLabel = "已完成";
        else if (tkStatus == 40)
            sLabel = "待评价";
        else if (tkStatus >= 30)
            sLabel = "待核查";
        else if (tkStatus >= 20)
            sLabel = "处理中";
        else if (tkStatus > 10)
            sLabel = "待处理";
        else if (tkStatus == 10)
            sLabel = "待指派";
        else
            sLabel = "待发布";
        if (tkStatus == 16)
            sLabel = "待指派";
        if (tkStatus == 32)
            sLabel = "待延期";
        if (tkStatus == 36)
            sLabel = "处理中";

        return sLabel;
    }


    /**
     * 说明配置
     *
     * @param
     * @return
     */
    @RequestMapping(value = "shuomingPZ", method = RequestMethod.GET)
    @ResponseBody
    public String shuomingPZ(String hechaText, String chuliText,String checkedZongZhi, String checkedJieJing, String checkedQianShou, String checkedWGYIsOnline, String checkedYuJing) {

        try {
            TkCommonTextExample tkCommonTextExample = new TkCommonTextExample();
            TkCommonTextExample.Criteria criteria = tkCommonTextExample.createCriteria();
            TkCommonText tkCommonText = tkCommonTextService.selectFirstByExample(tkCommonTextExample);
            if (tkCommonText == null) {//有值修改，没值添加
                tkCommonText = new TkCommonText();
                tkCommonText.setId(UUID.randomUUID().toString());
                tkCommonText.setYl1(hechaText);
                tkCommonText.setYl2(chuliText);
                tkCommonText.setYl3(checkedZongZhi);
                tkCommonText.setYl4(checkedJieJing);
                tkCommonText.setYl5(checkedQianShou);
                tkCommonText.setYl6(checkedWGYIsOnline);
                tkCommonText.setYl7(checkedYuJing);
                tkCommonTextService.insert(tkCommonText);
            } else {
                tkCommonText.setYl1(hechaText);
                tkCommonText.setYl2(chuliText);
                tkCommonText.setYl3(checkedZongZhi);
                tkCommonText.setYl4(checkedJieJing);
                tkCommonText.setYl5(checkedQianShou);
                tkCommonText.setYl6(checkedWGYIsOnline);
                tkCommonText.setYl7(checkedYuJing);
                tkCommonTextService.updateByPrimaryKey(tkCommonText);
            }

            return JSON.toJSONString(AjaxResult.build(200, "success", "配置成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "配置失败"));
        }

    }


    /**
     * 说明详情
     *
     * @return
     */
    @RequestMapping(value = "shuomingDetail", method = RequestMethod.GET)
    @ResponseBody
    public String shuomingDetail() {

        try {
            TkCommonTextExample tkCommonTextExample = new TkCommonTextExample();
            TkCommonTextExample.Criteria criteria = tkCommonTextExample.createCriteria();
            List<TkCommonText> tkCommonTexts = tkCommonTextService.selectByExample(tkCommonTextExample);
            if (tkCommonTexts != null && tkCommonTexts.size() > 0) {
                return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTexts.get(0)));
            } else {
                return JSON.toJSONString(AjaxResult.build(200, "success", new TkCommonText()));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "配置失败"));
        }

    }


    /**
     * 移动 事件量趋势统计
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/taskCountByMonth", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountByMonth() {
        String mon = "";
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        try {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            for (int i = 0; i < 9; i++) {
                Calendar c = Calendar.getInstance();
                c.setTime(new Date());
                c.add(Calendar.MONTH, 0 - i);//当前月
                Date m = c.getTime();
                mon = format.format(m);
                String[] split = mon.split("-");
                Date firstDayOfMonth1 = getFirstDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Date lastDayOfMonth1 = getLastDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Map<String, Object> map = new HashMap<String, Object>();
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
                map.put("firstDayOfMonth1", format2.format(firstDayOfMonth1));
                map.put("lastDayOfMonth1", format2.format(lastDayOfMonth1));
                Map<String, Object> stringObjectMap = tkCommonTaskExtMapper.nearThreeMonthCount(map);
                stringObjectMap.put("month", mon);
                ret.add(stringObjectMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    /**
     * （4）当年度按月工单上报数量，分来源（自行解决的和上报中心网格联动的）
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/taskCountByYearAndType", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountByYearAndType() {
        String mon = "";
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        Date releaseStartTime = DateUtils.getCurrYearFirst();
        Date releaseEndTime = DateUtils.getCurrYearLast();
        try {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            for (int i = 0; i < 12; i++) {
                Calendar c = Calendar.getInstance();
                c.setTime(releaseStartTime);
                c.add(Calendar.MONTH, 0 + i);//当前月
                Date m = c.getTime();
                mon = format.format(m);
                String[] split = mon.split("-");
                Date firstDayOfMonth1 = getFirstDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Date lastDayOfMonth1 = getLastDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Map<String, Object> map = new HashMap<String, Object>();
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
                map.put("firstDayOfMonth1", format2.format(firstDayOfMonth1));
                map.put("lastDayOfMonth1", format2.format(lastDayOfMonth1));
                map.put("releaseStartTime", releaseStartTime);
                map.put("releaseEndTime", releaseEndTime);
                Map<String, Object> stringObjectMap = tkCommonTaskExtMapper.overBySelfAndSBSJCount(map);
                if (stringObjectMap == null) {
                    stringObjectMap = new HashMap<String, Object>();
                    stringObjectMap.put("zxcl", 0);
                    stringObjectMap.put("sbzx", 0);
                }
                stringObjectMap.put("month", mon);
                ret.add(stringObjectMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    /**
     * 综治工单按月上报数量+本系统工单按月上报数量总和的趋势
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/taskCountAndZZByYearAndType", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountAndZZByYearAndType() {
        String mon = "";
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        Date releaseStartTime = DateUtils.getCurrYearFirst();
        Date releaseEndTime = DateUtils.getCurrYearLast();

        try {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            for (int i = 0; i < 12; i++) {
                Calendar c = Calendar.getInstance();
                c.setTime(releaseStartTime);
                c.add(Calendar.MONTH, 0 + i);//当前月
                Date m = c.getTime();
                mon = format.format(m);
                String[] split = mon.split("-");
                Date firstDayOfMonth1 = getFirstDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Date lastDayOfMonth1 = getLastDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Map<String, Object> map = new HashMap<String, Object>();
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
                map.put("firstDayOfMonth1", format2.format(firstDayOfMonth1));
                map.put("lastDayOfMonth1", format2.format(lastDayOfMonth1));
                Map<String, Object> stringObjectMap = tkCommonTaskExtMapper.countByMonth(map);//日常工单数量

                if (stringObjectMap == null) {
                    stringObjectMap = new HashMap<String, Object>();
                    stringObjectMap.put("taskCount", 0);
                }

                int xinbeiCount = 0;

                stringObjectMap.put("taskCountzz", 0);
                stringObjectMap.put("xinbeiCount", xinbeiCount);
                stringObjectMap.put("all", Integer.parseInt(stringObjectMap.get("taskCount").toString()) + 0 + xinbeiCount);
                stringObjectMap.put("month", mon);
                ret.add(stringObjectMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    /**
     * 工单统计（日常数量加综治数量）
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/taskCountAndZZCount", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountAndZZCount() {
        String mon = "";
        Map<String, Object> ret = new HashedMap();
        Date releaseStartTime = DateUtils.getCurrYearFirst();
        Date releaseEndTime = DateUtils.getCurrYearLast();

        SimpleDateFormat format = new SimpleDateFormat();
        format.applyPattern("YYYY-MM-dd HH:mm:ss");

        try {

            //所有任务数量
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            criteria.andCreateTimeBetween(releaseStartTime, releaseEndTime);
            int alltaskCount = tkCommonTaskService.countByExample(tkCommonTaskExample);//所有任务数量
            //已办结数量
            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andStandby1EqualTo("0");
            criteria2.andTkStatusEqualTo(50);
            criteria2.andCreateTimeBetween(releaseStartTime, releaseEndTime);
            int endtaskAll = tkCommonTaskService.countByExample(tkCommonTaskExample2);

            int zzcount = 0;

            int zzendcount = 0;


            int xinbeiCount = 0;

            DecimalFormat df = new DecimalFormat("0.00");//格式化小数
            ret.put("allcount", alltaskCount + zzcount + xinbeiCount);
            ret.put("endcount", endtaskAll + zzendcount + xinbeiCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    @RequestMapping(value = "bigWindow/taskCountByYearAndTypeDS", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountByYearAndTypeDS() {
        String mon = "";
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        Date releaseStartTime = DateUtils.getCurrYearFirst();
        Date releaseEndTime = DateUtils.getCurrYearLast();
        try {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            for (int i = 0; i < 12; i++) {
                Calendar c = Calendar.getInstance();
                c.setTime(releaseStartTime);
                c.add(Calendar.MONTH, 0 + i);//当前月
                Date m = c.getTime();
                mon = format.format(m);
                String[] split = mon.split("-");
                Date firstDayOfMonth1 = getFirstDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Date lastDayOfMonth1 = getLastDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Map<String, Object> map = new HashMap<String, Object>();
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
                map.put("firstDayOfMonth1", format2.format(firstDayOfMonth1));
                map.put("lastDayOfMonth1", format2.format(lastDayOfMonth1));
                map.put("releaseStartTime", releaseStartTime);
                map.put("releaseEndTime", releaseEndTime);
                Map<String, Object> stringObjectMap = tkCommonTaskExtMapper.overBySelfAndSBSJCount(map);

                if (stringObjectMap == null) {
                    stringObjectMap = new HashMap<String, Object>();
                    stringObjectMap.put("zxcl", 0);
                    stringObjectMap.put("sbzx", 0);
                    stringObjectMap.put("old", 0);
                } else {
                    stringObjectMap.put("old", 0);
                }
                stringObjectMap.put("month", mon);
                ret.add(stringObjectMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }

    /**
     * 移动事项一览
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/bigWindowaAllTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String bigWindowaAllTaskNum() {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //创建日常任务数
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            int allCount = tkCommonTaskService.countByExample(tkCommonTaskExample);
            map.put("allTaskCount", allCount);

            //完成日常任务数
            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andTkStatusGreaterThanOrEqualTo(40);//审核通过  待评价
            criteria2.andStandby1EqualTo("0");
            int endSize = tkCommonTaskService.countByExample(tkCommonTaskExample2);
            map.put("endTaskCount", endSize);
            map.put("doingTaskCount", allCount - endSize);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", map));
    }


    /**
     * 根据网格id获取该网格的累计工单 、累计办结、办结率
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/taskNumByCodeAndBaseId", method = RequestMethod.GET)
    @ResponseBody
    public String taskNumByCodeAndBaseId(String wgCode) {
        Map<String, Object> map = new HashMap<String, Object>();

        //查询网格的等级
        GridRegionExample bsWgxxbExample = new GridRegionExample();
        bsWgxxbExample.createCriteria().andWgCodeEqualTo(wgCode);
        List<GridRegion> bsWgxxbs = bsWgxxbService.selectByExample(bsWgxxbExample);
        if (bsWgxxbs == null || bsWgxxbs.size() == 0) {
            return JSON.toJSONString(AjaxResult.build(200, "网格数据为空", map));
        }
        String level = bsWgxxbs.get(0).getLevel();


        try {
            //创建日常任务数
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            if (level.equals("2")) {
                //如果查询2级网格的数量，那么任务表就得查wg_parent_code=code
                criteria.andWgParentIdEqualTo(wgCode);
            } else {
                //如果查询3级网格的数量，那么任务就得查wg_code=code
                criteria.andWgCodeEqualTo(wgCode);
            }
            int allCount = tkCommonTaskService.countByExample(tkCommonTaskExample);
            map.put("allTaskCount", allCount);

            //完成日常任务数
            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andTkStatusGreaterThanOrEqualTo(40);//审核通过  待评价
            if (level.equals("2")) {
                //如果查询2级网格的数量，那么任务表就得查wg_parent_code=code
                criteria2.andWgParentIdEqualTo(wgCode);
            } else {
                //如果查询3级网格的数量，那么任务就得查wg_code=code
                criteria2.andWgCodeEqualTo(wgCode);
            }
            criteria2.andStandby1EqualTo("0");
            int endSize = tkCommonTaskService.countByExample(tkCommonTaskExample2);
            map.put("endTaskCount", endSize);
            map.put("doingTaskCount", allCount - endSize);
            if (endSize == 0 || allCount == 0) {
                map.put("bjl", 0);
            } else {
                DecimalFormat df = new DecimalFormat("0.00");
                map.put("bjl", df.format((double) endSize / (double) allCount));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", map));
    }

    /**
     * 大屏事项来源
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/taskCountByComeFrom", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountByComeFrom(String date, String wgCode, Integer type, String startTime, String endTime) {
        List<Map<String, Object>> tkCommonTasks = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> data = new HashedMap();
            if (StringUtils.isNotBlank(date)) {
                data.put("date", date + "%");
            }
            if (StringUtils.isNotBlank(startTime)) {
                data.put("startTime", startTime);
            }
            if (StringUtils.isNotBlank(endTime)) {
                data.put("endTime", endTime);
            }
            if (type != null) {
                data.put("type", type);
            }

            if (StringUtils.isNotEmpty(wgCode)) {
                data.put("wgCode", wgCode);
            }

            tkCommonTasks = tkCommonTaskService.taskCountByComeFrom(data);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));
    }


    /**
     * 大屏事项来源+zz
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/taskCountByComeFromzongzhi", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountByComeFromzongzhi(String date, Integer type) {
        List<Map<String, Object>> tkCommonTasks = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> zzLists = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> data = new HashedMap();
            if (StringUtils.isNotBlank(date)) {
                data.put("date", date + "%");
            }
            if (type != null) {
                data.put("type", type);
            }

            tkCommonTasks = tkCommonTaskService.taskCountByComeFrom(data);
            //综治数据
            int zzCount = 0;
            //外12345数据

            int waiCount = 0;


            Map<String, Object> zzmap = new HashedMap();
            zzmap.put("comeFrom2", "全要素网格通");
            zzmap.put("comeTaskNum", zzCount);
            tkCommonTasks.add(zzmap);

            Map<String, Object> waimap = new HashedMap();
            waimap.put("comeFrom2", "12345（外）");
            waimap.put("comeTaskNum", waiCount);
            tkCommonTasks.add(waimap);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));
    }


    //老的没人用
    @RequestMapping(value = "bigWindow/taskCountByComeFromzongzhiOld", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountByComeFromzongzhiOld(String date, Integer type) {
        List<Map<String, Object>> tkCommonTasks = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> zzLists = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> data = new HashedMap();
            if (StringUtils.isNotBlank(date)) {
                data.put("date", date + "%");
            }
            if (type != null) {
                data.put("type", type);
            }

            tkCommonTasks = tkCommonTaskService.taskCountByComeFrom(data);
            if (tkCommonTasks != null && tkCommonTasks.size() > 0) {
                for (Map<String, Object> aa : tkCommonTasks) {
                    String comeFrom2 = aa.get("comeFrom2").toString();
                    if (comeFrom2.equals("综合治理")) {
                        Integer zhzlCount = Integer.parseInt(aa.get("comeTaskNum") + "");
                        Integer zzCount = Integer.parseInt(zzLists.get(0).get("allNum") + "");
                        aa.put("comeTaskNum", zhzlCount + zzCount);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));
    }

    /**
     * 大屏网格任务数量
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/bigWindowWGCount", method = RequestMethod.GET)
    @ResponseBody
    public String bigWindowWGCount(@RequestParam String topCode) {
        List<Map<String, Object>> tkCommonTasks = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> data = new HashedMap();
            data.put("topCode", topCode);
            tkCommonTasks = tkCommonTaskService.bigWindowWGCount(data);
            if (tkCommonTasks.size() > 0) {
                for (Map<String, Object> map : tkCommonTasks) {
                    BigWindowWGInfo bigWindowWGInfo = new BigWindowWGInfo();
                    String code = map.get("wg_code").toString();
                    //查询网格下的网格长
                    GridRegionUserExample bsWgxxUserExample = new GridRegionUserExample();
                    GridRegionUserExample.Criteria criteria = bsWgxxUserExample.createCriteria();
                    criteria.andWgIdEqualTo(code);
                    criteria.andYlzd2EqualTo("1");
                    List<GridRegionUser> bsWgxxUsers = bsWgxxUserService.selectByExample(bsWgxxUserExample);
                    bigWindowWGInfo.setWgzList(bsWgxxUsers);

                    //查询网格下的网格员
                    GridRegionUserExample bsWgxxUserExample2 = new GridRegionUserExample();
                    GridRegionUserExample.Criteria criteria2 = bsWgxxUserExample2.createCriteria();
                    criteria2.andWgIdLike(code + "%");
                    criteria2.andYlzd2EqualTo("1");
                    List<GridRegionUser> bsWgxxUsers2 = bsWgxxUserService.selectByExample(bsWgxxUserExample2);
                    if (bsWgxxUsers2 != null && bsWgxxUsers2.size() > 0) {
                        for (int i = 0; i < bsWgxxUsers2.size(); i++) {
                            if (bsWgxxUsers2.get(i).getWgId().length() == 12) {
                                bsWgxxUsers2.remove(i);
                            }
                        }
                    }

                    bigWindowWGInfo.setWgyList(bsWgxxUsers2);
                    map.put("user", bigWindowWGInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));
    }


    /**
     * 常态频发事项类型排行
     *
     * queryType 1查询二级事项来源  2查询三级来源
     * @return
     */
    @RequestMapping(value = "bigWindow/matterRank", method = RequestMethod.GET)
    @ResponseBody
    public String matterRank(@RequestParam(value = "queryType", defaultValue = "1") Integer queryType) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Date releaseStartTime = DateUtils.getCurrYearFirst();
            Date releaseEndTime = DateUtils.getCurrYearLast();
            Map<String, Object> data = new HashedMap();
            data.put("releaseStartTime", releaseStartTime);
            data.put("releaseEndTime", releaseEndTime);
            if (queryType == 1) {
                list = tkCommonTaskService.selectMatterRank(data);
            } else {
                list = tkCommonTaskService.selectMatterRankThreeType(data);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }


    /**
     * 常态频发事项类型排行+综治  统计二级分类
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/matterRankzongzhi", method = RequestMethod.GET)
    @ResponseBody
    public String matterRankzongzhi() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> bac = new ArrayList<Map<String, Object>>();
        try {
            Date releaseStartTime = DateUtils.getCurrYearFirst();
            Date releaseEndTime = DateUtils.getCurrYearLast();
            Map<String, Object> data = new HashedMap();
            data.put("releaseStartTime", releaseStartTime);
            data.put("releaseEndTime", releaseEndTime);
            list = tkCommonTaskService.selectMatterRank(data);
            List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
            all.addAll(list);

            Map<String, List<Map<String, Object>>> glist = all.stream().collect(Collectors.groupingBy(e -> e.get("parent_mattetr_name").toString()));

            glist.forEach((k, slist) -> {
                Map<String, Object> nmap = new HashMap<>();
                IntSummaryStatistics sumcc = slist.stream().collect(Collectors.summarizingInt(e -> Integer.valueOf(e.get("num").toString())));
                nmap.put("parent_mattetr_name", slist.get(0).get("parent_mattetr_name"));
                nmap.put("num", sumcc.getSum());//求和
                bac.add(nmap);

            });


            //根据完成比例倒叙
            Collections.sort(bac, new Comparator<Map<String, Object>>() {

                public int compare(Map<String, Object> o1, Map<String, Object> o2) {

                    // 按照学生的年龄进行降序排列
                    if (Integer.parseInt(o1.get("num") + "") > Integer.parseInt(o2.get("num") + "")) {
                        return -1;
                    }
                    if (Integer.parseInt(o1.get("num") + "") == Integer.parseInt(o2.get("num") + "")) {
                        return 0;
                    }
                    return 1;
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", bac));
    }


    /**
     * 常态频发事项类型排行+综治  统计三级分类
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/matterRankzongzhiThreeType", method = RequestMethod.GET)
    @ResponseBody
    public String matterRankzongzhiThreeType() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> bac = new ArrayList<Map<String, Object>>();
        try {
            Date releaseStartTime = DateUtils.getCurrYearFirst();
            Date releaseEndTime = DateUtils.getCurrYearLast();
            Map<String, Object> data = new HashedMap();
            data.put("releaseStartTime", releaseStartTime);
            data.put("releaseEndTime", releaseEndTime);
            list = tkCommonTaskService.selectMatterRankThreeType(data);
            List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
            all.addAll(list);

            Map<String, List<Map<String, Object>>> glist = all.stream().collect(Collectors.groupingBy(e -> e.get("matter_name").toString()));

            glist.forEach((k, slist) -> {
                Map<String, Object> nmap = new HashMap<>();
                IntSummaryStatistics sumcc = slist.stream().collect(Collectors.summarizingInt(e -> Integer.valueOf(e.get("num").toString())));
                nmap.put("matter_name", slist.get(0).get("matter_name"));
                nmap.put("num", sumcc.getSum());//求和
                bac.add(nmap);

            });


            //根据完成比例倒叙
            Collections.sort(bac, new Comparator<Map<String, Object>>() {

                public int compare(Map<String, Object> o1, Map<String, Object> o2) {

                    // 按照学生的年龄进行降序排列
                    if (Integer.parseInt(o1.get("num") + "") > Integer.parseInt(o2.get("num") + "")) {
                        return -1;
                    }
                    if (Integer.parseInt(o1.get("num") + "") == Integer.parseInt(o2.get("num") + "")) {
                        return 0;
                    }
                    return 1;
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", bac));
    }

    @RequestMapping(value = "bigWindow/matterRankDS", method = RequestMethod.GET)
    @ResponseBody
    public String matterRankDS() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Map.Entry<String, Integer>> result = new ArrayList<>();
        try {
            Date releaseStartTime = DateUtils.getCurrYearFirst();
            Date releaseEndTime = DateUtils.getCurrYearLast();
            Map<String, Object> data = new HashedMap();
            data.put("releaseStartTime", releaseStartTime);
            data.put("releaseEndTime", releaseEndTime);
            list = tkCommonTaskService.selectMatterRank(data);

            Map<String, Integer> DSOldMatter = new HashMap<>();
            DSOldMatter.put("市容环境", 6320);
            DSOldMatter.put("市政设施", 1018);
            DSOldMatter.put("宣传广告类", 676);
            DSOldMatter.put("园林绿化", 144);
            DSOldMatter.put("综合执法管理", 8);
            DSOldMatter.put("政法和社会管理", 3);
            DSOldMatter.put("安监管理", 66);
            DSOldMatter.put("社区管理", 76);
            DSOldMatter.put("建设局管理事项", 792);

            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);

                if (DSOldMatter.containsKey(map.get("parent_mattetr_name"))) {
                    DSOldMatter.put(map.get("parent_mattetr_name") + "", Integer.valueOf(map.get("num") + "") + DSOldMatter.get(map.get("parent_mattetr_name")));
                } else {
                    DSOldMatter.put(map.get("parent_mattetr_name") + "", Integer.valueOf(map.get("num") + ""));
                }

            }
            result = new ArrayList<Map.Entry<String, Integer>>(DSOldMatter.entrySet());

            Collections.sort(result, new Comparator<Map.Entry<String, Integer>>() {
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return (o2.getValue() - o1.getValue());
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }

    /**
     * （2）评价为三颗星的工单--（需要在地图上展示）
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/scoreEqual3", method = RequestMethod.GET)
    @ResponseBody
    public String scoreEqual3() {
        List<TkCommonTask> tkCommonTasks = new ArrayList<TkCommonTask>();
        try {
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andTkScoreEqualTo(3);
            criteria.andStandby1EqualTo("0");
            tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));
    }


    /**
     * 工单评价统计接口
     *
     * @return
     */
    @RequestMapping(value = "tkScore", method = RequestMethod.GET)
    @ResponseBody
    public String tk_score() {
        Map<String, Object> ret = new HashMap<>();
        Date releaseStartTime = DateUtils.getCurrYearFirst();
        Date releaseEndTime = DateUtils.getCurrYearLast();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("releaseStartTime", releaseStartTime);
            map.put("releaseEndTime", releaseEndTime);
            Map<String, String> result = diyService.getTkScore(map);
            String percentOne, percentTwo, percentThree, percentFour, percentFive;

            if (result != null) {
                int one = Integer.parseInt(String.valueOf(result.get("1")));
                int two = Integer.parseInt(String.valueOf(result.get("2")));
                int three = Integer.parseInt(String.valueOf(result.get("3")));
                int four = Integer.parseInt(String.valueOf(result.get("4")));
                int five = Integer.parseInt(String.valueOf(result.get("5")));

                int totalValid = one + two + three + four + five;
                // 创建一个数值格式化对象
                NumberFormat numberFormat = NumberFormat.getInstance();
                // 设置精确到小数点后1位
                numberFormat.setMaximumFractionDigits(1);
                percentOne = numberFormat.format((float) one / (float) totalValid * 100);
                percentTwo = numberFormat.format((float) two / (float) totalValid * 100);
                percentThree = numberFormat.format((float) three / (float) totalValid * 100);
                percentFour = numberFormat.format((float) four / (float) totalValid * 100);
                percentFive = numberFormat.format((float) five / (float) totalValid * 100);

                ret.put("one", percentOne + "%");
                ret.put("two", percentTwo + "%");
                ret.put("three", percentThree + "%");
                ret.put("four", percentFour + "%");
                ret.put("five", percentFive + "%");
            } else {
                ret.put("one", "0%");
                ret.put("two", "0%");
                ret.put("three", "0%");
                ret.put("four", "0%");
                ret.put("five", "0%");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }

    /**
     * 根据部门id 获取该部门下今日所有人员创建的工单
     *
     * @return
     */
    @RequestMapping(value = "getTaskByDepartmentId", method = RequestMethod.GET)
    @ResponseBody
    public String getTaskByDepartmentId(@RequestParam String deptId) {
        Map<String, Object> ret = new HashMap<>();
        if (StringUtils.isBlank(deptId)) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "部门id不能为空"));
        }
        //根据部门查询部门下所有员工
        List<SysUser> sysUsers = sysUserService.listByDepId(Long.parseLong(deptId));
        if (CollectionUtils.isEmpty(sysUsers)){
            return JSON.toJSONString(AjaxResult.build(200, "success", ret));
        }
        List<String> userIds = sysUsers.stream().map(SysUser::getUserId).map(String::valueOf).collect(Collectors.toList());
        try {
            //日受理
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andReleaseUserIdIn(userIds);
            criteria.andStandby1EqualTo("0");
            criteria.andCreateTimeBetween(DateUtils.getStartTime(), DateUtils.getEndTime());
//            int dayCount = tkCommonTaskService.countByExample(tkCommonTaskExample);
            List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
            ret.put("rslgd", tkCommonTasks.size());


            //月受理
            TkCommonTaskExample tkCommonTaskExampleMonth = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteriaMonth = tkCommonTaskExampleMonth.createCriteria();
            criteriaMonth.andReleaseUserIdIn(userIds);
            criteriaMonth.andStandby1EqualTo("0");
            criteriaMonth.andCreateTimeBetween(DateUtils.getBeginDayOfMonth(), DateUtils.getEndDayOfMonth());
            int monthCount = tkCommonTaskService.countByExample(tkCommonTaskExampleMonth);
            ret.put("yslgd", monthCount);

            //累计受理
            TkCommonTaskExample tkCommonTaskExampleAll = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteriaAll = tkCommonTaskExampleAll.createCriteria();
            criteriaAll.andReleaseUserIdIn(userIds);
            criteriaAll.andStandby1EqualTo("0");
            int allCount = tkCommonTaskService.countByExample(tkCommonTaskExampleAll);
            ret.put("ljslgd", allCount);

            //累计未办结工单
            TkCommonTaskExample tkCommonTaskExampleNotEnd = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteriaNotEnd = tkCommonTaskExampleNotEnd.createCriteria();
            criteriaNotEnd.andReleaseUserIdIn(userIds);
            criteriaNotEnd.andStandby1EqualTo("0");
            criteriaNotEnd.andTkStatusLessThan(50);
            ret.put("notEndAll", tkCommonTaskService.countByExample(tkCommonTaskExampleNotEnd));
            Date d = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String ds = df.format(d);
            Date today = df.parse(ds);
            int jijiangchaoshiNum = 0;
            //判断今日即将超时的工单
            if (tkCommonTasks != null && tkCommonTasks.size() > 0) {
                for (TkCommonTask tkCommonTask : tkCommonTasks) {
                    if (tkCommonTask.getTkStatus() > 10 && tkCommonTask.getTkStatus() < 30 && tkCommonTask.getTkStatus() != 16 && tkCommonTask.getAssignedEndTime() != null) {
                        int day = tkCommonTask.getAssignedEndTime().compareTo(today);//返回正值是代表左侧日期大于参数日期，反之亦然，日期格式必须一致
                        //大于0 则表示未超时 小于等于2 则表示即将超时
                        if (day <= 2 && day > 0) {
                            jijiangchaoshiNum++;
                        }
                    }
                    if (tkCommonTask.getTkStatus() >= 30 && tkCommonTask.getTkStatus() < 40 && tkCommonTask.getVerificationEndTime() != null) {
                        int day = tkCommonTask.getVerificationEndTime().compareTo(today);//返回正值是代表左侧日期大于参数日期，反之亦然，日期格式必须一致
                        //大于0 则表示未超时 小于等于2 则表示即将超时
                        if (day <= 2 && day > 0) {
                            jijiangchaoshiNum++;
                        }
                    }

                }
            }
            ret.put("jijiangchaoshiNum", jijiangchaoshiNum);


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    /**
     * 根据用户id获取今日创建工单
     *
     * @return
     */
    @RequestMapping(value = "createCountByUserId", method = RequestMethod.GET)
    @ResponseBody
    public String createCountByUserId(@RequestParam String userId) {
        Map<String, Object> ret = new HashMap<>();

        try {

            //日受理
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andReleaseUserIdEqualTo(userId);
            criteria.andStandby1EqualTo("0");
            criteria.andCreateTimeBetween(DateUtils.getStartTime(), DateUtils.getEndTime());
            int dayCount = tkCommonTaskService.countByExample(tkCommonTaskExample);//日创建
            ret.put("rslgdByUser", dayCount);


            //月受理
            TkCommonTaskExample tkCommonTaskExampleMonth = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteriaMonth = tkCommonTaskExampleMonth.createCriteria();
            criteriaMonth.andReleaseUserIdEqualTo(userId);
            criteriaMonth.andStandby1EqualTo("0");
            criteriaMonth.andCreateTimeBetween(DateUtils.getBeginDayOfMonth(), DateUtils.getEndDayOfMonth());
            int monthCount = tkCommonTaskService.countByExample(tkCommonTaskExampleMonth);
            ret.put("yslgdByUser", monthCount);

            //累计上报工单
            TkCommonTaskExample tkCommonTaskExampleAll = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteriaAll = tkCommonTaskExampleAll.createCriteria();
            criteriaAll.andReleaseUserIdEqualTo(userId);
            criteriaAll.andStandby1EqualTo("0");
            int allCount = tkCommonTaskService.countByExample(tkCommonTaskExampleAll);
            ret.put("ljslgdByUser", allCount);

            //累计未办结工单
            TkCommonTaskExample tkCommonTaskExampleNotEnd = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteriaNotEnd = tkCommonTaskExampleNotEnd.createCriteria();
            criteriaNotEnd.andReleaseUserIdEqualTo(userId);
            criteriaNotEnd.andStandby1EqualTo("0");
            criteriaNotEnd.andTkStatusLessThan(50);
            ret.put("notEndAllByUser", tkCommonTaskService.countByExample(tkCommonTaskExampleNotEnd));


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }

    /**
     * 日上报 日办理数量
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/todayTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String todayTaskNum(int type) {
        Map<String, Object> ret = new HashMap<>();
        try {
            //1日上报 日办理数量 2周  3月
            Date startTime = null;
            Date endTime = null;

            SimpleDateFormat format = new SimpleDateFormat();
            format.applyPattern("YYYY-MM-dd HH:mm:ss");

            if (type == 1) {
                startTime = DateUtils.getStartTime();
                endTime = DateUtils.getEndTime();
            } else if (type == 2) {
                startTime = DateUtils.getBeginDayOfWeek();
                endTime = DateUtils.getEndDayOfWeek();
            } else if (type == 3) {
                startTime = DateUtils.getBeginDayOfMonth();
                endTime = DateUtils.getEndDayOfMonth();
            }
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            criteria.andHandleTypeEqualTo(2);//2上报中心
            criteria.andReleaseTimeBetween(startTime, endTime);
            int shangbaoCount = tkCommonTaskService.countByExample(tkCommonTaskExample);
            ret.put("shangbao", shangbaoCount);

            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andStandby1EqualTo("0");
            criteria2.andTkStatusGreaterThanOrEqualTo(40);
            criteria2.andReleaseTimeBetween(startTime, endTime);
            int endCount = tkCommonTaskService.countByExample(tkCommonTaskExample2);

            int xinbeiCount = 0;

            ret.put("endCount", endCount + xinbeiCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    @RequestMapping(value = "bigWindow/todayTaskNumMix", method = RequestMethod.GET)
    @ResponseBody
    public String todayTaskNumMix(int type) {
        Map<String, Object> ret = new HashMap<>();
        try {
            //1日上报 日办理数量 2周  3月
            Date startTime = null;
            Date endTime = null;

            SimpleDateFormat format = new SimpleDateFormat();
            format.applyPattern("YYYY-MM-dd HH:mm:ss");

            if (type == 1) {
                startTime = DateUtils.getStartTime();
                endTime = DateUtils.getEndTime();
            } else if (type == 2) {
                startTime = DateUtils.getBeginDayOfWeek();
                endTime = DateUtils.getEndDayOfWeek();
            } else if (type == 3) {
                startTime = DateUtils.getBeginDayOfMonth();
                endTime = DateUtils.getEndDayOfMonth();
            }

            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            criteria.andHandleTypeEqualTo(2);//2上报中心
            criteria.andReleaseTimeBetween(startTime, endTime);
            int shangbaoCount = tkCommonTaskService.countByExample(tkCommonTaskExample);

            int zongzhiSBCount = 0;
            ret.put("shangbao", shangbaoCount + zongzhiSBCount);

            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andStandby1EqualTo("0");
            criteria2.andTkStatusGreaterThanOrEqualTo(40);
            criteria2.andReleaseTimeBetween(startTime, endTime);
            int endCount = tkCommonTaskService.countByExample(tkCommonTaskExample2);

            int xinbeiCount = 0;

            List<String> sjztList = new ArrayList<>();
            sjztList.add("已办结");
            sjztList.add("自行处置");
            sjztList.add("已结案");
            int zongzhiEndCount = 0;

            ret.put("endCount", endCount + xinbeiCount + zongzhiEndCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    /**
     * 区级今日新增今日办理工单数量接口 不包含综治
     *
     * @return
     */
    @RequestMapping(value = "areaTodayTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String qvtodayTaskNum(int type) {

        Map<String, Object> ret = new HashMap<>();
        try {
            //1日上报 日办理数量 2周  3月
            Date startTime = null;
            Date endTime = null;
            if (type == 1) {
                startTime = DateUtils.getStartTime();
                endTime = DateUtils.getEndTime();
            } else if (type == 2) {
                startTime = DateUtils.getBeginDayOfWeek();
                endTime = DateUtils.getEndDayOfWeek();
            } else if (type == 3) {
                startTime = DateUtils.getBeginDayOfMonth();
                endTime = DateUtils.getEndDayOfMonth();
            }

            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            criteria.andReleaseTimeBetween(startTime, endTime);
            int shangbaoCount = tkCommonTaskService.countByExample(tkCommonTaskExample);
            ret.put("shangbao", shangbaoCount);

            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andStandby1EqualTo("0");
            criteria2.andTkStatusGreaterThanOrEqualTo(40);
            criteria2.andAssignedTimeBetween(startTime, endTime);
            int endCount = tkCommonTaskService.countByExample(tkCommonTaskExample2);
            ret.put("endCount", endCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    private void XZData(List<Map<String, Object>> idAndName) {
        try {

            String url = managedataUrl + "/manageData/getXZData";
            //获取区下所有乡镇
            Map<String, String> map = new HashedMap();
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");
            String ret = ZQTHttpHelper.doPostJson(url, JSON.toJSONString(map), headParams);


            JSONObject jsonObject = JSONObject.parseObject(ret);
            if (jsonObject != null && jsonObject.get("msg").equals("success")) {
                JSONArray data = (JSONArray) jsonObject.get("data");
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jo = (JSONObject) data.get(i);
                    Map<String, Object> idName = new HashedMap();
                    if (jo.get("xzmc") != null) {
                        idName.put("name", jo.get("xzmc").toString());
                    }
                    if (jo.get("longitude") != null) {
                        idName.put("longitude", jo.get("longitude").toString());
                    }
                    if (jo.get("latitude") != null) {
                        idName.put("latitude", jo.get("latitude").toString());
                    }
                    idAndName.add(idName);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 区级 工单数量（累计工单 办结工单 办结率）
     *
     * @return
     */
    @RequestMapping(value = "areaTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String areaTaskNum(String wgCode) {
        Map map = new HashedMap();
        try {


            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            if (StringUtils.isNotEmpty(wgCode)) criteria.andWgCodeLike(wgCode + "%");
            int allCount = tkCommonTaskService.countByExample(tkCommonTaskExample);
            map.put("allCount", allCount);//累计工单

            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andStandby1EqualTo("0");
            if (StringUtils.isNotEmpty(wgCode)) criteria2.andWgCodeLike(wgCode + "%");
            criteria2.andTkStatusEqualTo(50);
            int endCount = tkCommonTaskService.countByExample(tkCommonTaskExample2);
            map.put("endCount", endCount);//办结工单

            DecimalFormat df = new DecimalFormat("######0.00");
            if (allCount == 0) {
                map.put("bjl", 0 + "%");
            } else {
                map.put("bjl", df.format(((double) endCount / (double) allCount) * 100) + "%");
            }


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", map));
    }

    //大屏网格工单列表

    /**
     * 任务查询
     *
     * @param pageNum       当前页数
     * @param pageSize      一页几行
     * @param loginUserId   登录人id
     * @param loginUserRole 3三级 2二级 1一级 0中心
     *                      queryType 1查询未完成  2查询已完成
     * @return
     */
    @RequestMapping(value = "bigWindow/taskList", method = RequestMethod.GET)
    @ResponseBody
    public String bigWindowTaskList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                    @RequestParam String loginUserId,
                                    @RequestParam String loginUserRole,
                                    @RequestParam String roleCode,
                                    @RequestParam(required = false) Integer comeFrom,
                                    @RequestParam(value = "queryType", defaultValue = "1") int queryType) {
        TaskCommonListRequest request = new TaskCommonListRequest();
        if (queryType == 1) {
            request.setUnfinished(true);//未完成
        } else {
            request.setFinished(true);//已完成
        }
        request.setComeFrom(comeFrom);
        request.setLoginUserId(loginUserId);
        request.setLoginUserRole(loginUserRole);
        request.setLoginUserRole(loginUserRole);
        ZQTPageModel result = new ZQTPageModel();
        try {
            PageInfo<TkCommonTask> page = tkCommonTaskService.selectList(request.params(),pageNum,pageSize);
            if (page.getList().size() > 0) {
                for (int i = 0; i < page.getList().size(); i++) {
                    //查询是否有催办记录
                    TkCommonTaskDynamicExample tkCommonTaskDynamicExample = new TkCommonTaskDynamicExample();
                    TkCommonTaskDynamicExample.Criteria criteria = tkCommonTaskDynamicExample.createCriteria();
                    criteria.andCommonTkIdEqualTo(page.getList().get(i).getId());
                    criteria.andCuibanReasonIsNotNull();
                    if (tkCommonTaskDynamicService.selectByExample(tkCommonTaskDynamicExample).size() > 0) {
                        page.getList().get(i).setCuiban(true);
                    } else {
                        page.getList().get(i).setCuiban(false);
                    }

                    //红黄绿灯
                    int color = 1;//正常
                    TkCommonTask tkCommonTask = page.getList().get(i);
                    if (tkCommonTask.getTkStatus() >= 10 && tkCommonTask.getTkStatus() < 30
                            && tkCommonTask.getTkStatus() != 16 && tkCommonTask.getAssignedEndTime() != null) {
                        long day = diffDay(tkCommonTask.getAssignedEndTime());
                        if (day > 0 && day <= 2) {
                            color = 2;//警告
                        }
                        if (day < 0) {
                            color = 3;//超时
                        }
                    }
                    if (tkCommonTask.getTkStatus() >= 30 && tkCommonTask.getTkStatus() < 40 && tkCommonTask.getVerificationEndTime() != null) {
                        long day = diffDay(tkCommonTask.getVerificationEndTime());
                        if (day > 0 && day <= 2) {
                            color = 2;//警告
                        }
                        if (day < 0) {
                            color = 3;//超时
                        }
                    }
                    if (tkCommonTask.getTkStatus() > 40) {
                        color = 4;//完成。
                    }

                    tkCommonTask.setColor(color);
                }
            }


            //分页
            result.setItemList(page.getList());
            //总记录数
            result.setRecordCount(page.getTotal());
            //总页数
            result.setPageCount(page.getPages());
            //当前页
            result.setCurPage(page.getPageNum());
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "查询出错"));
        }

        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }


    /**
     * 时间比较
     *
     * @param endTime
     * @return
     */
    public long diffDay(Date endTime) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d2 = new Date();
        Date d1 = endTime;
        long diff = d1.getTime() - d2.getTime();//这样得到的差值是毫秒级别
        long days = diff / (1000 * 60 * 60 * 24);

        long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
        System.out.println("" + days + "天" + hours + "小时" + minutes + "分");
        return days;
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, HttpServletRequest request, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 根据时间排序
     *
     * @param list
     */
    private static void ListSort(List<TkCommonTask> list) {
        Collections.sort(list, new Comparator<TkCommonTask>() {
            @Override
            public int compare(TkCommonTask o1, TkCommonTask o2) {
                try {
                    Date dt1 = o1.getCreateTime();
                    Date dt2 = o2.getCreateTime();
                    if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }

    /**
     * 查询最后一条指派人信息
     *
     * @param id
     * @return
     */
    private List<TkCommonAssigned> getTkCommonAssigneds(@RequestParam String id) {
        TkCommonAssignedExample tkCommonAssignedExample = new TkCommonAssignedExample();
        TkCommonAssignedExample.Criteria criteria1 = tkCommonAssignedExample.createCriteria();
        criteria1.andCommonTkIdEqualTo(id);
        tkCommonAssignedExample.setOrderByClause("assigned_status desc");
        List<TkCommonAssigned> list = tkCommonAssignedService.selectByExample(tkCommonAssignedExample);
        if(CollectionUtils.isEmpty(list)){
            return list;
        }
        Integer maxStatus = list.stream().mapToInt(TkCommonAssigned::getAssignedStatus).max().getAsInt();
        return list.stream().filter(t->maxStatus.equals(t.getAssignedStatus())).collect(Collectors.toList());
    }


    /**
     * 获取过去或者未来 任意天内的日期数组
     *
     * @param intervals intervals天内
     * @return 日期数组
     */
    public static ArrayList<Date> getDateList(int intervals) {
        ArrayList<Date> pastDaysList = new ArrayList<>();
        for (int i = 0; i < intervals; i++) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }

    public static ArrayList<Date> getDateList(int intervals, String startTime) {
        ArrayList<Date> pastDaysList = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int d = 1;
        for (int i = 0; i < intervals; i++) {
            Date parse = formatter.parse(startTime, new ParsePosition(0));
            calendar.setTime(parse);
            //i ---->后几天，-i ---->前几天
            calendar.add(Calendar.DATE, -i);
            Date time = calendar.getTime();
            String toTime = formatter.format(time);
            try {
                pastDaysList.add(formatter.parse(toTime));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("第" + d + "天：" + toTime);
            d++;
        }
        return pastDaysList;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static Date getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        try {
            return format.parse(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取指定年月的第一天
     *
     * @param year
     * @param month
     * @return
     */
    public Date getFirstDayOfMonth1(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return cal.getTime();
    }


    /**
     * 获取指定年月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public Date getLastDayOfMonth1(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return cal.getTime();
    }


    /**
     * 自行处理接口
     * 上报上级后的自行处理接口
     *
     * @return
     */
    @RequestMapping(value = "selectNewData", method = RequestMethod.GET)
    @ResponseBody
    public String selectNewData() {
        List<TkCommonTaskParams> list = new ArrayList<TkCommonTaskParams>();
        //查询塔集镇下面的所有没有查询过的数据
        TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
        criteria.andStandby5EqualTo("0");
        List<TkCommonTask> tkTaskList = tkCommonTaskService.selectByExample(tkCommonTaskExample);
        //更新被查询的任务的是否已被查询过的状态
        for (TkCommonTask m : tkTaskList) {
            TkCommonTaskParams result = new TkCommonTaskParams();
            m.setStandby5("1");
            tkCommonTaskService.updateByPrimaryKey(m);

            BeanUtils.copyProperties(m, result);
            result.setItemOneTypeValue("100000000000102");
            result.setItemOneTypeName("环境保护");
            result.setItemTwoTypeValue("10283");
            result.setItemTwoTypeName("固废污染");
            result.setTkDetail(m.getTkDetail());
            list.add(result);
        }

        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }


    /**
     * 日常任务发布 tkCommonTask TkCommonTaskExt
     *
     * @param
     * @return
     */
    @RequestMapping(value = "addNew", method = RequestMethod.POST)
    @ResponseBody
    public String addNew(@RequestBody TkCommonTask tkCommonTask) {
        taskService.addNew(tkCommonTask);
        return JSON.toJSONString(AjaxResult.build(200, "success", "保存成功"));
    }

    /**
     *
     */
    /**
     * 已办日常任务插入
     *
     * @param
     * @return
     */
    @RequestMapping(value = "overTask", method = RequestMethod.POST)
    @ResponseBody
    public String overTask(@RequestBody TkCommonTaskExt tkCommonTaskext) {
        TkCommonTask tkCommonTask = new TkCommonTask();
        BeanUtils.copyProperties(tkCommonTaskext, tkCommonTask);
        TkCommonTask tkTaskModel = tkCommonTaskService.selectByPrimaryKey(tkCommonTask.getId());
        if (tkTaskModel != null) {
            return JSON.toJSONString(AjaxResult.build(200, "success", "数据已存在"));
        }

        tkCommonTask.setWgCode("320831003");
        tkCommonTask.setReleaseUserId("b34e3c4c-964d-47b6-9e49-394c9671682d");
        tkCommonTask.setLoginUserGrid("塔集镇");
        tkCommonTask.setLoginUserRole("1");
        tkCommonTask.setComeFrom(1);
        tkCommonTask.setBelongGrid("陆河村委会网格一");
        tkCommonTask.setStandby1("1");
        tkCommonTask.setMatterType(1);
        tkCommonTask.setStandby5("1");
        tkCommonTask.setHandleType(3);
        if (tkCommonTask.getMatterName().equals("环境保护")) {
            tkCommonTask.setMatterId("7966e584-0000-49bc-8a21-0a2530ddc29c");
        } else if (tkCommonTask.getMatterName().equals("专项活动")) {
            tkCommonTask.setMatterId("b032724b-8126-47f1-9624-29076c6e9200");
        } else if (tkCommonTask.getMatterName().equals("民生服务")) {
            tkCommonTask.setMatterId("99516661-ac6f-411d-a861-8aa3a95f2f8f");
        } else if (tkCommonTask.getMatterName().equals("城市管理")) {
            tkCommonTask.setMatterId("f3d006d0-059d-4910-a250-fda0379b0594");
        } else if (tkCommonTask.getMatterName().equals("公共安全")) {
            tkCommonTask.setMatterId("3dfe4337-7242-463e-95d2-effe351dcec2");
        } else if (tkCommonTask.getMatterName().equals("社会治安")) {
            tkCommonTask.setMatterId("cb4c8a6b-ca5f-483e-97af-b5fa8a403b2c");
        } else if (tkCommonTask.getMatterName().equals("矛盾纠纷标准")) {
            tkCommonTask.setMatterId("26965953-db6a-4616-b53a-236ced32cc66");
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String releaseTime = sdf.format(tkCommonTask.getReleaseTime());
            tkCommonTask.setReleaseTime(tkCommonTask.getReleaseTime());
        } catch (Exception e) {
            e.printStackTrace();
        }

        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dateNowStr = sdf.format(d);
        System.out.println("格式化后的日期：" + dateNowStr);
        tkCommonTask.setTkId(dateNowStr.substring(0, 15));
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
        try {
            tkCommonTask.setCreateTime(tkCommonTask.getReleaseTime());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //创建上报实体类
        TkCommonReport tkCommonReport = new TkCommonReport();
        tkCommonReport.setId(UUID.randomUUID().toString());
        tkCommonReport.setCommonTkId(tkCommonTask.getId());
        tkCommonReport.setCreateTime(new Date());
        String roleCode = "";//


        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
        Date assignedEndTime = null;
        try {
            String format = sdf3.format(tkCommonTask.getReleaseTime());
            assignedEndTime = sdf3.parse(format);
        } catch (Exception e) {
            LOGGER.error("异常",e);
        }
        //创建指派实体类 如果是自行处理就得保存  自己指派给自己
        TkCommonAssigned tkCommonAssigned = null;

        tkCommonTask.setTkStatus(50);
        tkCommonTask.setStandby2("0");
        tkCommonReport.setTolevel("0");
        roleCode = "centerman";

        String now2 = sdf2.format(tkCommonTask.getReleaseTime());
        try {
            tkCommonAssigned.setCreateTime(sdf2.parse(now2));
        } catch (Exception e) {
            LOGGER.error("异常",e);
        }
        tkCommonTask.setStandby1("0");
        tkCommonTask.setCreateBy(tkCommonTask.getReleaseUserId());

        //自动指派逻辑
        List<GridItemDaily> bsRcsxbs = new ArrayList<GridItemDaily>();//自行指派的数据
        AjaxResult result = new AjaxResult();//根据角色获取用户们

        //数据 上报上级的接收人数据 所以当前登录角色为2级 就查询中心的用户。
        AjaxResult result2 = new AjaxResult();//根据角色获取用户们

        String uname = tkCommonTask.getReleaseUserName();
        tkCommonTask.setReleaseUserName(uname);
        tkCommonTask.setVerificationUserName(uname);
        tkCommonTask.setAssignedUserName(uname);
        tkCommonTask.setAssAssignedUserName(uname);
        tkCommonTask.setVerificationUserName(uname);
        tkCommonTask.setPerformUserName(uname);
        tkCommonTask.setPjPersonName(uname);
        tkCommonTask.setAssBeassignedUserName(uname);
        tkCommonTask.setZpVerificationUserName(uname);
        tkCommonTask.setAssAssignedUserName(uname);

        tkCommonTask.setReleaseTime(tkCommonTask.getReleaseTime());
        tkCommonTask.setAssignedEndTime(tkCommonTask.getReleaseTime());
        tkCommonTask.setAssignedTime(tkCommonTask.getReleaseTime());
        tkCommonTask.setVerificationTime(tkCommonTask.getReleaseTime());
        tkCommonTask.setEndTime(tkCommonTask.getReleaseTime());


        try {
            if (tkCommonTaskService.saveTask(tkCommonTask, tkCommonReport, bsRcsxbs, result, tkCommonAssigned, result2) == 0) {
                return JSON.toJSONString(AjaxResult.build(400, "fail", "保存出错"));
            }


            TkCommonTaskDynamic tkCommonTaskDynamic = new TkCommonTaskDynamic();
            tkCommonTaskDynamic.setId(UUID.randomUUID().toString());
            tkCommonTaskDynamic.setCommonTkId(tkCommonTask.getId());
            tkCommonTaskDynamic.setName(tkCommonTask.getReleaseUserName());
            tkCommonTaskDynamic.setAddress("塔集镇");
            tkCommonTaskDynamic.setNote(tkCommonTaskext.getRemark());
            tkCommonTaskDynamic.setTkTime(tkCommonTask.getReleaseTime());
            tkCommonTaskDynamic.setCreateTime(tkCommonTask.getReleaseTime());
            tkCommonTaskDynamic.setReturnReason(tkCommonTaskext.getRemark());//退回原因

            tkCommonTaskDynamicService.insert(tkCommonTaskDynamic);


            TkCommonAssigned TkCommonAssigned = new TkCommonAssigned();//任务指派实体类
            TkCommonAssigned.setId(UUID.randomUUID().toString());
            TkCommonAssigned.setCommonTkId(tkCommonTask.getId());
            TkCommonAssigned.setAssignedUserId(tkCommonTask.getReleaseUserId());//指派人id
            TkCommonAssigned.setAssignedUserName(tkCommonTask.getReleaseUserName());//指派人姓名
            TkCommonAssigned.setAssignedEndTime(tkCommonTask.getReleaseTime());
            TkCommonAssigned.setAssignedNode(tkCommonTaskext.getRemark());
            TkCommonAssigned.setBeassignedUserId(tkCommonTask.getReleaseUserId());//被指派人用户id
            TkCommonAssigned.setBeassignedUserName(tkCommonTask.getReleaseUserName());//被指派人用户名
            TkCommonAssigned.setCreateTime(tkCommonTask.getReleaseTime());

            TkCommonAssignedExample tkCommonAssignedExample = new TkCommonAssignedExample();
            TkCommonAssignedExample.Criteria criteria = tkCommonAssignedExample.createCriteria();
            criteria.andCommonTkIdEqualTo(tkCommonTask.getId());
            //查询有关联任务id 的数据
            List<TkCommonAssigned> tkCommonAssigneds = tkCommonAssignedService.selectByExample(tkCommonAssignedExample);
            if (tkCommonAssigneds.size() > 0) {//
                int status = tkCommonAssigneds.get(tkCommonAssigneds.size() - 1).getAssignedStatus();//取出最后一条
                TkCommonAssigned.setAssignedStatus(status + 1);//取出最后一条数据的状态+1
            } else {
                TkCommonAssigned.setAssignedStatus(1);//没数据就设为 1
            }

            tkCommonAssignedService.insert(TkCommonAssigned);


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "保存出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "保存成功"));

    }


    @RequestMapping(value = "xinBeiTask", method = RequestMethod.POST)
    @ResponseBody
    public String xinBeiTask(@RequestBody TkCommonTaskExt tkCommonTaskext) {
        TkCommonTask tkCommonTask = new TkCommonTask();
        BeanUtils.copyProperties(tkCommonTaskext, tkCommonTask);

        TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
        criteria.andTkIdEqualTo(tkCommonTask.getTkId());
        TkCommonTask existTkCommonTask = tkCommonTaskService.selectFirstByExample(tkCommonTaskExample);

        boolean flag = false;
        if (null != existTkCommonTask) {
            tkCommonTask.setId(existTkCommonTask.getId());
            flag = true;
        } else {
            tkCommonTask.setId(UUID.randomUUID().toString());
        }

        if (StringUtils.isNotBlank(tkCommonTaskext.getSjfl()) && StringUtils.isNotBlank(tkCommonTaskext.getMatterId())) {
            GridItemDailyExample bsRcsxbExample = new GridItemDailyExample();
            GridItemDailyExample.Criteria criteria1 = bsRcsxbExample.createCriteria();
            criteria1.andSjflEqualTo(tkCommonTaskext.getSjfl());
            criteria1.andSxbmEqualTo(tkCommonTaskext.getMatterId());
            GridItemDaily bsRcsxb = bsRcsxbService.selectFirstByExample(bsRcsxbExample);

            if (null != bsRcsxb) {
                tkCommonTask.setMatterName(bsRcsxb.getSxmc());
            }
        }

        Integer tkStatus = tkCommonTask.getTkStatus();

        GridRegionUserExample bsWgxxUserExample = new GridRegionUserExample();
        GridRegionUserExample.Criteria bsWgxxUserCr = bsWgxxUserExample.createCriteria();
        bsWgxxUserCr.andUserIdEqualTo(tkCommonTask.getReleaseUserId());
        GridRegionUser bsWgxxUser = bsWgxxUserService.selectFirstByExample(bsWgxxUserExample);

        if (null != bsWgxxUser && StringUtils.isNotBlank(bsWgxxUser.getWgId())) {
            GridRegionExample bsWgxxbExample = new GridRegionExample();
            GridRegionExample.Criteria bsWgxxbCr = bsWgxxbExample.createCriteria();
            bsWgxxbCr.andWgCodeEqualTo(bsWgxxUser.getWgId());
            GridRegion bsWgxxb = bsWgxxbService.selectFirstByExample(bsWgxxbExample);

            if (null != bsWgxxb) {
                tkCommonTask.setBelongGrid(bsWgxxb.getWgName());
                tkCommonTask.setWgCode(bsWgxxb.getWgCode());
            }
        }

        tkCommonTask.setLoginUserRole("1");
        tkCommonTask.setComeFrom(1);
        tkCommonTask.setStandby1("1");
        tkCommonTask.setMatterType(1);
        tkCommonTask.setStandby5("1");
        tkCommonTask.setHandleType(0);

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
        try {
            tkCommonTask.setCreateTime(tkCommonTask.getReleaseTime());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //创建指派实体类 如果是自行处理就得保存  自己指派给自己

        tkCommonTask.setStandby2("0");

        tkCommonTask.setStandby1("0");
        tkCommonTask.setCreateBy(tkCommonTask.getReleaseUserId());

        String uname = tkCommonTask.getReleaseUserName();
        String uId = tkCommonTask.getReleaseUserId();
        tkCommonTask.setReleaseUserName(uname);
        tkCommonTask.setReleaseUserId(uId);
        tkCommonTask.setAssignedUserName(uname);
        tkCommonTask.setAssignedUserId(uId);

        tkCommonTask.setCreateTime(new Date());
        tkCommonTask.setIsYouxiao(0);

        tkCommonTask.setReleaseTime(new Date());
        if (null != tkStatus && 50 == tkStatus) {
            tkCommonTask.setVerificationUserName(uname);
            tkCommonTask.setVerificationUserId(uId);

            tkCommonTask.setAssignedUserName(uname);
            tkCommonTask.setAssignedUserId(uId);
            tkCommonTask.setVerificationUserName(uname);
            tkCommonTask.setReleaseUserId(uId);
            tkCommonTask.setPerformUserName(uname);
            tkCommonTask.setReleaseUserId(uId);
            tkCommonTask.setZpVerificationUserId(uId);
            tkCommonTask.setPjPersonId(uId);

            tkCommonTask.setPjPersonName(uname);
            tkCommonTask.setAssBeassignedUserName(uname);
            tkCommonTask.setZpVerificationUserName(uname);

            tkCommonTask.setReleaseTime(tkCommonTask.getReleaseTime());
            tkCommonTask.setAssignedEndTime(tkCommonTask.getReleaseTime());
            tkCommonTask.setAssignedTime(tkCommonTask.getReleaseTime());
            tkCommonTask.setVerificationTime(tkCommonTask.getReleaseTime());
            tkCommonTask.setEndTime(tkCommonTask.getReleaseTime());

            tkCommonTask.setAssignedEndTime(tkCommonTask.getReleaseTime());
            tkCommonTask.setAssignedTime(tkCommonTask.getReleaseTime());
            tkCommonTask.setVerificationTime(tkCommonTask.getReleaseTime());
            tkCommonTask.setVerificationEndTime(tkCommonTask.getReleaseTime());
            tkCommonTask.setVerificationStatus(0);
            tkCommonTask.setTkScore(5);
            tkCommonTask.setReleaseTime(tkCommonTask.getReleaseTime());
        }

        try {
            int num = 0;
            if (flag) {
                num = tkCommonTaskService.updateByPrimaryKeySelective(tkCommonTask);
            } else {
                num = tkCommonTaskService.insert(tkCommonTask);
            }

            if (num == 0) {
                return JSON.toJSONString(AjaxResult.build(400, "fail", "保存出错"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "保存出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "保存成功"));
    }


    /**
     * 每日日常统计
     *
     * @return
     */
    @RequestMapping(value = "statistics", method = RequestMethod.GET)
    @ResponseBody
    public String statistics(String date) {
        //如果传进来的时间为空 就设置为今天的时间。
        Date selectDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATAFORMAT_STR);
        String now = sdf.format(new Date());
        if (StringUtils.isNotBlank(date)) {
            selectDate = DateUtil.getDate(date, DateUtil.DATAFORMAT_STR);
        } else {
            selectDate = DateUtil.getDate(now, DateUtil.DATAFORMAT_STR);
        }
        Map<String, Object> map = new HashMap<>();

        try {
            // 先取到某政府下有效的3级基础网格，再更具这个查到所有plan
            List<GridRegion> third = diyService.getThird();
            List<String> gridIds = new ArrayList<>();//所有三级网格code
            for (GridRegion bsWgxxb : third) {
                gridIds.add(bsWgxxb.getWgCode());
            }

            Map<String, Object> para = new HashMap<String, Object>();
            para.put("gridIds", gridIds);
            para.put("selectDate", selectDate);
            List<TkCommonTask> tkCommonTasks = tkCommonTaskService.taskListByWgCode(para);
            int SBNum = tkCommonTasks.size();

            TkCommonTaskExample tkCommonTaskExample1 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria1 = tkCommonTaskExample1.createCriteria();
            criteria1.andReleaseTimeEqualTo(selectDate);
            criteria1.andComeFromIsNotNull();
            int ZXFBNum = tkCommonTaskService.countByExample(tkCommonTaskExample1);
            map.put("allWGNum", third.size());//所有网格数量
            map.put("SBNum", SBNum);//上报数量
            map.put("WSBNum", third.size() - SBNum);//未上报数量
            map.put("ZXFBNum", ZXFBNum);//未上报数量


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "查询失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", map));
    }


    /**
     * 每日日常统计列表
     *
     * @return
     */
    @RequestMapping(value = "statisticsList", method = RequestMethod.GET)
    @ResponseBody
    public String statisticsList(String date, Integer isOver) {
        if (isOver == null) {
            isOver = 0;
        }
        //如果传进来的时间为空 就设置为今天的时间。
        Date selectDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATAFORMAT_STR);
        String now = sdf.format(new Date());
        if (StringUtils.isNotBlank(date)) {
            selectDate = DateUtil.getDate(date, DateUtil.DATAFORMAT_STR);
        } else {
            selectDate = DateUtil.getDate(now, DateUtil.DATAFORMAT_STR);
        }

        List<Map<String, Object>> mapList = new ArrayList<>();

        try {
            // 先取到某政府下有效的3级基础网格，再更具这个查到所有plan
            List<GridRegion> third = diyService.getThird();
            List<String> gridIds = new ArrayList<>();//所有三级网格code
            for (GridRegion bsWgxxb : third) {
                gridIds.add(bsWgxxb.getWgCode());
            }
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andWgCodeIn(gridIds);
            criteria.andReleaseTimeEqualTo(selectDate);
            List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
            Map<String, Object> map = null;
            for (GridRegion wgxxb : third) {
                map = new HashMap<>();
                map.put("wgName", wgxxb.getWgName());
                int num = 0;
                for (TkCommonTask tkCommonTask : tkCommonTasks) {
                    if (wgxxb.getWgCode().equals(tkCommonTask.getWgCode())) {
                        num++;
                    }
                }
                map.put("taskNum", num);
                if (num > 0) {
                    map.put("isOver", true);
                } else {
                    map.put("isOver", false);
                }
                boolean isOver1 = (boolean) map.get("isOver");
                if (isOver == 1) {//1 完成上报
                    if (isOver1) {
                        mapList.add(map);
                    }
                } else if (isOver == 2) {//2 未完成上报
                    if (!isOver1) {
                        mapList.add(map);
                    }
                } else {//所有
                    mapList.add(map);
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "查询失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", mapList));
    }


    /**
     * 通用接口  存储其他乡镇的任务
     *
     * @param tkList
     * @return
     */
    @RequestMapping(value = "generalTaskSave", method = RequestMethod.POST)
    @ResponseBody
    public String generalTaskSave(@RequestBody List<TkCommonTask> tkList) {

        try {
            for (int i = 0; i < tkList.size(); i++) {
                TkCommonTask tk = tkList.get(i);
                TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
                TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
                criteria.andFormIdEqualTo(tk.getFormId());
                List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
                if (tkCommonTasks != null && tkCommonTasks.size() > 0) {//数据库有数据
                    break;
                } else {//获取待办详情 并且插入数据库

                    TkCommonTask tkCommonTask = new TkCommonTask();
                    tkCommonTask.setId(UUID.randomUUID().toString());
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String releaseTime = sdf.format(new Date());
                        tkCommonTask.setReleaseTime(sdf.parse(releaseTime));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Date d = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    String dateNowStr = sdf.format(d);
                    tkCommonTask.setTkId(dateNowStr.substring(0, 15));
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                    String now = sdf2.format(new Date());
                    try {
                        tkCommonTask.setCreateTime(sdf2.parse(now));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    tkCommonTask.setTkStatus(10);
                    tkCommonTask.setStandby2("0");
                    tkCommonTask.setStandby1("0");
                    tkCommonTask.setQianshouorbohui(0);
                    tkCommonTask.setIsdelaytime(0);
                    tkCommonTask.setReleaseUserId(tk.getReleaseUserId());
                    tkCommonTask.setReleaseUserName(tk.getReleaseUserName());
                    tkCommonTask.setCreateBy(tkCommonTask.getReleaseUserId());
                    //以上是基础数据

                    //以下时详情接口获取的数据
                    tkCommonTask.setTkName(tk.getTitle());
                    tkCommonTask.setComplaintsPerson(tk.getCusName());
                    tkCommonTask.setComeFrom(3);
                    tkCommonTask.setLitigationType(1);//litigationType     诉讼类型 1求助、2投诉
                    tkCommonTask.setTkDetail(tk.getContentText());
                    DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                    tkCommonTask.setPlantime(format1.parse(tk.getPlanTimeString()));
                    tkCommonTask.setNum(tk.getBusiNumber());
                    tkCommonTask.setComplaintsPhone(tk.getCusPhone());
                    tkCommonTask.setHandleType(2);
                    tkCommonTask.setFormId(tk.getFormId());
                    tkCommonTask.setFormstatus(tk.getFormStatusName());

                    int insert = tkCommonTaskService.insert(tkCommonTask);
                }
            }
            return JSON.toJSONString(AjaxResult.build(200, "success", "插入成功"));

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "插入失败"));
        }

    }

    /**
     * 收集12345待办
     *
     * @param tkList
     * @return
     */
    @RequestMapping(value = "getUnFinishedTask", method = RequestMethod.POST)
    @ResponseBody
    public String getUnFinishedTask(@RequestBody List<TkCommonTask> tkList) {

        try {
            for (int i = 0; i < tkList.size(); i++) {
                TkCommonTask tk = tkList.get(i);
                TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
                TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
                criteria.andFormIdEqualTo(tk.getFormId());
                List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
                if (tkCommonTasks != null && tkCommonTasks.size() > 0) {//数据库有数据
                    break;
                } else {//获取待办详情 并且插入数据库

                    TkCommonTask tkCommonTask = new TkCommonTask();
                    tkCommonTask.setId(UUID.randomUUID().toString());
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String releaseTime = sdf.format(new Date());
                        tkCommonTask.setReleaseTime(sdf.parse(releaseTime));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Date d = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    String dateNowStr = sdf.format(d);
                    tkCommonTask.setTkId(dateNowStr.substring(0, 15));
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                    String now = sdf2.format(new Date());
                    try {
                        tkCommonTask.setCreateTime(sdf2.parse(now));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    tkCommonTask.setTkStatus(10);
                    tkCommonTask.setStandby2("0");
                    tkCommonTask.setStandby1("0");
                    tkCommonTask.setQianshouorbohui(0);
                    tkCommonTask.setIsdelaytime(0);
                    tkCommonTask.setReleaseUserId("480045d7-f880-4847-a32c-08b2b14967fc");
                    tkCommonTask.setReleaseUserName("金湖县塔集镇");
                    tkCommonTask.setCreateBy(tkCommonTask.getReleaseUserId());
                    //以上是基础数据

                    //以下时详情接口获取的数据
                    tkCommonTask.setTkName(tk.getTitle());
                    tkCommonTask.setComplaintsPerson(tk.getCusName());
                    tkCommonTask.setComeFrom(3);
                    tkCommonTask.setLitigationType(1);//litigationType     诉讼类型 1求助、2投诉
                    tkCommonTask.setTkDetail(tk.getContentText());
                    DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                    tkCommonTask.setPlantime(format1.parse(tk.getPlanTimeString()));
                    tkCommonTask.setNum(tk.getBusiNumber());
                    tkCommonTask.setComplaintsPhone(tk.getCusPhone());
                    tkCommonTask.setHandleType(2);
                    tkCommonTask.setFormId(tk.getFormId());
                    tkCommonTask.setFormstatus(tk.getFormStatusName());

                    int insert = tkCommonTaskService.insert(tkCommonTask);
                }
            }
            return JSON.toJSONString(AjaxResult.build(200, "success", "插入成功"));

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "插入失败"));
        }

    }


    /**
     * 返回12345待办
     *
     * @return
     */
    @RequestMapping(value = "back12345Task", method = RequestMethod.POST)
    @ResponseBody
    public String back12345Task() {

        try {
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andComeFromEqualTo(3);
            criteria.andFormIdIsNotNull();
            List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
            return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "内部服务器错误"));
        }

    }


    /**
     * 工单签收
     *
     * @param
     * @return
     */
    @RequestMapping(value = "receiveTask", method = RequestMethod.POST)
    @ResponseBody
    public String receiveTask(String id) {
        System.out.println("id---->" + id);
        try {
            TkCommonTask tk = tkCommonTaskService.selectByPrimaryKey(id);
            if (tk != null) {
                tk.setQianshouorbohui(1);
                String utl = "https://connect-data-taji.app.zqtong.com/api/v3_1busiformSign?formId=" + tk.getFormId();
                String ret = ZQTHttpHelper.doGet(utl);
                if (StringUtils.isNotBlank(ret)) {
                    JSONObject jsonObject = JSONObject.parseObject(ret);
                    boolean oK = (boolean) jsonObject.get("oK");
                    if (oK) {//调用成功
                        tkCommonTaskService.updateByPrimaryKey(tk);
                        String joData = (String) jsonObject.get("data");
                        return JSON.toJSONString(AjaxResult.build(200, "success", joData));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "签收失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "签收失败"));
    }


    /**
     * 工单驳回
     *
     * @param
     * @return
     */
    @RequestMapping(value = "backTask", method = RequestMethod.POST)
    @ResponseBody
    public String backTask(String id, String text) {

        try {
            TkCommonTask tk = tkCommonTaskService.selectByPrimaryKey(id);
            if (tk != null) {
                tk.setQianshouorbohui(2);
                tkCommonTaskService.updateByPrimaryKey(tk);
                String utl = "https://connect-data-taji.app.zqtong.com/api/v3_1busiformReject?formId=" + tk.getFormId() + "&advContentText=" + text;
                String ret = ZQTHttpHelper.doGet(utl);
                if (StringUtils.isNotBlank(ret)) {
                    JSONObject jsonObject = JSONObject.parseObject(ret);
                    boolean oK = (boolean) jsonObject.get("oK");
                    if (oK) {//调用成功
                        tkCommonTaskService.updateByPrimaryKey(tk);
                        String joData = (String) jsonObject.get("data");
                        return JSON.toJSONString(AjaxResult.build(200, "success", joData));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "驳回失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "驳回失败"));
    }


    /**
     * 工单办结
     *
     * @param id
     * @param text        办结说明
     * @param performType
     * @return
     */
    private void accomplishTask(String id, String text, int performType) {

        try {
            TkCommonTask tk = tkCommonTaskService.selectByPrimaryKey(id);
            if (tk != null) {
                String type = "反馈处理意见(含一次不满意)";
                String utl = "https://connect-data-taji.app.zqtong.com/api/v3_1busiformProcess?formId=" + tk.getFormId() + "&advContentText=" + text + "&doActionName" + type;
                String ret = ZQTHttpHelper.doGet(utl);
                if (StringUtils.isNotBlank(ret)) {
                    JSONObject jsonObject = JSONObject.parseObject(ret);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 延时申请
     *
     * @param id        任务id
     * @param text      延时说明
     * @param delayDays 延时日期
     * @param delayUnit 延时单位
     * @return
     */
    @RequestMapping(value = "delayTime", method = RequestMethod.POST)
    @ResponseBody
    public String delayTime(String id, String text, int delayDays, String delayUnit) {

        try {

            TkCommonTask tk = tkCommonTaskService.selectByPrimaryKey(id);
            if (tk != null) {
                tk.setIsdelaytime(1);
                tkCommonTaskService.updateByPrimaryKey(tk);

                String utl = "https://connect-data-taji.app.zqtong.com/api/v3_1busiformDelay?formId=" + tk.getFormId() + "&delayDays=" + delayDays + "&delayUnit=" + delayUnit + "&reason=" + text;
                String ret = ZQTHttpHelper.doGet(utl);
                if (StringUtils.isNotBlank(ret)) {
                    JSONObject jsonObject = JSONObject.parseObject(ret);
                    boolean oK = (boolean) jsonObject.get("oK");
                    if (oK) {//调用成功
                        tkCommonTaskService.updateByPrimaryKey(tk);
                        String joData = (String) jsonObject.get("data");
                        return JSON.toJSONString(AjaxResult.build(200, "success", joData));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "申请失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "申请失败"));
    }

    @RequestMapping(value = "taskStat", method = RequestMethod.GET)
    @ResponseBody
    public String taskStat(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam String year,
            @RequestParam String month,
            String day,
            String ParentWgCode) {

        String ymFlag = "1";
        List<TKGridRegion> list = new ArrayList<>();
        ZQTPageModel result = new ZQTPageModel();

        Date firstDate = null;
        Date lastDate = null;
        if (StringUtils.isNotBlank(day)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            StringBuilder sb = new StringBuilder();
            sb.append(year).append("-").append(month.length() == 1 ? "0" + month : month).append("-").append(day.length() == 1 ? "0" + day : day);
            try {
                firstDate = format.parse(sb.toString() + " 00:00:00");
                lastDate = format.parse(sb.toString() + " 23:59:59");
                ymFlag = "2";
            } catch (ParseException e) {
                e.printStackTrace();
            }

        } else {
            Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
            firstDate = dateMap.get("firstDate");
            lastDate = dateMap.get("lastDate");
        }


        try {

            SysRole sysRole = new SysRole();
            sysRole.setRoleKey("threegird");
            sysRole.setStatus("0");
            List<SysRole> roles = sysRoleService.selectRoleList(sysRole);
            List<Long> roleIds = new ArrayList<>();
            for (SysRole role : roles) {
                roleIds.add(role.getRoleId());
            }
            List<SysUserRole> roleUsers = sysUserRoleMapper.listByRoleIds(roleIds);
            List<String> roleUserIds = new ArrayList<>();
            for (SysUserRole user : roleUsers) {
                roleUserIds.add(user.getUserId());
            }

            TKGridRegionExample xxbExample = new TKGridRegionExample();
            xxbExample.setWgCode(ParentWgCode);
            xxbExample.setUserIds(roleUserIds);
            List<GridRegion> allGridRegions = extendGridRegionMapper.selectThirdWgByBaseId(xxbExample);

            xxbExample.setStartLimit((pageNum - 1) * pageSize);
            xxbExample.setEndLimit(pageSize);

            List<GridRegion> bsWgxxbs = extendGridRegionMapper.selectThirdWgByBaseId(xxbExample);

            long count = extendGridRegionMapper.countThirdWgByBaseId(xxbExample);

            List<String> gridIds = new ArrayList<>();//所有三级网格code
            List<String> allGridIds = new ArrayList<>();
            Set<String> parentIds = new HashSet<>();
            for (GridRegion bsWgxxb : bsWgxxbs) {
                gridIds.add(bsWgxxb.getWgCode());
                parentIds.add(bsWgxxb.getWgParentId());
            }

            for (GridRegion bsWgxxb : allGridRegions) {
                allGridIds.add(bsWgxxb.getWgCode());
            }

            if (CollectionUtils.isEmpty(gridIds)) {
                return JSON.toJSONString(AjaxResult.build(200, "success", "查询无数据"));
            }

            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andWgCodeIn(new ArrayList<>(parentIds));

            List<GridRegion> parentWgs = bsWgxxbService.selectByExample(example);

            Map<String, String> parentMap = new HashMap<>();
            for (GridRegion xxb : parentWgs) {
                parentMap.put(xxb.getWgCode(), xxb.getWgName());
            }

            Map<String, Object> para = new HashMap<String, Object>();
            para.put("gridIds", gridIds);
            para.put("startDate", firstDate);
            para.put("ymFlag", ymFlag);
            List<TkCommonTask> tkCommonTasks = tkCommonTaskExtMapper.thirdWgTaskList(para);


            para.put("gridIds", allGridIds);
            long allCount = tkCommonTaskExtMapper.countThirdWgTaskList(para);

            Map<String, Integer> taskAllMap = new HashMap<>();
            Map<String, Integer> taskResolveMap = new HashMap<>();
            Map<String, Integer> taskActiveMap = new HashMap<>();
            for (TkCommonTask task : tkCommonTasks) {
                if (!taskAllMap.containsKey(task.getWgCode())) {
                    taskAllMap.put(task.getWgCode(), 1);
                } else {
                    taskAllMap.put(task.getWgCode(), taskAllMap.get(task.getWgCode()) + 1);
                }

                if (null != task.getTkStatus() && task.getTkStatus() == 50) {
                    if (!taskResolveMap.containsKey(task.getWgCode())) {
                        taskResolveMap.put(task.getWgCode(), 1);
                    } else {
                        taskResolveMap.put(task.getWgCode(), taskResolveMap.get(task.getWgCode()) + 1);
                    }
                }

                if (null == task.getIsYouxiao() || 0 == task.getIsYouxiao()) {
                    if (!taskActiveMap.containsKey(task.getWgCode())) {
                        taskActiveMap.put(task.getWgCode(), 1);
                    } else {
                        taskActiveMap.put(task.getWgCode(), taskActiveMap.get(task.getWgCode()) + 1);
                    }
                }
            }


            Map<String, Integer> roundMap = new HashMap<>();
            TkRoundSubtaskExample subtaskExample = new TkRoundSubtaskExample();
            TkRoundSubtaskExample.Criteria criteria1 = subtaskExample.createCriteria();
            criteria1.andGridIdIn(gridIds);
            List<TkRoundSubtask> subtasks = tkRoundSubtaskService.selectByExample(subtaskExample);
            List<String> taskIds = new ArrayList<>();

            Map<String, String> wgRoundsubMap = new HashMap<>();
            Map<String, String> wgRoundTaskMap = new HashMap<>();
            Map<String, String> wgRoundPlanMap = new HashMap<>();
            if (subtasks != null && subtasks.size() > 0) {
                for (TkRoundSubtask subtask : subtasks) {
                    taskIds.add(subtask.getTaskId());
                    wgRoundsubMap.put(subtask.getTaskId(), subtask.getGridId());
                }

                TkRoundTaskExample taskExample = new TkRoundTaskExample();
                TkRoundTaskExample.Criteria criteria2 = taskExample.createCriteria();
                criteria2.andIdIn(taskIds);
                List<TkRoundTask> tasks = tkRoundTaskService.selectByExample(taskExample);
                List<String> planIds = new ArrayList<>();
                if (tasks != null && tasks.size() > 0) {
                    for (TkRoundTask task : tasks) {
                        planIds.add(task.getRoundPlanId());
                        if (wgRoundsubMap.containsKey(task.getId())) {
                            wgRoundTaskMap.put(task.getRoundPlanId(), wgRoundsubMap.get(task.getId()));
                        }
                    }

                    TkRoundPlanExample examplet = new TkRoundPlanExample();
                    TkRoundPlanExample.Criteria criterias = examplet.createCriteria();
                    criterias.andPeriodTypeEqualTo("4");
                    criterias.andIdIn(planIds);
                    criterias.andEndDateBetween(firstDate, lastDate);

                    List<TkRoundPlan> tkRoundPlanList = tkRoundPlanService.selectByExample(examplet);

                    if (tkRoundPlanList != null && tkRoundPlanList.size() > 0) {
                        for (TkRoundPlan tkRoundPlan : tkRoundPlanList) {
                            String wgCode = wgRoundTaskMap.get(tkRoundPlan.getId());
                            if (roundMap.get(wgCode) == null) {
                                roundMap.put(wgCode, 1);
                            } else {
                                roundMap.put(wgCode, Integer.parseInt(roundMap.get(wgCode).toString()) + 1);
                            }
                        }
                    }
                }
            }

            for (GridRegion bsWgxxb : bsWgxxbs) {
                TKGridRegion wgxxb = new TKGridRegion();
                String wgCode = bsWgxxb.getWgCode();
                String wgName = bsWgxxb.getWgName();
                wgxxb.setCunSheQu(parentMap.get(bsWgxxb.getWgParentId()));
                wgxxb.setWgMaster(wgName);
                wgxxb.setName(bsWgxxb.getYlzd1());
                wgxxb.setReportNum(taskAllMap.get(wgCode));
                wgxxb.setDoneNum(taskResolveMap.get(wgCode));
                wgxxb.setRoundNum(roundMap.get(wgCode));
                wgxxb.setActiveNum(taskActiveMap.get(wgCode));
                list.add(wgxxb);
            }

            //分页
            result.setItemList(list);
            //总记录数
            result.setRecordCount(count);
            //总页数
            result.setPageCount((count + pageSize - 1) / pageSize);
            //当前页
            result.setCurPage(count == 0 ? 0 : pageNum);

            result.setAllReportCount((int) allCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }

    @RequestMapping(value = "SecWgTaskStat", method = RequestMethod.GET)
    @ResponseBody
    public String SecWgTaskStat(
            @RequestParam String year,
            @RequestParam String month) {


        Map<String, TKGridRegion> wgMap = new HashMap<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDate = dateMap.get("firstDate");
        List<TKGridRegion> result = new ArrayList<>();

        try {
            TKGridRegionExample xxbExample = new TKGridRegionExample();
            xxbExample.setStartDate(firstDate);
            List<TKGridRegion> allGridRegions = extendGridRegionMapper.selectSecWgTaskStat(xxbExample);

            for (TKGridRegion xxb : allGridRegions) {
                if (null == xxb.getSumCount()) {
                    xxb.setSumCount(0);
                }
                if (null == xxb.getDoneCount()) {
                    xxb.setDoneCount(0);
                }
                if (wgMap.containsKey(xxb.getWgName())) {
                    TKGridRegion xxbTemp = wgMap.get(xxb.getWgName());
                    xxbTemp.setSumCount(xxbTemp.getSumCount() + xxb.getSumCount());
                    xxbTemp.setDoneCount(xxbTemp.getDoneCount() + xxb.getDoneCount());
                } else {
                    wgMap.put(xxb.getWgName(), xxb);
                }
            }

            if (!CollectionUtils.isEmpty(wgMap.values())) {
                List<TKGridRegion> xxbs = new ArrayList<>(wgMap.values());
                result = xxbs.stream().sorted(new Comparator<TKGridRegion>() {
                    @Override
                    public int compare(TKGridRegion o1, TKGridRegion o2) {
                        return o2.getSumCount() - o1.getSumCount();
                    }
                }).collect(Collectors.toList());
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));

    }


    /**
     * 网格事项类别的饼图 奔牛
     *
     * @param wgCode
     * @return
     */
    @RequestMapping(value = "groupMatter", method = RequestMethod.GET)
    @ResponseBody
    public String groupMatter(@RequestParam String wgCode) {

        //查询网格的等级
        GridRegionExample bsWgxxbExample = new GridRegionExample();
        bsWgxxbExample.createCriteria().andWgCodeEqualTo(wgCode);
        List<GridRegion> bsWgxxbs = bsWgxxbService.selectByExample(bsWgxxbExample);
        String level = bsWgxxbs.get(0).getLevel();

        List<Map<String, Object>> tkList = new ArrayList<>();
        try {
            Map<String, Object> map = new HashedMap();

            if (level.equals("2")) {
                //如果查询2级网格的数量，那么任务表就得查wg_parent_code=code
                map.put("wgParentCode", wgCode + "%");
            } else {
                //如果查询3级网格的数量，那么任务就得查wg_code=code
                map.put("wgCode", wgCode);
            }
            tkList = tkCommonTaskExtMapper.groupMatter(map);


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", ""));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", tkList));

    }


    @RequestMapping(value = "matterStat", method = RequestMethod.GET)
    @ResponseBody
    public String matterStat(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam String year,
            @RequestParam String month) {

        ZQTPageModel result = new ZQTPageModel();
        List<TKGridRegion> lists = new ArrayList<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDay = dateMap.get("firstDate");

        try {

            TKGridRegionExample exampleTemp = new TKGridRegionExample();
            exampleTemp.setStartLimit((pageNum - 1) * pageSize);
            exampleTemp.setEndLimit(pageSize);
            exampleTemp.setStartDate(firstDay);

            long count = extendGridRegionMapper.countMatterId(exampleTemp);
            long allCount = extendGridRegionMapper.countAllMatterStat(exampleTemp);

            lists = extendGridRegionMapper.selectMatterStat(exampleTemp);

            for (TKGridRegion xxb : lists) {
                if (null != xxb.getAvgTime()) {
                    xxb.setAvgTime(xxb.getAvgTime() / 3600);
                }
                if (null != xxb.getMaxTime()) {
                    xxb.setMaxTime(xxb.getMaxTime() / 3600);
                }
                if (null != xxb.getMinTime()) {
                    xxb.setMinTime(xxb.getMinTime() / 3600);
                }
            }

            //分页
            result.setItemList(lists);
            //总记录数
            result.setRecordCount(count);
            //总页数
            result.setPageCount((count + pageSize - 1) / pageSize);
            //当前页
            result.setCurPage(count == 0 ? 0 : pageNum);

            result.setAllReportCount((int) allCount);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }

    @RequestMapping(value = "matterDetailStat", method = RequestMethod.GET)
    @ResponseBody
    public String matterDetailStat(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam String year,
            @RequestParam String month,
            @RequestParam String matterId) {

        ZQTPageModel result = new ZQTPageModel();
        List<TKGridRegion> lists = new ArrayList<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDay = dateMap.get("firstDate");

        try {

            TKGridRegionExample exampleTemp = new TKGridRegionExample();
            exampleTemp.setStartLimit((pageNum - 1) * pageSize);
            exampleTemp.setEndLimit(pageSize);
            exampleTemp.setStartDate(firstDay);
            exampleTemp.setMatterId(matterId);
            lists = extendGridRegionMapper.selectMatterDetailStat(exampleTemp);

            long count = extendGridRegionMapper.countMatterDetailStat(exampleTemp);

            long allCount = extendGridRegionMapper.countAllMatterDetail(exampleTemp);

            //分页
            result.setItemList(lists);
            //总记录数
            result.setRecordCount(count);
            //总页数
            result.setPageCount((count + pageSize - 1) / pageSize);
            //当前页
            result.setCurPage(count == 0 ? 0 : pageNum);

            result.setAllReportCount((int) allCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }

    @RequestMapping(value = "comefrom3", method = RequestMethod.GET)
    @ResponseBody
    public String comeForm3(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam String year,
            @RequestParam String month) {

        ZQTPageModel result = new ZQTPageModel();
        List<TkCommonTask> lists = new ArrayList<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDay = dateMap.get("firstDate");
        Date lastDate = dateMap.get("lastDate");

        try {

            TKGridRegionExample exampleTemp = new TKGridRegionExample();
            exampleTemp.setStartLimit((pageNum - 1) * pageSize);
            exampleTemp.setEndLimit(pageSize);
            exampleTemp.setStartDate(firstDay);
            lists = extendGridRegionMapper.selectComeFrom3(exampleTemp);

            long count = extendGridRegionMapper.countComeFrom3(exampleTemp);

            Map<String, String> deptMap = new HashMap<>();
            for (TkCommonTask task : lists) {
                if (StringUtils.isNotBlank(task.getPerformUserId())) {
                    SysUser userDept = sysUserService.selectUserById(task.getPerformUserId());
                    deptMap.put(task.getPerformUserId(), userDept.getDept().getDeptName());
                }
            }

            List<BsCommon> listTemp = new ArrayList<>();

            Map<String, String> guiShuMap = new HashMap<>();
            AjaxResult resultTemp = new AjaxResult();
            List<BsCommon> wgdxList = flpzService.getWgNameList(1, 100, "12345", resultTemp);
            ZQTPageModel<BsCommon> appPageModel = (ZQTPageModel<BsCommon>) resultTemp.get("data");
            if (!CollectionUtils.isEmpty(appPageModel.getItemList())) {
                for (BsCommon bsCommon : appPageModel.getItemList()) {
                    guiShuMap.put(bsCommon.getId(), bsCommon.getName());
                }
            }

            for (TkCommonTask tkCommonTask : lists) {

                if (StringUtils.isNotBlank(tkCommonTask.getGuishuCode()) && guiShuMap.containsKey(tkCommonTask.getGuishuCode())) {
                    tkCommonTask.setMatterName(guiShuMap.get(tkCommonTask.getGuishuCode()));
                }

                if (deptMap.containsKey(tkCommonTask.getPerformUserId())) {
                    tkCommonTask.setStandby3(deptMap.get(tkCommonTask.getPerformUserId()));
                }
                if (tkCommonTask.getTkStatus() > 40) {
                    tkCommonTask.setZt("已完成");
                } else if (tkCommonTask.getTkStatus() == 40) {
                    tkCommonTask.setZt("待评价");
                } else if (tkCommonTask.getTkStatus() >= 30 && tkCommonTask.getTkStatus() < 40) {
                    tkCommonTask.setZt("待核查");
                } else if (tkCommonTask.getTkStatus() >= 20 && tkCommonTask.getTkStatus() < 30) {
                    tkCommonTask.setZt("处理中");
                } else if (tkCommonTask.getTkStatus() > 10 && tkCommonTask.getTkStatus() < 20 && tkCommonTask.getTkStatus() != 16) {
                    tkCommonTask.setZt("待处理");
                } else if (tkCommonTask.getTkStatus() == 10 || tkCommonTask.getTkStatus() == 10) {
                    tkCommonTask.setZt("待指派");
                } else if (tkCommonTask.getTkStatus() == 32) {
                    tkCommonTask.setZt("待延时");
                }
            }
            //分页
            result.setItemList(lists);
            //总记录数
            result.setRecordCount(count);
            //总页数
            result.setPageCount((count + pageSize - 1) / pageSize);
            //当前页
            result.setCurPage(count == 0 ? 0 : pageNum);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }

    @RequestMapping(value = "countcomefrom3", method = RequestMethod.GET)
    @ResponseBody
    public String comeForm3(
            @RequestParam Integer year,
            @RequestParam Integer month,
            @RequestParam Integer day) {

        Map<String, Object> result = new HashMap<>();

        try {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month - 1);
            calendar.set(Calendar.DAY_OF_MONTH, day);

            Map<String, Object> para = new HashMap<String, Object>();
            para.put("comeFrom", "3");
            para.put("startDate", calendar.getTime());
            long dayCount = tkCommonTaskExtMapper.countComeFromThirdTask(para);

            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteriat = tkCommonTaskExample.createCriteria();
            criteriat.andComeFromEqualTo(3);
            int allCount = tkCommonTaskService.countByExample(tkCommonTaskExample);

            result.put("dayCount", dayCount);
            result.put("allCount", allCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }

    @RequestMapping(value = "deptStat", method = RequestMethod.GET)
    @ResponseBody
    public String deptStat(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            String type,
            String year,
            String month,
            String day) {
        ZQTPageModel result = new ZQTPageModel();
        List<TkCommonTask> lists = new ArrayList<>();

        try {

            TKGridRegionExample example = new TKGridRegionExample();
            example.setType(type);

            if (StringUtils.isNotBlank(year) && StringUtils.isNotBlank(month) && StringUtils.isNotBlank(day)) {
                month = month.length() == 1 ? "0" + month : month;
                day = day.length() == 1 ? "0" + day : day;
                example.setYearMonthDay(year + "-" + month + "-" + day);
            }

            if (StringUtils.isNotBlank(year) && StringUtils.isNotBlank(month)) {
                month = month.length() == 1 ? "0" + month : month;
                example.setYearMonth(year + "-" + month);
            }

            List<TKGridRegion> userTasks = extendGridRegionMapper.selectDeptStat(example);

            CountDownLatch latch = new CountDownLatch(userTasks.size());

            for (TKGridRegion xxb : userTasks) {
                threadPool.execute(new taskThread(latch, xxb));
            }

            latch.await();

            Map<String, TKGridRegion> resultMap = new HashMap<>();
            for (TKGridRegion xxb : userTasks) {
                if (!resultMap.containsKey(xxb.getName())) {
                    TKGridRegion tempxxb = new TKGridRegion();
                    BeanUtils.copyProperties(xxb, tempxxb);
                    resultMap.put(xxb.getName(), tempxxb);
                } else {
                    TKGridRegion tempxxb = resultMap.get(xxb.getName());
                    tempxxb.setReportNum(tempxxb.getReportNum() + xxb.getReportNum());
                    tempxxb.setDoneNum(tempxxb.getDoneNum() + xxb.getDoneNum());
                }
            }

            resultMap.remove(null);

            List<TKGridRegion> resultList = new ArrayList<>();
            List<TKGridRegion> resultListTemp = new ArrayList<>();
            List<TKGridRegion> resultListTemp2 = new ArrayList<>();
            resultListTemp = new ArrayList<>(resultMap.values());
            resultList = resultListTemp.stream().sorted(new Comparator<TKGridRegion>() {
                @Override
                public int compare(TKGridRegion o1, TKGridRegion o2) {
                    return o2.getReportNum() - o1.getReportNum();
                }
            }).collect(Collectors.toList());

            int allCount = 0;
            for (TKGridRegion xxb : resultList) {
                allCount = allCount + xxb.getReportNum();
            }

            //总页数
            result.setPageCount((resultMap.size() + pageSize - 1) / pageSize);

            if (pageNum >= result.getPageCount()) {
                resultListTemp2 = resultList.subList((pageNum - 1) * pageSize, resultMap.size());
            } else {
                resultListTemp2 = resultList.subList((pageNum - 1) * pageSize, pageNum * pageSize);
            }


            DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
            //可以设置精确几位小数
            df.setMaximumFractionDigits(2);
            //模式 例如四舍五入
            df.setRoundingMode(RoundingMode.HALF_UP);

            for (TKGridRegion xxb : resultListTemp2) {
                double done = xxb.getDoneNum();
                double all = xxb.getReportNum();
                double rate = done / all * 100;
                xxb.setDonePercent(df.format(rate));
            }
            //分页
            result.setItemList(resultListTemp2);
            //总记录数
            result.setRecordCount(resultMap.size());

            //当前页
            result.setCurPage(resultMap.size() == 0 ? 0 : pageNum);

            result.setAllReportCount(allCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }


    //微信小程序获取用户唯一标识
    //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
    @RequestMapping(value = "wx/getUser", method = RequestMethod.GET)
    @ResponseBody
    public String wxGetUser(
            @RequestParam String code) {
        if (StringUtils.isBlank(code)) {
            return JSON.toJSONString(AjaxResult.build(500, "fail", "code必填"));
        }
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + dyAppId + "&secret=" + dyAppSecret + "&js_code=" + code + "&grant_type=authorization_code";
            String s = ZQTHttpHelper.doGet(url);
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (jsonObject != null) {
                System.out.println("接口返回" + s);
                return JSON.toJSONString(AjaxResult.build(200, "success", jsonObject));
            } else {
                return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
            }


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }

    }


    @RequestMapping(value = "wx/getWebUser", method = RequestMethod.GET)
    @ResponseBody
    public String getWebUser(
            @RequestParam String code) {
        if (StringUtils.isBlank(code)) {
            return JSON.toJSONString(AjaxResult.build(500, "fail", "code必填"));
        }
        String token = redisRepository.get("wx:webAccessToken");
        if (token != null) {
            return JSON.toJSONString(AjaxResult.build(200, "success", JSONObject.parseObject(token)));
        }
        try {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + dyAppId + "&secret=" + dyAppSecret + "&code=" + code + "&grant_type=authorization_code";
            String s = ZQTHttpHelper.doGet(url);
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (jsonObject != null) {
                System.out.println("接口返回" + s);
                redisRepository.save("wx:webAccessToken", s, 7200);
                return JSON.toJSONString(AjaxResult.build(200, "success", jsonObject));
            } else {
                return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
            }


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }

    }


    @RequestMapping(value = "wx/getWxTick", method = RequestMethod.GET)
    @ResponseBody
    public String getWxTick(String url) {
        try {
            JSONObject jsonObject = null;
            String accessToken = WxUtil.getCommonAccessToken(dyAppId, dyAppSecret);
            String ticket = WxUtil.getJsTicket(accessToken);
            jsonObject = new JSONObject();
            if (StringUtils.isNotBlank(accessToken) && StringUtils.isNotBlank(ticket)) {
                jsonObject.put("accessToken", accessToken);
                jsonObject.put("ticket", ticket);
                jsonObject.put("sign", WxUtil.sign(ticket, url));
            }
            return JSON.toJSONString(AjaxResult.build(200, "success", jsonObject));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }

    }


    class taskThread implements Runnable {

        private CountDownLatch latch;
        private TKGridRegion xxb;

        public taskThread(CountDownLatch latch, TKGridRegion xxb) {
            this.latch = latch;
            this.xxb = xxb;
        }

        @Override
        public void run() {
            try {
                SysUser sysUser = sysUserService.selectUserById(xxb.getPerformUserId());
                xxb.setName(sysUser.getDept().getDeptName());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //当前计算工作已结束，计数器减一
                latch.countDown();
            }
        }
    }

    @RequestMapping(value = "taskCountByComeFrom", method = RequestMethod.GET)
    @ResponseBody
    public String taskCount() {
        LOGGER.info("taskCountByComeFrom 入口");
        List<Map<String, Object>> tkCommonTasks = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> data = new HashedMap();
            tkCommonTasks = tkCommonTaskService.taskCountByBaseId(data);
            //综治数据
            int zzCount = 0;
            LOGGER.info("taskCountByComeFrom 综治查询 " + zzCount);

            Map<String, Object> zongzhi = new HashMap<>();
            zongzhi.put("comeFrom2", "综治工单");
            zongzhi.put("comeTaskNum", zzCount);
            tkCommonTasks.add(zongzhi);
            LOGGER.info("taskCountByComeFrom 结果 " + tkCommonTasks);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));
    }

    @RequestMapping(value = "ComeFromThirdTaskStat", method = RequestMethod.GET)
    @ResponseBody
    public String ComeFromThirdTaskStat(String year,
                                        String month) {

        Date firstDay = null;
        Map resultMap = new HashMap();
        if (StringUtils.isNotBlank(year) && StringUtils.isNotBlank(month)) {
            Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
            firstDay = dateMap.get("firstDate");
        }

        try {
            Map<String, Object> para = new HashMap<String, Object>();
            para.put("comeFrom", "3");
            para.put("startDate", firstDay);
            List<TkCommonTask> result = tkCommonTaskExtMapper.ComeFromThirdTaskStat(para);

            List<BsCommon> listTemp = new ArrayList<>();

            Map<String, String> guiShuMap = new HashMap<>();
            AjaxResult resultTemp = new AjaxResult();
            ZQTPageModel<BsCommon> appPageModel = (ZQTPageModel<BsCommon>) resultTemp.get("data");
            if (!CollectionUtils.isEmpty(appPageModel.getItemList())) {
                for (BsCommon bsCommon : appPageModel.getItemList()) {
                    guiShuMap.put(bsCommon.getId(), bsCommon.getName());
                }
            }

            for (TkCommonTask tkCommonTask : result) {
                //0建设 1商务 2社事 3环保 4水利 5组织人事 6行政村',
                if (StringUtils.isNotBlank(tkCommonTask.getGuishuCode())) {
                    resultMap.put("", tkCommonTask.getNum());
                } else {
                    if (StringUtils.isNotBlank(tkCommonTask.getGuishuCode()) && guiShuMap.containsKey(tkCommonTask.getGuishuCode())) {
                        resultMap.put(guiShuMap.get(tkCommonTask.getGuishuCode()), tkCommonTask.getNum());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", resultMap));
    }

    @RequestMapping(value = "matterTask", method = RequestMethod.GET)
    @ResponseBody
    public String matterTask(String wgCode,
                             String startTime,
                             String endTime,
                             String year,
                             String month) {

        Date firstDay = null;
        Map resultMap = new HashMap();
        DecimalFormat df = new DecimalFormat("######0.00");
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        firstDay = dateMap.get("firstDate");
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        try {
            Map<String, Object> para = new HashMap<String, Object>();
            if (StringUtils.isNotEmpty(year) && StringUtils.isNotEmpty(month)) para.put("startDate", firstDay);
            para.put("wgCode", wgCode);
            if (StringUtils.isNotEmpty(startTime)) para.put("startTime", startTime);
            if (StringUtils.isNotEmpty(endTime)) para.put("endTime", endTime);
            List<TkCommonTask> result = tkCommonTaskExtMapper.matterTask(para);

            List<Map<String, Object>> allMatter = bsRcsxService.getFirstDwRcsxList();
            List<String> firstMatter = new ArrayList<>();

            for (Map<String, Object> mapTemp : allMatter) {
                List<Map<String, Object>> mapTempNet = (List<Map<String, Object>>) mapTemp.get("children");
                for (Map<String, Object> mapStr : mapTempNet) {
                    //二级事项
                    firstMatter.add(String.valueOf(mapStr.get("sxmc")));
                }
            }

            for (int i = 0; i < firstMatter.size(); i++) {
                Map<String, String> map = new HashMap<String, String>();
                if (result.isEmpty()) {
                    map.put("name", firstMatter.get(i));
                    map.put("value", "0");
                } else {
                    for (TkCommonTask tkCommonTask : result) {
                        if (tkCommonTask.getMatterName().equals(firstMatter.get(i))) {
                            map.put("name", firstMatter.get(i));
                            map.put("value", tkCommonTask.getNum());
                            break;
                        } else {
                            map.put("name", firstMatter.get(i));
                            map.put("value", "0");
                        }
                    }
                }

                list.add(map);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }

    @RequestMapping(value = "MatterTaskComeFrom3", method = RequestMethod.GET)
    @ResponseBody
    public String MatterTaskComeFrom3(String year,
                                      String month) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Date firstDay = null;
        Map resultMap = new HashMap();
        DecimalFormat df = new DecimalFormat("######0.00");
        if (StringUtils.isNotBlank(year) && StringUtils.isNotBlank(month)) {
            Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
            firstDay = dateMap.get("firstDate");
        }

        try {
            Map<String, Object> para = new HashMap<String, Object>();
            para.put("comeFrom", "3");
            para.put("startDate", firstDay);
            List<TkCommonTask> result = tkCommonTaskExtMapper.ComeFromThirdTaskStat(para);

            List<BsCommon> listTemp = new ArrayList<>();

            AjaxResult resultTemp = new AjaxResult();
            ZQTPageModel<BsCommon> appPageModel = (ZQTPageModel<BsCommon>) resultTemp.get("data");
            if (!CollectionUtils.isEmpty(appPageModel.getItemList())) {
                listTemp = appPageModel.getItemList();
            }
            for (BsCommon bsCommon : listTemp) {
                Map<String, String> map = new HashMap<String, String>();
                if (result.isEmpty()) {
                    map.put("name", bsCommon.getName());
                    map.put("value", "0");
                } else {
                    for (TkCommonTask tkCommonTask : result) {
                        //0建设 1商务 2社事 3环保 4水利 5组织人事 6行政村',
                        if (String.valueOf(tkCommonTask.getGuishuCode()).equals(bsCommon.getId())) {
                            map.put("name", bsCommon.getName());
                            map.put("value", tkCommonTask.getNum());
                            break;
                        } else {
                            map.put("name", bsCommon.getName());
                            map.put("value", "0");
                        }
                    }
                }

                list.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }


    private String getWgName(String planId) {
        TkRoundTaskExample example = new TkRoundTaskExample();
        TkRoundTaskExample.Criteria criteria = example.createCriteria();
        criteria.andRoundPlanIdEqualTo(planId);
        List<TkRoundTask> tkRoundTasks = tkRoundTaskService.selectByExample(example);
        TkRoundMatterExample matterExample = new TkRoundMatterExample();
        TkRoundMatterExample.Criteria criteria1 = matterExample.createCriteria();
        criteria1.andSubTaskIdEqualTo(tkRoundTasks.get(0).getId());
        List<TkRoundMatter> tkRoundMatters = tkRoundMatterService.selectByExample(matterExample);
        return tkRoundMatters.get(0).getStandby3();
    }

    private Map<String, Date> getMonthFirstAndLastDay(String year, String month) {
        Date firstDate = null;
        Date lastDate = null;
        Calendar cal_1 = Calendar.getInstance();
        Calendar cal_2 = Calendar.getInstance();
        if (StringUtils.isBlank(year) && StringUtils.isBlank(month)) {
            cal_1.set(Calendar.DAY_OF_MONTH, 1);

            cal_2.set(Calendar.DAY_OF_MONTH, cal_1.getActualMaximum(Calendar.DAY_OF_MONTH));

        } else if (!StringUtils.isBlank(year) && StringUtils.isBlank(month)) {
            cal_1.set(Calendar.YEAR, Integer.valueOf(year));//设置年
            cal_1.set(Calendar.DAY_OF_YEAR, cal_1.getActualMinimum(Calendar.DAY_OF_YEAR));

            cal_2.set(Calendar.YEAR, Integer.valueOf(year));//设置年
            cal_2.set(Calendar.DAY_OF_YEAR, cal_1.getActualMaximum(Calendar.DAY_OF_YEAR));
        } else {
            cal_1.set(Calendar.YEAR, Integer.valueOf(year));//设置年
            cal_1.set(Calendar.MONTH, Integer.valueOf(month) - 1);//设置月，月设置要-1
            cal_1.set(Calendar.DAY_OF_MONTH, 1);

            cal_2.set(Calendar.YEAR, Integer.valueOf(year));//设置年
            cal_2.set(Calendar.MONTH, Integer.valueOf(month) - 1);//设置月，月设置要-1
            cal_2.set(Calendar.DAY_OF_MONTH, cal_2.getActualMaximum(Calendar.DAY_OF_MONTH));
        }

        cal_1.set(Calendar.MINUTE, 0);
        cal_1.set(Calendar.SECOND, 0);
        cal_1.set(Calendar.HOUR_OF_DAY, 0);
        firstDate = cal_1.getTime();

        cal_2.set(Calendar.MINUTE, 59);
        cal_2.set(Calendar.SECOND, 59);
        cal_2.set(Calendar.HOUR_OF_DAY, 23);
        lastDate = cal_2.getTime();

        Map<String, Date> dateMap = new HashMap<>();
        dateMap.put("firstDate", firstDate);
        dateMap.put("lastDate", lastDate);
        return dateMap;
    }


    @RequestMapping(value = "/sxList/sxListExportInfo", method = RequestMethod.GET)
    @ResponseBody
    public String sxListExportInfo(HttpServletResponse response, @RequestParam String year, @RequestParam String month) throws IOException {
        int pageNum = 1;
        int pageSize = 9999;
        try {
            ZQTPageModel result = new ZQTPageModel();
            List<TKGridRegion> lists = new ArrayList<>();
            Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
            Date firstDay = dateMap.get("firstDate");

            TKGridRegionExample exampleTemp = new TKGridRegionExample();
            exampleTemp.setStartLimit((pageNum - 1) * pageSize);
            exampleTemp.setEndLimit(pageSize);
            exampleTemp.setStartDate(firstDay);
            List<TKGridRegion> wgxxbs = extendGridRegionMapper.selectMatterId(exampleTemp);

            long count = extendGridRegionMapper.countMatterId(exampleTemp);

            Map<String, String> matterIds = new HashMap<>();
            for (TKGridRegion xxb : wgxxbs) {
                matterIds.put(xxb.getMatterId(), xxb.getId());
            }

            if (CollectionUtils.isEmpty(matterIds.keySet())) {
                return JSON.toJSONString(AjaxResult.build(200, "success", "无数据"));
            }

            exampleTemp.setMatterIds(new ArrayList<>(matterIds.keySet()));
            lists = extendGridRegionMapper.selectMatterStat(exampleTemp);

            for (TKGridRegion xxb : lists) {
                if (matterIds.containsKey(xxb.getMatterId())) {
                    xxb.setId(matterIds.get(xxb.getMatterId()));
                }
                if (null != xxb.getActiveNum()) {
                    xxb.setAvgTime(xxb.getAvgTime() / 3600);
                }
                if (null != xxb.getMaxTime()) {
                    xxb.setMaxTime(xxb.getMaxTime() / 3600);
                }
                if (null != xxb.getMinTime()) {
                    xxb.setMinTime(xxb.getMinTime() / 3600);
                }
            }

            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建一个Excel表单,参数为sheet的名字
            HSSFSheet sheet = workbook.createSheet("事项列表");
            //创建表头
            HSSFRow row = sheet.createRow(0);
            //设置为居中加粗
            HSSFCellStyle style = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            style.setFont(font);
            style.setAlignment(HorizontalAlignment.CENTER);

            HSSFCell cell;
            cell = row.createCell(0);
            cell.setCellValue("序号");
            cell.setCellStyle(style);

            cell = row.createCell(1);
            cell.setCellValue("事项类型");
            cell.setCellStyle(style);

            cell = row.createCell(2);
            cell.setCellValue("上报数量");
            cell.setCellStyle(style);


            cell = row.createCell(3);
            cell.setCellValue("完成数量");
            cell.setCellStyle(style);

            cell = row.createCell(4);
            cell.setCellValue("最长处置时间");
            cell.setCellStyle(style);

            cell = row.createCell(5);
            cell.setCellValue("最短处置时间");
            cell.setCellStyle(style);

            cell = row.createCell(6);
            cell.setCellValue("平均值");
            cell.setCellStyle(style);

            //新增数据行，并且设置单元格数据
            int rowNum = 1;
            for (TKGridRegion xxb : lists) {
                row = sheet.createRow(rowNum);
                style = workbook.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER);
                row.setRowStyle(style);
                row.createCell(0).setCellValue(rowNum);

                if (xxb.getMatterName() == null) {
                    row.createCell(1).setCellValue("");
                } else {
                    row.createCell(1).setCellValue(xxb.getMatterName());
                }


                if (xxb.getSumCount() == null) {
                    row.createCell(2).setCellValue("");
                } else {
                    row.createCell(2).setCellValue(xxb.getSumCount());
                }


                if (xxb.getDoneCount() == null) {
                    row.createCell(3).setCellValue("");
                } else {
                    row.createCell(3).setCellValue(xxb.getDoneCount());
                }


                if (xxb.getMaxTime() == null) {
                    row.createCell(4).setCellValue("");
                } else {
                    row.createCell(4).setCellValue(xxb.getMaxTime());
                }


                if (xxb.getMinTime() == null) {
                    row.createCell(5).setCellValue("");
                } else {
                    row.createCell(5).setCellValue(xxb.getMinTime());
                }


                if (xxb.getAvgTime() == null) {
                    row.createCell(6).setCellValue("");
                } else {
                    row.createCell(6).setCellValue(xxb.getAvgTime());
                }


                rowNum++;
            }

            String fileName = "sxlist.xls";
            fileName = new String(fileName.getBytes(), "ISO8859-1");
            //清空response
            //设置response的Header
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream os = response.getOutputStream();
            //将excel写入到输出流中
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "导出失败"));
        }

        return JSON.toJSONString(AjaxResult.build(200, "success", "导出成功"));
    }


    @RequestMapping(value = "/sxList/sxEditExport", method = RequestMethod.GET)
    @ResponseBody
    public String sxEditExport(HttpServletResponse response, @RequestParam String year, @RequestParam String month
            , @RequestParam String matterId, String name) throws IOException {
        int pageNum = 1;
        int pageSize = 9999;
        ZQTPageModel result = new ZQTPageModel();
        List<TKGridRegion> lists = new ArrayList<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDay = dateMap.get("firstDate");
        TKGridRegionExample exampleTemp = new TKGridRegionExample();
        exampleTemp.setStartLimit((pageNum - 1) * pageSize);
        exampleTemp.setEndLimit(pageSize);
        exampleTemp.setStartDate(firstDay);
        exampleTemp.setMatterId(matterId);
        lists = extendGridRegionMapper.selectMatterDetailStat(exampleTemp);


        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个Excel表单,参数为sheet的名字
        HSSFSheet sheet = workbook.createSheet("事项列表");
        //创建表头
        HSSFRow row = sheet.createRow(0);
        //设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);

        HSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("序号");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue("事项类型");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("网格");
        cell.setCellStyle(style);

        cell = row.createCell(3);
        cell.setCellValue("上报数量");
        cell.setCellStyle(style);


        cell = row.createCell(4);
        cell.setCellValue("完成数量");
        cell.setCellStyle(style);

        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        for (TKGridRegion xxb : lists) {
            row = sheet.createRow(rowNum);
            style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            row.setRowStyle(style);
            row.createCell(0).setCellValue(rowNum);
            if (StringUtils.isNotEmpty(name)) {
                row.createCell(1).setCellValue(name);
            } else {
                row.createCell(1).setCellValue("");
            }

            if (xxb.getWgMaster() == null) {
                row.createCell(2).setCellValue("");
            } else {
                row.createCell(2).setCellValue(xxb.getWgMaster());
            }


            if (xxb.getSumCount() == null) {
                row.createCell(3).setCellValue("");
            } else {
                row.createCell(3).setCellValue(xxb.getSumCount());
            }


            if (xxb.getDoneCount() == null) {
                row.createCell(4).setCellValue("");
            } else {
                row.createCell(4).setCellValue(xxb.getDoneCount());
            }
            rowNum++;
        }
        String fileName = "sxEdit.xls";
        fileName = new String(fileName.getBytes(), "ISO8859-1");
        //清空response
        //设置response的Header
        response.setContentType("application/octet-stream;charset=ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        OutputStream os = response.getOutputStream();
        //将excel写入到输出流中
        workbook.write(os);
        os.flush();
        os.close();
        return "导出解析成功";
    }


    @RequestMapping(value = "/zx/zxExport", method = RequestMethod.GET)
    @ResponseBody
    public String zxExport(HttpServletResponse response, @RequestParam String year, @RequestParam String month) throws IOException {
        int pageNum = 1;
        int pageSize = 9999;
        ZQTPageModel result = new ZQTPageModel();
        List<TkCommonTask> lists = new ArrayList<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDay = dateMap.get("firstDate");
        Date lastDate = dateMap.get("lastDate");

        TKGridRegionExample exampleTemp = new TKGridRegionExample();
        exampleTemp.setStartLimit((pageNum - 1) * pageSize);
        exampleTemp.setEndLimit(pageSize);
        exampleTemp.setStartDate(firstDay);
        lists = extendGridRegionMapper.selectComeFrom3(exampleTemp);

        TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteriat = tkCommonTaskExample.createCriteria();
        criteriat.andComeFromEqualTo(3);
        criteriat.andReleaseTimeBetween(firstDay, lastDate);
        long count = tkCommonTaskService.countByExample(tkCommonTaskExample);

        Map<String, String> deptMap = new HashMap<>();
        for (TkCommonTask task : lists) {
            if (StringUtils.isNotBlank(task.getPerformUserId())) {
                SysUser sysUser = sysUserService.selectUserById(task.getPerformUserId());
                deptMap.put(task.getPerformUserId(), sysUser.getDept().getDeptName());
            }
        }

        for (TkCommonTask tkCommonTask : lists) {
            tkCommonTask.setMatterName("");
            if (deptMap.containsKey(tkCommonTask.getPerformUserId())) {
                tkCommonTask.setStandby3(deptMap.get(tkCommonTask.getPerformUserId()));
            }
            if (tkCommonTask.getTkStatus() > 40) {
                tkCommonTask.setZt("已完成");
            } else if (tkCommonTask.getTkStatus() == 40) {
                tkCommonTask.setZt("待评价");
            } else if (tkCommonTask.getTkStatus() >= 30 && tkCommonTask.getTkStatus() < 40) {
                tkCommonTask.setZt("待核查");
            } else if (tkCommonTask.getTkStatus() >= 20 && tkCommonTask.getTkStatus() < 30) {
                tkCommonTask.setZt("处理中");
            } else if (tkCommonTask.getTkStatus() > 10 && tkCommonTask.getTkStatus() < 20 && tkCommonTask.getTkStatus() != 16) {
                tkCommonTask.setZt("待处理");
            } else if (tkCommonTask.getTkStatus() == 10 || tkCommonTask.getTkStatus() == 10) {
                tkCommonTask.setZt("待指派");
            } else if (tkCommonTask.getTkStatus() == 32) {
                tkCommonTask.setZt("待延时");
            }
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个Excel表单,参数为sheet的名字
        HSSFSheet sheet = workbook.createSheet("事项列表");
        //创建表头
        HSSFRow row = sheet.createRow(0);
        //设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);

        HSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("序号");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue("名称");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("内容");
        cell.setCellStyle(style);


        cell = row.createCell(3);
        cell.setCellValue("类型");
        cell.setCellStyle(style);

        cell = row.createCell(4);
        cell.setCellValue("办理部门");
        cell.setCellStyle(style);

        cell = row.createCell(5);
        cell.setCellValue("办理人");
        cell.setCellStyle(style);

        cell = row.createCell(6);
        cell.setCellValue("抄送人");
        cell.setCellStyle(style);

        cell = row.createCell(7);
        cell.setCellValue("要求办结时间");
        cell.setCellStyle(style);

        cell = row.createCell(8);
        cell.setCellValue("实际办理时长");
        cell.setCellStyle(style);

        cell = row.createCell(9);
        cell.setCellValue("办理状态");
        cell.setCellStyle(style);

        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        for (TkCommonTask tkCommonTask : lists) {
            row = sheet.createRow(rowNum);
            style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            row.setRowStyle(style);
            row.createCell(0).setCellValue(rowNum);
            if (tkCommonTask.getTkName() == null) {
                row.createCell(1).setCellValue("");
            } else {
                row.createCell(1).setCellValue(tkCommonTask.getTkName());
            }


            if (tkCommonTask.getTkDetail() == null) {
                row.createCell(2).setCellValue("");
            } else {
                row.createCell(2).setCellValue(tkCommonTask.getTkDetail());
            }

            if (tkCommonTask.getMatterName() == null) {
                row.createCell(3).setCellValue("");
            } else {
                row.createCell(3).setCellValue(tkCommonTask.getMatterName());
            }

            if (tkCommonTask.getStandby3() == null) {
                row.createCell(4).setCellValue("");
            } else {
                row.createCell(4).setCellValue(tkCommonTask.getStandby3());
            }

            if (tkCommonTask.getPerformUserName() == null) {
                row.createCell(5).setCellValue("");
            } else {
                row.createCell(5).setCellValue(tkCommonTask.getPerformUserName());
            }

            if (tkCommonTask.getStandby4() == null) {
                row.createCell(6).setCellValue("");
            } else {
                row.createCell(6).setCellValue(tkCommonTask.getStandby4());
            }

            if (tkCommonTask.getAssignedEndTime() == null) {
                row.createCell(7).setCellValue("");
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String sj = "";
                sj = sdf.format(tkCommonTask.getAssignedEndTime());
                row.createCell(7).setCellValue(sj);

            }

            if (tkCommonTask.getStandby5() == null) {
                row.createCell(8).setCellValue("");
            } else {
                row.createCell(8).setCellValue(String.valueOf(Integer.parseInt(tkCommonTask.getStandby5()) / 3600));
            }

            if (tkCommonTask.getZt() == null) {
                row.createCell(9).setCellValue("");
            } else {
                row.createCell(9).setCellValue(tkCommonTask.getZt());
            }
            rowNum++;
        }
        String fileName = "zs.xls";
        fileName = new String(fileName.getBytes(), "ISO8859-1");
        //清空response
        //设置response的Header
        response.setContentType("application/octet-stream;charset=ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        OutputStream os = response.getOutputStream();
        //将excel写入到输出流中
        workbook.write(os);
        os.flush();
        os.close();
        return "导出解析成功";
    }


    @RequestMapping(value = "/gdtj/gdtjExportInfo", method = RequestMethod.GET)
    @ResponseBody
    public String gdtjExportInfo(HttpServletResponse response, @RequestParam String year,
                                 @RequestParam String month, String day) {
        int pageNum = 1;
        int pageSize = 9999;
        String ymFlag = "1";
        List<TKGridRegion> list = new ArrayList<>();
        ZQTPageModel result = new ZQTPageModel();

        Date firstDate = null;
        Date lastDate = null;
        if (StringUtils.isNotBlank(day)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            StringBuilder sb = new StringBuilder();
            sb.append(year).append("-").append(month.length() == 1 ? "0" + month : month).append("-").append(day.length() == 1 ? "0" + day : day);
            try {
                firstDate = format.parse(sb.toString() + " 00:00:00");
                lastDate = format.parse(sb.toString() + " 23:59:59");
                ymFlag = "2";
            } catch (ParseException e) {
                e.printStackTrace();
            }

        } else {
            Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
            firstDate = dateMap.get("firstDate");
            lastDate = dateMap.get("lastDate");
        }

        try {
            SysRole sysRole = new SysRole();
            sysRole.setRoleKey("threegird");
            sysRole.setStatus("0");
            List<SysRole> roles = sysRoleService.selectRoleList(sysRole);
            List<Long> roleIds = new ArrayList<>();
            for (SysRole role : roles) {
                roleIds.add(role.getRoleId());
            }
            List<SysUserRole> roleUsers = sysUserRoleMapper.listByRoleIds(roleIds);
            List<String> roleUserIds = new ArrayList<>();
            for (SysUserRole user : roleUsers) {
                roleUserIds.add(user.getUserId());
            }
            TKGridRegionExample xxbExample = new TKGridRegionExample();
            xxbExample.setUserIds(roleUserIds);
            List<GridRegion> allGridRegions = extendGridRegionMapper.selectThirdWgByBaseId(xxbExample);

            xxbExample.setStartLimit((pageNum - 1) * pageSize);
            xxbExample.setEndLimit(pageSize);

            List<GridRegion> bsWgxxbs = extendGridRegionMapper.selectThirdWgByBaseId(xxbExample);

            long count = extendGridRegionMapper.countThirdWgByBaseId(xxbExample);

            List<String> gridIds = new ArrayList<>();//所有三级网格code
            List<String> allGridIds = new ArrayList<>();
            Set<String> parentIds = new HashSet<>();
            for (GridRegion bsWgxxb : bsWgxxbs) {
                gridIds.add(bsWgxxb.getWgCode());
                parentIds.add(bsWgxxb.getWgParentId());
            }

            for (GridRegion bsWgxxb : allGridRegions) {
                allGridIds.add(bsWgxxb.getWgCode());
            }

            if (CollectionUtils.isEmpty(gridIds)) {
                return JSON.toJSONString(AjaxResult.build(200, "success", "查询无数据"));
            }

            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andWgCodeIn(new ArrayList<>(parentIds));

            List<GridRegion> parentWgs = bsWgxxbService.selectByExample(example);

            Map<String, String> parentMap = new HashMap<>();
            for (GridRegion xxb : parentWgs) {
                parentMap.put(xxb.getWgCode(), xxb.getWgName());
            }

            Map<String, Object> para = new HashMap<String, Object>();
            para.put("gridIds", gridIds);
            para.put("startDate", firstDate);
            para.put("ymFlag", ymFlag);
            List<TkCommonTask> tkCommonTasks = tkCommonTaskExtMapper.thirdWgTaskList(para);


            para.put("gridIds", allGridIds);
            long allCount = tkCommonTaskExtMapper.countThirdWgTaskList(para);

            Map<String, Integer> taskAllMap = new HashMap<>();
            Map<String, Integer> taskResolveMap = new HashMap<>();
            Map<String, Integer> taskActiveMap = new HashMap<>();
            for (TkCommonTask task : tkCommonTasks) {
                if (!taskAllMap.containsKey(task.getWgCode())) {
                    taskAllMap.put(task.getWgCode(), 1);
                } else {
                    taskAllMap.put(task.getWgCode(), taskAllMap.get(task.getWgCode()) + 1);
                }

                if (null != task.getTkStatus() && task.getTkStatus() == 50) {
                    if (!taskResolveMap.containsKey(task.getWgCode())) {
                        taskResolveMap.put(task.getWgCode(), 1);
                    } else {
                        taskResolveMap.put(task.getWgCode(), taskResolveMap.get(task.getWgCode()) + 1);
                    }
                }

                if (null == task.getIsYouxiao() || 0 == task.getIsYouxiao()) {
                    if (!taskActiveMap.containsKey(task.getWgCode())) {
                        taskActiveMap.put(task.getWgCode(), 1);
                    } else {
                        taskActiveMap.put(task.getWgCode(), taskActiveMap.get(task.getWgCode()) + 1);
                    }
                }
            }


            Map<String, Integer> roundMap = new HashMap<>();
            TkRoundSubtaskExample subtaskExample = new TkRoundSubtaskExample();
            TkRoundSubtaskExample.Criteria criteria1 = subtaskExample.createCriteria();
            criteria1.andGridIdIn(gridIds);
            List<TkRoundSubtask> subtasks = tkRoundSubtaskService.selectByExample(subtaskExample);
            List<String> taskIds = new ArrayList<>();

            Map<String, String> wgRoundsubMap = new HashMap<>();
            Map<String, String> wgRoundTaskMap = new HashMap<>();
            Map<String, String> wgRoundPlanMap = new HashMap<>();
            if (subtasks != null && subtasks.size() > 0) {
                for (TkRoundSubtask subtask : subtasks) {
                    taskIds.add(subtask.getTaskId());
                    wgRoundsubMap.put(subtask.getTaskId(), subtask.getGridId());
                }

                TkRoundTaskExample taskExample = new TkRoundTaskExample();
                TkRoundTaskExample.Criteria criteria2 = taskExample.createCriteria();
                criteria2.andIdIn(taskIds);
                List<TkRoundTask> tasks = tkRoundTaskService.selectByExample(taskExample);
                List<String> planIds = new ArrayList<>();
                if (tasks != null && tasks.size() > 0) {
                    for (TkRoundTask task : tasks) {
                        planIds.add(task.getRoundPlanId());
                        if (wgRoundsubMap.containsKey(task.getId())) {
                            wgRoundTaskMap.put(task.getRoundPlanId(), wgRoundsubMap.get(task.getId()));
                        }
                    }

                    TkRoundPlanExample examplet = new TkRoundPlanExample();
                    TkRoundPlanExample.Criteria criterias = examplet.createCriteria();
                    criterias.andPeriodTypeEqualTo("4");
                    criterias.andIdIn(planIds);
                    criterias.andEndDateBetween(firstDate, lastDate);

                    List<TkRoundPlan> tkRoundPlanList = tkRoundPlanService.selectByExample(examplet);

                    if (tkRoundPlanList != null && tkRoundPlanList.size() > 0) {
                        for (TkRoundPlan tkRoundPlan : tkRoundPlanList) {
                            String wgCode = wgRoundTaskMap.get(tkRoundPlan.getId());
                            if (roundMap.get(wgCode) == null) {
                                roundMap.put(wgCode, 1);
                            } else {
                                roundMap.put(wgCode, Integer.parseInt(roundMap.get(wgCode).toString()) + 1);
                            }
                        }
                    }
                }
            }

            for (GridRegion bsWgxxb : bsWgxxbs) {
                TKGridRegion wgxxb = new TKGridRegion();
                String wgCode = bsWgxxb.getWgCode();
                String wgName = bsWgxxb.getWgName();
                wgxxb.setCunSheQu(parentMap.get(bsWgxxb.getWgParentId()));
                wgxxb.setWgMaster(wgName);
                wgxxb.setName(bsWgxxb.getYlzd1());
                wgxxb.setReportNum(taskAllMap.get(wgCode));
                wgxxb.setDoneNum(taskResolveMap.get(wgCode));
                wgxxb.setRoundNum(roundMap.get(wgCode));
                wgxxb.setActiveNum(taskActiveMap.get(wgCode));
                list.add(wgxxb);
            }

            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建一个Excel表单,参数为sheet的名字
            HSSFSheet sheet = workbook.createSheet("工单统计");
            //创建表头
            HSSFRow row = sheet.createRow(0);
            //设置为居中加粗
            HSSFCellStyle style = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            style.setFont(font);
            style.setAlignment(HorizontalAlignment.CENTER);

            HSSFCell cell;
            cell = row.createCell(0);
            cell.setCellValue("所属村社区");
            cell.setCellStyle(style);

            cell = row.createCell(1);
            cell.setCellValue("所属网格");
            cell.setCellStyle(style);

            cell = row.createCell(2);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);


            cell = row.createCell(3);
            cell.setCellValue("上报数量");
            cell.setCellStyle(style);

            cell = row.createCell(4);
            cell.setCellValue("完成数量");
            cell.setCellStyle(style);

            cell = row.createCell(5);
            cell.setCellValue("日常巡查次数");
            cell.setCellStyle(style);

            cell = row.createCell(6);
            cell.setCellValue("有效任务数");
            cell.setCellStyle(style);


            //新增数据行，并且设置单元格数据
            int rowNum = 1;
            for (TKGridRegion tKGridRegion : list) {
                row = sheet.createRow(rowNum);
                style = workbook.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER);
                row.setRowStyle(style);
                if (tKGridRegion.getCunSheQu() == null) {
                    row.createCell(0).setCellValue("");
                } else {
                    row.createCell(0).setCellValue(tKGridRegion.getCunSheQu());
                }


                if (tKGridRegion.getWgMaster() == null) {
                    row.createCell(1).setCellValue("");
                } else {
                    row.createCell(1).setCellValue(tKGridRegion.getWgMaster());
                }

                if (tKGridRegion.getName() == null) {
                    row.createCell(2).setCellValue("");
                } else {
                    row.createCell(2).setCellValue(tKGridRegion.getName());
                }

                if (tKGridRegion.getReportNum() == null) {
                    row.createCell(3).setCellValue("");
                } else {
                    row.createCell(3).setCellValue(tKGridRegion.getReportNum());
                }

                if (tKGridRegion.getDoneNum() == null) {
                    row.createCell(4).setCellValue("");
                } else {
                    row.createCell(4).setCellValue(tKGridRegion.getDoneNum());
                }

                if (tKGridRegion.getRoundNum() == null) {
                    row.createCell(5).setCellValue("");
                } else {
                    row.createCell(5).setCellValue(tKGridRegion.getRoundNum());
                }

                if (tKGridRegion.getActiveNum() == null) {
                    row.createCell(6).setCellValue("");
                } else {
                    row.createCell(6).setCellValue(tKGridRegion.getActiveNum());
                }
                rowNum++;
            }
            String fileName = "gdtj.xls";
            fileName = new String(fileName.getBytes(), "ISO8859-1");
            //清空response
            //设置response的Header
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream os = response.getOutputStream();
            //将excel写入到输出流中
            workbook.write(os);
            os.flush();
            os.close();
            return JSON.toJSONString(AjaxResult.build(200, "success", "导出成功"));

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
    }


    @RequestMapping(value = "/bmtj/bmtjExport", method = RequestMethod.GET)
    @ResponseBody
    public String bmtjExportdccs(HttpServletResponse response, String type, String year,
                                 String month, String day) throws IOException {
        int pageNum = 1;
        int pageSize = 9999;
        ZQTPageModel result = new ZQTPageModel();
        List<TkCommonTask> lists = new ArrayList<>();
        try {
            TKGridRegionExample example = new TKGridRegionExample();
            example.setType(type);

            if (StringUtils.isNotBlank(year) && StringUtils.isNotBlank(month) && StringUtils.isNotBlank(day)) {
                month = month.length() == 1 ? "0" + month : month;
                day = day.length() == 1 ? "0" + day : day;
                example.setYearMonthDay(year + "-" + month + "-" + day);
            }

            if (StringUtils.isNotBlank(year) && StringUtils.isNotBlank(month)) {
                month = month.length() == 1 ? "0" + month : month;
                example.setYearMonth(year + "-" + month);
            }
            List<TKGridRegion> userTasks = extendGridRegionMapper.selectDeptStat(example);

            CountDownLatch latch = new CountDownLatch(userTasks.size());
            for (TKGridRegion xxb : userTasks) {
                threadPool.execute(new taskThread(latch, xxb));
            }

            latch.await();

            Map<String, TKGridRegion> resultMap = new HashMap<>();
            for (TKGridRegion xxb : userTasks) {
                if (!resultMap.containsKey(xxb.getName())) {
                    TKGridRegion tempxxb = new TKGridRegion();
                    BeanUtils.copyProperties(xxb, tempxxb);
                    resultMap.put(xxb.getName(), tempxxb);
                } else {
                    TKGridRegion tempxxb = resultMap.get(xxb.getName());
                    tempxxb.setReportNum(tempxxb.getReportNum() + xxb.getReportNum());
                    tempxxb.setDoneNum(tempxxb.getDoneNum() + xxb.getDoneNum());
                }
            }

            resultMap.remove(null);

            List<TKGridRegion> resultList = new ArrayList<>();
            List<TKGridRegion> resultListTemp = new ArrayList<>();
            List<TKGridRegion> resultListTemp2 = new ArrayList<>();
            resultListTemp = new ArrayList<>(resultMap.values());
            resultList = resultListTemp.stream().sorted(new Comparator<TKGridRegion>() {
                @Override
                public int compare(TKGridRegion o1, TKGridRegion o2) {
                    return o2.getReportNum() - o1.getReportNum();
                }
            }).collect(Collectors.toList());

            //总页数
            result.setPageCount((resultMap.size() + pageSize - 1) / pageSize);

            if (pageSize >= result.getPageCount()) {
                resultListTemp2 = resultList.subList((pageNum - 1) * pageSize, resultMap.size());
            } else {
                resultListTemp2 = resultList.subList((pageNum - 1) * pageSize, pageNum * pageSize);
            }


            DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
            //可以设置精确几位小数
            df.setMaximumFractionDigits(2);
            //模式 例如四舍五入
            df.setRoundingMode(RoundingMode.HALF_UP);

            for (TKGridRegion xxb : resultListTemp2) {
                double done = xxb.getDoneNum();
                double all = xxb.getReportNum();
                double rate = done / all * 100;
                xxb.setDonePercent(df.format(rate));
            }


            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建一个Excel表单,参数为sheet的名字
            HSSFSheet sheet = workbook.createSheet("事项列表");
            //创建表头
            HSSFRow row = sheet.createRow(0);
            //设置为居中加粗
            HSSFCellStyle style = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            style.setFont(font);
            style.setAlignment(HorizontalAlignment.CENTER);

            HSSFCell cell;
            cell = row.createCell(0);
            cell.setCellValue("部门名称");
            cell.setCellStyle(style);

            cell = row.createCell(1);
            cell.setCellValue("上报数量");
            cell.setCellStyle(style);

            cell = row.createCell(2);
            cell.setCellValue("完成工单数");
            cell.setCellStyle(style);


            cell = row.createCell(3);
            cell.setCellValue("完成工单率");
            cell.setCellStyle(style);

            //新增数据行，并且设置单元格数据
            int rowNum = 1;
            for (TKGridRegion xxb : resultListTemp2) {
                row = sheet.createRow(rowNum);
                style = workbook.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER);
                row.setRowStyle(style);
                if (xxb.getName() == null) {
                    row.createCell(0).setCellValue("");
                } else {
                    row.createCell(0).setCellValue(xxb.getName());
                }

                if (xxb.getReportNum() == null) {
                    row.createCell(1).setCellValue("");
                } else {
                    row.createCell(1).setCellValue(xxb.getReportNum());
                }


                if (xxb.getDoneNum() == null) {
                    row.createCell(2).setCellValue("");
                } else {
                    row.createCell(2).setCellValue(xxb.getDoneNum());
                }


                if (xxb.getDonePercent() == null) {
                    row.createCell(3).setCellValue("");
                } else {
                    row.createCell(3).setCellValue(xxb.getDonePercent() + "%");
                }
                rowNum++;
            }
            String fileName = "bmtj.xls";
            fileName = new String(fileName.getBytes(), "ISO8859-1");
            //清空response
            //设置response的Header
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream os = response.getOutputStream();
            //将excel写入到输出流中
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "导出失败"));
        }
        return "导出解析成功";
    }


    public Map<String, Object> listWgNamesAndIds(String wgName, String WgCode) {
        Map<String, Object> resultMap = new HashMap<>();
        List<String> wgNames = new ArrayList<>();
        List<String> wgIds = new ArrayList<>();

        wgNames.add("");
        wgIds.add("");

        resultMap.put("wgNames", wgNames);
        resultMap.put("wgIds", wgIds);

        GridRegionExample fGridRegionExample = new GridRegionExample();
        GridRegionExample.Criteria fBsWgCr = fGridRegionExample.createCriteria();
        fBsWgCr.andWgCodeEqualTo(WgCode);
        GridRegion fWg = bsWgxxbService.selectFirstByExample(fGridRegionExample);

        if (null == fWg) {
            return resultMap;
        }

        wgNames.add(fWg.getWgName());
        wgIds.add(fWg.getWgCode());

        GridRegionExample bsWgxxbExample = new GridRegionExample();
        GridRegionExample.Criteria bsWgCr = bsWgxxbExample.createCriteria();
        bsWgCr.andWgParentIdEqualTo(fWg.getWgCode());
        List<GridRegion> secBsWgs = bsWgxxbService.selectByExample(bsWgxxbExample);

        for (GridRegion bsWgxxb : secBsWgs) {
            wgNames.add(bsWgxxb.getWgName());
            wgIds.add(bsWgxxb.getWgCode());
        }

        GridRegionExample thirdGridRegionExample = new GridRegionExample();
        GridRegionExample.Criteria thirdBsWgCr = thirdGridRegionExample.createCriteria();
        thirdBsWgCr.andWgParentIdIn(wgIds);
        List<GridRegion> thirdBsWgs = bsWgxxbService.selectByExample(thirdGridRegionExample);

        for (GridRegion bsWgxxb : thirdBsWgs) {
            wgNames.add(bsWgxxb.getWgName());
            wgIds.add(bsWgxxb.getWgCode());
        }

        resultMap.put("wgNames", wgNames);
        resultMap.put("wgIds", wgIds);

        return resultMap;
    }

    @RequestMapping(value = "bigWindow/allTaskList", method = RequestMethod.GET)
    @ResponseBody
    public String bigWindowAllTaskList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                       @RequestParam String loginUserId,
                                       @RequestParam String loginUserRole,
                                       @RequestParam String roleCode,
                                       String wgCode,
                                       @RequestParam(required = false) Integer tkStatus,
                                       String titleOrCode) {


        Map<String, Object> data = new HashedMap();

        data.put("unfinished", 50);//未完成
        /*或者查询开始*/
        data.put("loginUserId", loginUserId);
        data.put("loginUserRole", loginUserRole);
        /*或者查询结束*/

        if (loginUserRole.equals("2")) {
            data.put("roleLeave", 2);
        } else if (loginUserRole.equals("0")) {
            data.put("roleLeave", 0);
        } else if (loginUserRole.equals("1") && !roleCode.equals("oneman")) {
            data.put("roleLeave", 1);
        } else {
            data.put("roleLeave", 3);
        }

        if (tkStatus != null) {//任务状态
            data.put("tkStatus", tkStatus);
        }

        //塞分页
        data.put("currIndex", (pageNum - 1) * pageSize);
        data.put("pageSize", pageSize);
        if (StringUtils.isNotBlank(titleOrCode)) {
            data.put("titleOrCode", "%" + titleOrCode + "%");
        }

        ZQTPageModel result = new ZQTPageModel();
        try {

            if (StringUtils.isNotBlank(wgCode)) {
                Map<String, Object> wgs = listWgNamesAndIds(null, wgCode);
                data.putAll(wgs);
            } else {
                data.put("wgNames", new ArrayList<>());
                data.put("wgIds", new ArrayList<>());
            }


            long count = 0;


            //分页
            result.setItemList(null);
            //总记录数
            int recordCount = (int) count;
            result.setRecordCount(recordCount);
            //总页数
            result.setPageCount((recordCount + pageSize - 1) / pageSize);
            //当前页
            result.setCurPage(recordCount == 0 ? 0 : pageNum);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "查询出错"));
        }

        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }

    /**
     * （4）当年度按月工单上报数量，分来源（自行解决的和上报中心网格联动的）
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/taskCountByYearMonth", method = RequestMethod.GET)
    @ResponseBody
    public String taskCountByYearMonth(@RequestParam String wgCode) {
        String mon = "";
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        Date releaseStartTime = DateUtils.getCurrYearFirst();
        Date releaseEndTime = DateUtils.getCurrYearLast();
        try {

            Map<String, Object> wgs = listWgNamesAndIds(null, wgCode);

            List<String> wgIds = (ArrayList) wgs.get("wgIds");
            List<String> wgNames = (ArrayList) wgs.get("wgNames");

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            for (int i = 0; i < 12; i++) {
                Calendar c = Calendar.getInstance();
                c.setTime(releaseStartTime);
                c.add(Calendar.MONTH, 0 + i);//当前月
                Date m = c.getTime();
                mon = format.format(m);
                //System.out.println("过去一个月："+mon);
                String[] split = mon.split("-");
                Date firstDayOfMonth1 = getFirstDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Date lastDayOfMonth1 = getLastDayOfMonth1(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
                Map<String, Object> map = new HashMap<String, Object>();
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
                map.put("firstDayOfMonth1", format2.format(firstDayOfMonth1));
                map.put("lastDayOfMonth1", format2.format(lastDayOfMonth1));
                map.put("releaseStartTime", releaseStartTime);
                map.put("releaseEndTime", releaseEndTime);
                map.put("wgNames", wgNames);
                map.put("wgIds", wgIds);
                Map<String, Object> allMap = new HashMap<String, Object>();
                allMap.put("wgCount", 0);
                allMap.put("zongZhiCount", 0);
                Map<String, Object> wgMap = tkCommonTaskExtMapper.overCount(map);
                if (null != wgMap && null != wgMap.get("wgCount")) {
                    allMap.put("wgCount", wgMap.get("wgCount"));
                }

                allMap.put("month", mon);
                ret.add(allMap);
            }

            TkCommonTaskExample example = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria cr = example.createCriteria();
            cr.andReleaseTimeBetween(releaseStartTime, releaseEndTime);
            cr.andWgCodeIn(wgIds);
            cr.andStandby1EqualTo("0");
            long allWgCount = tkCommonTaskMapper.countByExample(example);

            cr.andTkStatusGreaterThanOrEqualTo(40);
            long allDoneWgCount = tkCommonTaskMapper.countByExample(example);

            long allZongZhiCount = 0;

            long allDoneZongZhiCount = 0;

            long allCount = allWgCount + allZongZhiCount;
            long allDoneCount = allDoneWgCount + allDoneZongZhiCount;
            result.put("allCount", allCount);
            result.put("allDoneCount", allDoneCount);
            result.put("monthData", ret);

            if (allCount == 0L || allDoneCount == 0L) {
                result.put("bjl", 0);
            } else {
                DecimalFormat df = new DecimalFormat("0.00");
                result.put("bjl", df.format((double) allDoneCount / (double) allCount));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }


    /**
     * 日上报 日办理数量
     *
     * @return
     */
    @RequestMapping(value = "bigWindow/todayAllTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String todayAllTaskNum(
                                  @RequestParam int type,
                                  @RequestParam String wgCode) {
        Map<String, Object> ret = new HashMap<>();
        try {
            //1日上报 日办理数量 2周  3月
            Date startTime = null;
            Date endTime = null;
            if (type == 1) {
                startTime = DateUtils.getStartTime();
                endTime = DateUtils.getEndTime();
            } else if (type == 2) {
                startTime = DateUtils.getBeginDayOfWeek();
                endTime = DateUtils.getEndDayOfWeek();
            } else if (type == 3) {
                startTime = DateUtils.getBeginDayOfMonth();
                endTime = DateUtils.getEndDayOfMonth();
            }

            Map<String, Object> wgs = listWgNamesAndIds(null, wgCode);
            List<String> wgIds = (ArrayList) wgs.get("wgIds");
            List<String> wgNames = (ArrayList) wgs.get("wgNames");

            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andStandby1EqualTo("0");
            criteria.andHandleTypeEqualTo(2);//2上报中心
            criteria.andReleaseTimeBetween(startTime, endTime);
            criteria.andWgCodeIn(wgIds);
            int shangbaoCount = tkCommonTaskService.countByExample(tkCommonTaskExample);

            long allZongZhiCount =0;

            ret.put("shangbao", shangbaoCount + allZongZhiCount);

            TkCommonTaskExample tkCommonTaskExample2 = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria2 = tkCommonTaskExample2.createCriteria();
            criteria2.andStandby1EqualTo("0");
            criteria2.andTkStatusGreaterThanOrEqualTo(40);
            criteria2.andReleaseTimeBetween(startTime, endTime);
            criteria2.andWgCodeIn(wgIds);
            int endCount = tkCommonTaskService.countByExample(tkCommonTaskExample2);

            List<String> ztList = new ArrayList<>();
            ztList.add("已办结");
            ztList.add("自行处置");
            long ZongZhiEndCount =0;

            ret.put("endCount", endCount + ZongZhiEndCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }

    @RequestMapping(value = "bigWindow/allMatterRank", method = RequestMethod.GET)
    @ResponseBody
    public String allMatterRank(
                                @RequestParam int type,
                                @RequestParam String wgCode) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {

            Map<String, Object> wgs = listWgNamesAndIds(null, wgCode);
            Date releaseStartTime = DateUtils.getCurrYearFirst();
            Date releaseEndTime = DateUtils.getCurrYearLast();
            Map<String, Object> data = new HashedMap();
            data.put("releaseStartTime", releaseStartTime);
            data.put("releaseEndTime", releaseEndTime);
            data.putAll(wgs);
            if (type == 1) {
                list = tkCommonTaskService.selectMatterRankByWg(data);
            } else if (type == 2) {
                list = Collections.emptyList();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }


    /**
     * 常州奔牛专用接口，获取他们做的微信小程序提交的所有数据
     *
     * @param releaseUserId
     * @return
     */
    @RequestMapping(value = "wxDataList", method = RequestMethod.GET)
    @ResponseBody
    public String wxDataList(
                             @RequestParam(required = true) String releaseUserId,
                             String wxUserId) {

        List<TkCommonTask> tkCommonTasks = new ArrayList<>();
        try {
            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
            criteria.andReleaseUserIdEqualTo(releaseUserId);
            criteria.andStandby1EqualTo("0");
            criteria.andComeFromEqualTo(6);
            if (StringUtils.isNotBlank(wxUserId)) {
                criteria.andWxUserIdEqualTo(wxUserId);
            }
            tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);


        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", tkCommonTasks));
        }


        return JSON.toJSONString(AjaxResult.build(200, "success", tkCommonTasks));
    }

    //环卫人员工单统计
    @RequestMapping(value = "enviromentManStatistic", method = RequestMethod.GET)
    @ResponseBody
    public String enviromentManStatistic(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam String year,
            @RequestParam String month) {

        ZQTPageModel result = new ZQTPageModel();
        List<Map<String, Object>> lists = new ArrayList<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDay = dateMap.get("firstDate");
        Map paramMap = new HashMap();


        try {

            paramMap.put("comeFrom", "18");
            paramMap.put("startDate", firstDay);

            lists = tkCommonTaskService.enviromentManStatistic(paramMap);

            result.setPageCount((lists.size() + pageSize - 1) / pageSize);

            if (pageNum >= result.getPageCount()) {
                resultList = lists.subList((pageNum - 1) * pageSize, lists.size());
            } else {
                resultList = lists.subList((pageNum - 1) * pageSize, pageNum * pageSize);
            }

            //总记录数
            result.setRecordCount(lists.size());
            result.setItemList(resultList);
            //当前页
            result.setCurPage(pageNum);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }

    //环卫督查事项统计
    @RequestMapping(value = "enviromentMatterStatistic", method = RequestMethod.GET)
    @ResponseBody
    public String enviromentMatterStatistic(
            @RequestParam String year,
            @RequestParam String month) {

        ZQTPageModel result = new ZQTPageModel();
        List<Map<String, Object>> lists = new ArrayList<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDay = dateMap.get("firstDate");
        Map paramMap = new HashMap();


        try {

            paramMap.put("comeFrom", "18");
            paramMap.put("startDate", firstDay);

            lists = tkCommonTaskService.enviromentMatterStatistic(paramMap);


            //总记录数
            result.setRecordCount(lists.size());
            result.setItemList(lists);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", result));
    }


    @RequestMapping(value = "/hwdc/hwdcExport", method = RequestMethod.GET)
    @ResponseBody
    public String hwdcExport(HttpServletResponse response, @RequestParam String year, @RequestParam String month) throws IOException {
        int pageNum = 1;
        int pageSize = 9999;
        ZQTPageModel result = new ZQTPageModel();
        List<Map<String, Object>> lists = new ArrayList<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDay = dateMap.get("firstDate");
        Map paramMap = new HashMap();
        paramMap.put("comeFrom", "18");
        paramMap.put("startDate", firstDay);
        lists = tkCommonTaskService.enviromentManStatistic(paramMap);


        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个Excel表单,参数为sheet的名字
        HSSFSheet sheet = workbook.createSheet("环卫督察");
        //创建表头
        HSSFRow row = sheet.createRow(0);
        //设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);

        HSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("姓名");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue("月份");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("工单数量");
        cell.setCellStyle(style);

        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        for (int i = 0; i < lists.size(); i++) {
            ;
            row = sheet.createRow(rowNum);
            style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            row.setRowStyle(style);
            if (StringUtils.isNotEmpty(lists.get(i).get("release_user_name").toString())) {
                row.createCell(0).setCellValue(lists.get(i).get("release_user_name").toString());
            } else {
                row.createCell(0).setCellValue("");
            }
            if (StringUtils.isNotEmpty(lists.get(i).get("month").toString())) {
                row.createCell(1).setCellValue(lists.get(i).get("month").toString());
            } else {
                row.createCell(1).setCellValue("");
            }

            if (StringUtils.isNotEmpty(lists.get(i).get("num").toString())) {
                row.createCell(2).setCellValue(lists.get(i).get("num").toString());
            } else {
                row.createCell(2).setCellValue("");
            }

            rowNum++;
        }
        String fileName = "sxEdit.xls";
        fileName = new String(fileName.getBytes(), "ISO8859-1");
        //清空response
        //设置response的Header
        response.setContentType("application/octet-stream;charset=ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        OutputStream os = response.getOutputStream();
        //将excel写入到输出流中
        workbook.write(os);
        os.flush();
        os.close();
        return "导出解析成功";
    }


    /**
     * 近7天的日常任务数量
     *
     * @return
     */
    @RequestMapping(value = "nearSevenDayTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String nearSevenDayTaskNum(String wgCode, String startTime) {
        List<DayAndNums> list = new ArrayList<DayAndNums>();
        ArrayList<Date> test = null;
        try {
            if (StringUtils.isNotEmpty(startTime)) {
                test = getDateList(7, startTime);
            } else {
                test = getDateList(7);
            }

            SimpleDateFormat format = new SimpleDateFormat("MM/dd");
            System.out.println("----" + JSONObject.toJSONString(test));

            if (test.size() > 0) {
                int i = 7;//计数器
                for (Date da : test) {
                    TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
                    TkCommonTaskExample.Criteria criteria = tkCommonTaskExample.createCriteria();
                    criteria.andReleaseTimeEqualTo(da);
                    criteria.andStandby1EqualTo("0");
                    criteria.andWgCodeLike(wgCode + "%");
                    List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(tkCommonTaskExample);
                    DayAndNums dayAndNums = new DayAndNums();
                    dayAndNums.setDay(format.format(da));
                    dayAndNums.setValue(tkCommonTasks.size());
                    list.add(dayAndNums);
                    i--;
                }
            }

            Collections.reverse(list); // 倒叙

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "任务数量获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", list));
    }


    /**
     * 日/周/月的工单数量
     *
     * @param wgUserId 网格用户id
     * @return
     */
    @RequestMapping(value = "countAllTypeTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String todayTaskNum(String wgUserId, String startTime, String endTime,@RequestParam(required = false) Integer comeFrom) {
        TodayTaskNumVO ret = new TodayTaskNumVO();
        DecimalFormat df = new DecimalFormat("0.00");
        try {

            //今日工单
            int todayCount = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(DateUtils.getStartTime(), DateUtils.getEndTime(),wgUserId,null,comeFrom);
            ret.setTodayCount(todayCount);
            //今日办结工单
            int todayEndCount =  tkCommonTaskExtMapper.countByReleaseTimeAndUserId(DateUtils.getStartTime(), DateUtils.getEndTime(),wgUserId,50,comeFrom);
            ret.setTodayEndCount(todayCount);
            //今日办结率
            ret.setCurrentTodayBjl(todayCount == 0?"0":df.format(((double) todayEndCount / (double) todayCount) * 100));

            //本周工单
            int weekCount = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(DateUtils.getBeginDayOfWeek(), DateUtils.getEndDayOfWeek(),wgUserId,null,comeFrom);
            ret.setWeekCount(weekCount);
            //本周办结工单
            int weekEndCount =  tkCommonTaskExtMapper.countByReleaseTimeAndUserId(DateUtils.getBeginDayOfWeek(), DateUtils.getEndDayOfWeek(),wgUserId,50,comeFrom);
            ret.setWeekEndCount(weekCount);
            //本周办结率
            ret.setCurrentWeekBjl(weekCount == 0?"0":df.format(((double) weekEndCount / (double) weekCount) * 100));

            //本月工单
            int monthCount = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(DateUtils.getBeginDayOfMonth(), DateUtils.getEndDayOfMonth(),wgUserId,null,comeFrom);
            ret.setMonthCount(monthCount);
            //本月办结工单
            int monthEndCount = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(DateUtils.getBeginDayOfMonth(), DateUtils.getEndDayOfMonth(),wgUserId,50,comeFrom);
            ret.setMonthEndCount(monthEndCount);
            //本月办结率
            ret.setCurrentMonthBjl(monthCount==0?"0":df.format(((double) monthEndCount / (double) monthCount) * 100));

            //本年工单
            int yearCount = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(DateUtils.getCurrYearFirst(), DateUtils.getCurrYearLast(),wgUserId,null,comeFrom);
            ret.setYearCount(yearCount);
            //本年办结工单
            int yearEndCount = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(DateUtils.getCurrYearFirst(), DateUtils.getCurrYearLast(),wgUserId,50,comeFrom);
            ret.setYearEndCount(yearEndCount);
            //本年办结率
            ret.setCurrentYearBjl(yearCount==0?"0":df.format(((double) yearEndCount / (double) yearCount) * 100));

            Date startTimeF = StringUtils.isBlank(startTime)?null:DateUtil.getDate(startTime, DateUtil.DATAFORMAT_STR);
            Date endTimeF = StringUtils.isBlank(endTime)?null:DateUtil.getDate(endTime, DateUtil.DATAFORMAT_STR);
            //完成工单
            int endCount = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(startTimeF,endTimeF,wgUserId,50,comeFrom);
            ret.setEndCount(endCount);
            //所有工单
            int allCount = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(startTimeF,endTimeF,wgUserId,null,comeFrom);
            ret.setAllCount(allCount);
            //办结率
            ret.setBjl(allCount == 0?"0":df.format(((double) endCount / (double) allCount) * 100));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "获取出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", ret));
    }


    //当月村社区工单统计
    @RequestMapping(value = "countTaskBySq", method = RequestMethod.GET)
    @ResponseBody
    public String countTaskBySq(
            @RequestParam String year,
            @RequestParam String month,
            @RequestParam String wgCode) {
        List<GridWgBean> lists = new ArrayList<>();
        Map<String, Date> dateMap = getMonthFirstAndLastDay(year, month);
        Date firstDay = dateMap.get("firstDate");
        Map paramMap = new HashMap();

        try {

            paramMap.put("wgCode", wgCode);
            paramMap.put("startDate", firstDay);
            paramMap.put("rootCode", bsWgxxbMapper.getRootWgCode());

            lists = tkCommonTaskService.countTaskBySq(paramMap);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", lists));
    }


    /**
     * 工单评级
     *
     * @return
     */
    @RequestMapping(value = "pingji", method = RequestMethod.POST)
    @ResponseBody
    public String pingji(String id, String gsType) {
        TkCommonTask tkCommonTask = new TkCommonTask();
        tkCommonTask.setGsType(Integer.valueOf(gsType));
        tkCommonTask.setId(id);
        try {
            int i = tkCommonTaskService.updateByPrimaryKeySelective(tkCommonTask);
            if (i == 0) {
                return JSON.toJSONString(AjaxResult.build(400, "fail", "评级出错"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "评级出错"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", "评级成功"));
    }


    /**
     * 新增领导端 超级检索查询网格工单列表查询接口：
     *
     * @param userName
     * @param pageSize
     * @param pageNum
     * @return
     */
    @RequestMapping(value = "selectTaskList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult selectTaskList(
                                       @RequestParam(value = "userName") String userName,
                                       @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                       @RequestParam(value = "pageNum", defaultValue = "1", required = false) int pageNum) {

        try {
            PageInfo<Map<String, Object>> pageInfo = tkCommonTaskService.selectTaskList(userName, pageSize, pageNum);
            return AjaxResult.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.build(400, "fail", "查询失败");
        }
    }

    @ApiOperation("重新指派签批人")
    @PostMapping("resetQpr")
    public AjaxResult resetQpr(@RequestBody TkResetRequest request){
        List<GridRegionUser> gridRegionUser = bsWgxxUserService.getPermissionWgCodes(this.getUserId());
        Map<String,String> gridRegion = bsWgxxbService.getMapByWgCodes(gridRegionUser.stream().map(GridRegionUser::getWgId).collect(Collectors.toList()));
        request.setLoginUserName(this.getLoginUser().getUser().getNickName());
        request.setLoginUserBelongGrid(String.join(",",gridRegion.values()));
        taskService.resetQpr(request);
        return  AjaxResult.build(200, "success", "操作成功");
    }
}