package com.ruoyi.web.controller.task;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.zqt.ZQTPageModel;
import com.ruoyi.system.domain.grid.GridRegion;
import com.ruoyi.system.domain.task.*;
import com.ruoyi.system.domain.task.utils.WorkMSGUtils;
import com.ruoyi.system.service.task.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(tags = "工单 巡查 任务")
@RestController
@RequestMapping("/api/task/roundTask")
public class RoundTaskController {

    @Autowired
    TkRoundTaskService tkRoundTaskService;

    @Autowired
    TkRoundSubtaskService tkRoundSubtaskService;

    @Autowired
    TkRoundPlanService tkRoundPlanService;
    @Autowired
    TkRoundMatterService tkRoundMatterService;

    @Autowired
    DiyService diyService;

    @Autowired
    TkCommonTaskService tkCommonTaskService;

    @Autowired
    private WorkMSGUtils workMSGUtils;


    @ApiOperation("每日巡查统计")
    @RequestMapping(value = "statistics", method = RequestMethod.GET)
    @ResponseBody
    public String endTask(String matterId,
                          String matterName,
                          String date) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> result = new TreeMap<>();
        List<TkRoundPlan> totalPlanList = new ArrayList<>();
        List<Map<String, Object>> mapList = new ArrayList<>();
        try {
            // 先取到某政府下有效的3级基础网格，再更具这个查到所有plan
            List<GridRegion> third = diyService.getThird();

            List<String> wgNames = new ArrayList<>();
            Set<String> haveDateWgNames = new HashSet<>();
            for (GridRegion bsWgxxb : third) {
                wgNames.add(bsWgxxb.getWgName());
            }

            TkRoundSubtaskExample subtaskExample = new TkRoundSubtaskExample();
            TkRoundSubtaskExample.Criteria criteria1 = subtaskExample.createCriteria();
            List<String> gridIds = new ArrayList<>();
            for (GridRegion bsWgxxb : third) {
                gridIds.add(bsWgxxb.getWgCode());
            }
            criteria1.andGridIdIn(gridIds);
            List<TkRoundSubtask> subtasks = tkRoundSubtaskService.selectByExample(subtaskExample);
            List<String> taskIds = new ArrayList<>();

            if (subtasks != null && subtasks.size() > 0) {
                for (TkRoundSubtask subtask : subtasks) {
                    taskIds.add(subtask.getTaskId());
                }

                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());
                    }


                    TkRoundPlanExample example = new TkRoundPlanExample();
                    TkRoundPlanExample.Criteria criteria = example.createCriteria();
                    criteria.andPeriodTypeEqualTo("4");
                    criteria.andIdIn(planIds);
                    totalPlanList = tkRoundPlanService.selectByExample(example);
                    if (StringUtils.isNotBlank(date)) {
                        criteria.andEndDateEqualTo(DateUtil.getDate(date, DateUtil.DATAFORMAT_STR));
                    } else {
                        criteria.andEndDateEqualTo(new Date());
                    }

                    if (StringUtils.isNotBlank(matterName)) {
                        criteria.andMatterNameLike("%" + matterName + "%");
                    }
                    List<TkRoundPlan> tkRoundPlanList = tkRoundPlanService.selectByExample(example);

                    if (tkRoundPlanList != null && tkRoundPlanList.size() > 0) {
                        for (TkRoundPlan tkRoundPlan : tkRoundPlanList) {
                            String wgName = getWgName(tkRoundPlan.getId());
                            haveDateWgNames.add(wgName);
                            if (result.get(wgName) == null) {
                                result.put(wgName, 1);
                            } else {
                                result.put(wgName, Integer.parseInt(result.get(wgName).toString()) + 1);
                            }
                        }

                        // 删掉有的 剩下就是空网格
                        wgNames.removeAll(haveDateWgNames);
                    }
                }
            }
            for (String wgName : wgNames) {
                result.put(wgName, 0);
            }
            int done = haveDateWgNames.size();
            int todo = wgNames.size();
            map.put("total", third.size());
            map.put("done", done);
            map.put("todo", todo);

            for (String s : result.keySet()) {
                Map<String, Object> wg = new HashMap<>();
                wg.put("wgName", s);
                wg.put("doNum", result.get(s));
                wg.put("done", Integer.parseInt(result.get(s).toString()) == 0 ? false : true);
                mapList.add(wg);
            }
            map.put("result", mapList);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(500, "fail", "查询失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success", map));
    }

    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();
    }


    @ApiOperation("结束日常巡查")
    @RequestMapping(value = "endTask", method = RequestMethod.POST)
    @ResponseBody
    public String endTask(@RequestBody Map<String, Object> map) {
        try {
            TkRoundTask tkRoundTask = tkRoundTaskService.selectByPrimaryKey(map.get("taskId").toString());
            tkRoundTask.setStatus("2");
            tkRoundTask.setPercent(100);
            tkRoundTaskService.updateByPrimaryKey(tkRoundTask);
            TkRoundPlan tkRoundPlan = tkRoundPlanService.selectByPrimaryKey(tkRoundTask.getRoundPlanId());
            tkRoundPlan.setEndDate(new Date());
            tkRoundPlanService.updateByPrimaryKey(tkRoundPlan);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return JSON.toJSONString(AjaxResult.build(500, "fail", "结束失败"));
        }
        return JSON.toJSONString(AjaxResult.build(200, "success"));
    }

    /**
     * 查询列表
     * GET（SELECT） 从服务器取出资源（一项或多项）
     * 筛选：
     * 1.权限    loginUserRole
     * 2.是否是参与人员   userId  （如果不是中心领导或者一级网格领导）
     *
     * @return
     */
    @ApiOperation("查询列表")
    @GetMapping
    @ResponseBody
    public String getList(@RequestParam(required = false, value = "pageNum", defaultValue = "1") int pageNum,
                          @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize,
                          @RequestParam(required = false, value = "objId") String objId,
                          @RequestParam(required = false, value = "origin") String origin,
                          @RequestParam(required = false, value = "status") String status,
                          @RequestParam(required = false, value = "loginUserRole") String loginUserRole,
                          @RequestParam(required = false, value = "userId") String userId,
                          @RequestParam(required = false, value = "time") String time,
                          @RequestParam(required = false, value = "startDate") String startDate,
                          @RequestParam(required = false, value = "endDate") String endDate,
                          @RequestParam(required = false, value = "currentMonth") Integer currentMonth,
                          @RequestParam(required = false, value = "name") String name
    ) {
        List<String> taskIdsList = new ArrayList<>();
        if (StringUtils.isNotBlank(objId)) {
            TkRoundSubtaskExample example = new TkRoundSubtaskExample();
            TkRoundSubtaskExample.Criteria criteria = example.createCriteria();
            criteria.andObjIdEqualTo(objId);

            List<TkRoundSubtask> subtasks = tkRoundSubtaskService.selectByExample(example);
            Set<String> taskIds = new HashSet<>();
            for (TkRoundSubtask subtask : subtasks) {
                taskIds.add(subtask.getTaskId());
            }
            taskIdsList = new ArrayList<>(taskIds);
        }

        TkRoundTaskExample tkRoundTaskExample = new TkRoundTaskExample();
        TkRoundTaskExample.Criteria criteria = tkRoundTaskExample.createCriteria();

        tkRoundTaskExample.setOrderByClause("time desc");
        criteria.andIsShowEqualTo("1");
        if (time != null) {
            Date time2 = DateUtil.getDate(time, DateUtil.DATAFORMAT_STR);
            criteria.andTimeEqualTo(time2);
        }
        if (startDate != null) {
            Date time2 = DateUtil.getDate(startDate, DateUtil.DATAFORMAT_STR);
            criteria.andTimeGreaterThanOrEqualTo(time2);
        }
        if (endDate != null) {
            Date time2 = DateUtil.getDate(endDate, DateUtil.DATAFORMAT_STR);
            criteria.andTimeLessThanOrEqualTo(time2);
        }
        if (taskIdsList.size() > 0) {
            criteria.andIdIn(taskIdsList);
        }
        if (StringUtils.isNotBlank(origin)) {
            criteria.andOriginLike("%" + origin + "%");
        }
        if (StringUtils.isNotBlank(status)) {
            criteria.andStatusLike("%" + status + "%");
        }
        if (StringUtils.isNotBlank(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (currentMonth != null && currentMonth == 1) {
            criteria.andTimeGreaterThanOrEqualTo(getFirstDayByMonth(0));
            criteria.andTimeLessThan(getFirstDayByMonth(1));
        }
        if (StringUtils.isNotBlank(loginUserRole) && (loginUserRole.equals("centerman") || loginUserRole.startsWith("one"))) {
            System.out.println("中心或者一级网格看见所有 ");
        } else {
            if (StringUtils.isNotBlank(userId)) {
                criteria.andUserIdsLike("%" + userId + "%");
            }
        }

        PageHelper.startPage(pageNum, pageSize);
        List<TkRoundTask> tkRoundTaskList = tkRoundTaskService.selectByExampleWithBLOBs(tkRoundTaskExample);
        for (TkRoundTask tkRoundTask : tkRoundTaskList) {
            TkRoundPlan tkRoundPlan = tkRoundPlanService.selectByPrimaryKey(tkRoundTask.getRoundPlanId());
            if (tkRoundPlan != null) {
                tkRoundTask.setPeriodType(tkRoundPlan.getPeriodType());
                tkRoundTask.setMatterId(tkRoundPlan.getMatterId());
                tkRoundTask.setMatterName(tkRoundPlan.getMatterName());
                tkRoundTask.setTime(tkRoundPlan.getStartDate());
                tkRoundTask.setEndTime(tkRoundPlan.getEndDate());
            }
        }
        int recordCount = tkRoundTaskService.countByExample(tkRoundTaskExample);

        // 分页
        ZQTPageModel zqtongPageListResult = new ZQTPageModel();
        zqtongPageListResult.setItemList(tkRoundTaskList);
        //当前页
        zqtongPageListResult.setCurPage(recordCount == 0 ? 0 : pageNum);
        //总页数
        int totalPageNum = (recordCount + pageSize - 1) / pageSize;
        zqtongPageListResult.setPageCount(totalPageNum);
        //总记录数
        zqtongPageListResult.setRecordCount(recordCount);

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

    public Date getFirstDayByMonth(int monthLater) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, monthLater);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    @ApiOperation("任务详情")
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getById(@RequestParam(required = false, value = "pageNum", defaultValue = "1") int pageNum,
                          @RequestParam(required = false, value = "pageSize", defaultValue = "5") int pageSize,
                          @RequestParam(required = false, value = "loginUserRole") String loginUserRole,
                          @RequestParam(required = false, value = "subGridCodes") String subGridCodes,
                          @RequestParam(required = false, value = "gridCode") String gridCode,
                          @PathVariable String id) {

        TkRoundTask tkRoundTask = tkRoundTaskService.selectByPrimaryKey(id);


        TkRoundPlan tkRoundPlan = tkRoundPlanService.selectByPrimaryKey(tkRoundTask.getRoundPlanId());
        tkRoundTask.setPeriodType(tkRoundPlan.getPeriodType());
        tkRoundTask.setMatterId(tkRoundPlan.getMatterId());
        tkRoundTask.setMatterName(tkRoundPlan.getMatterName());

        TkRoundSubtaskExample tkRoundSubtaskExample = new TkRoundSubtaskExample();
        TkRoundSubtaskExample.Criteria criteria = tkRoundSubtaskExample.createCriteria();
        tkRoundSubtaskExample.setOrderByClause("time");
        if (tkRoundTask == null) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "未查询到巡查任务！"));
        }
        criteria.andTaskIdEqualTo(tkRoundTask.getId());
        if (StringUtils.isNotBlank(loginUserRole)) {
            // 中心或一级看见所有
            if (loginUserRole.equals("centerman") || loginUserRole.startsWith("one")) {
                System.out.println("中心或者一级网格看见所有详情 centerman：中心；one：一级");
            }
            // 二级网格要看见子地块   subGridCodes不能为空
            else if (loginUserRole.startsWith("two")) {
                if (StringUtils.isBlank(subGridCodes)) {
                    System.out.println("粗问题了：二级网格要看见子地块   subGridCodes不能为空!!!");
                } else {
                    String[] subIds = subGridCodes.split(",");
                    List<String> gridCodes = Arrays.asList(subIds);
                    criteria.andGridIdIn(gridCodes);
                }
            }
            // 三级网格直接查
            else if (loginUserRole.startsWith("three")) {
                if (StringUtils.isNotBlank(gridCode)) {
                    criteria.andGridIdEqualTo(gridCode);
                }
            }
        }

        PageHelper.startPage(pageNum, pageSize);
        List<TkRoundSubtask> tkRoundSubtaskList = tkRoundSubtaskService.selectByExample(tkRoundSubtaskExample);
        int recordCount = tkRoundSubtaskService.countByExample(tkRoundSubtaskExample);

        //总页数
        int totalPageNum = (recordCount + pageSize - 1) / pageSize;

        Map<String, Object> result = new HashMap<>();
        tkRoundTask.setObjName(tkRoundPlan.getObjNames());
        tkRoundTask.setCreateName(tkRoundPlan.getCreateName());
        TkRoundMatterExample example = new TkRoundMatterExample();
        TkRoundMatterExample.Criteria criteria1 = example.createCriteria();
        criteria1.andSubTaskIdEqualTo(tkRoundTask.getId());
        List<TkRoundMatter> tkRoundMatters = tkRoundMatterService.selectByExample(example);
        if (tkRoundMatters.size() > 0) {
            tkRoundTask.setStandby3(tkRoundMatters.get(0).getStandby3());
        }
        tkRoundTask.setEndTime(tkRoundPlan.getEndDate());
        result.put("task", tkRoundTask);
        result.put("subList", tkRoundSubtaskList);
        result.put("curPage", pageNum);
        result.put("pageCount", totalPageNum);
        result.put("recordCount", recordCount);


        if (result != null) {
            return JSON.toJSONString(AjaxResult.build(200, "success", result));
        } else {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "查询失败！"));
        }
    }

    @ApiOperation("查第一个详情")
    @RequestMapping(value = "first", method = RequestMethod.GET)
    @ResponseBody
    public String getFirst(@RequestParam(required = false, value = "pageNum", defaultValue = "1") int pageNum,
                           @RequestParam(required = false, value = "pageSize", defaultValue = "5") int pageSize,
                           @RequestParam(required = false, value = "gridCode") String gridCode,
                           @RequestParam(required = false, value = "origin") String origin,
                           @RequestParam(required = false, value = "status") String status,
                           @RequestParam(required = false, value = "loginUserRole") String loginUserRole,
                           @RequestParam(required = false, value = "userId") String userId,
                           @RequestParam(required = false, value = "subGridCodes") String subGridCodes,
                           @RequestParam(required = false, value = "time") String time,
                           @RequestParam(required = false, value = "name") String name
    ) {
        TkRoundTaskExample tkRoundTaskExample = new TkRoundTaskExample();
        TkRoundTaskExample.Criteria criteria = tkRoundTaskExample.createCriteria();

        criteria.andIsShowEqualTo("1");
        if (time != null) {
            Date time2 = DateUtil.getDate(time, DateUtil.DATAFORMAT_STR);
            criteria.andTimeEqualTo(time2);
        }
        if (StringUtils.isNotBlank(origin)) {
            criteria.andOriginEqualTo(origin);
        }
        if (StringUtils.isNotBlank(status)) {
            criteria.andStatusLike("%" + status + "%");
        }
        if (StringUtils.isNotBlank(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (StringUtils.isNotBlank(loginUserRole) && (loginUserRole.equals("centerman") || loginUserRole.startsWith("one"))) {
            System.out.println("中心或者一级网格看见所有 ");
        } else {
            if (StringUtils.isNotBlank(userId)) {
                criteria.andUserIdsLike("%" + userId + "%");
            }
        }

        PageHelper.startPage(pageNum, pageSize);
        List<TkRoundTask> tkRoundTaskList = tkRoundTaskService.selectByExample(tkRoundTaskExample);

        if (tkRoundTaskList == null || tkRoundTaskList.size() == 0) {
            return JSON.toJSONString(AjaxResult.build(200, "success", "没数据！"));
        }

        TkRoundSubtaskExample tkRoundSubtaskExample = new TkRoundSubtaskExample();
        TkRoundSubtaskExample.Criteria criteria2 = tkRoundSubtaskExample.createCriteria();
        tkRoundSubtaskExample.setOrderByClause("time");
        if (StringUtils.isNotBlank(loginUserRole)) {
            // 中心或一级看见所有
            if ("centerman".equals(loginUserRole) || loginUserRole.startsWith("one")) {
                System.out.println("中心或者一级网格看见所有详情 centerman：中心；one：一级");
            }
            // 二级网格要看见子地块   subGridCodes不能为空
            else if (loginUserRole.startsWith("two")) {
                if (StringUtils.isBlank(subGridCodes)) {
                    System.out.println("粗问题了：二级网格要看见子地块   subGridCodes不能为空!!!");
                } else {
                    String[] subIds = subGridCodes.split(",");
                    List<String> gridCodes = Arrays.asList(subIds);
                    criteria2.andGridIdIn(gridCodes);
                }
            }
            // 三级网格直接查
            else if (loginUserRole.startsWith("three")) {
                if (StringUtils.isNotBlank(gridCode)) {
                    criteria2.andGridIdEqualTo(gridCode);
                }
            }
        }
        criteria2.andTaskIdEqualTo(tkRoundTaskList.get(0).getId());
        PageHelper.startPage(pageNum, pageSize);
        List<TkRoundSubtask> tkRoundSubtaskList = tkRoundSubtaskService.selectByExample(tkRoundSubtaskExample);
        int recordCount = tkRoundSubtaskService.countByExample(tkRoundSubtaskExample);

        //总页数
        int totalPageNum = (recordCount + pageSize - 1) / pageSize;

        Map<String, Object> result = new HashMap<>();
        result.put("task", tkRoundTaskList.get(0));
        result.put("subList", tkRoundSubtaskList);
        result.put("curPage", pageNum);
        result.put("pageCount", totalPageNum);
        result.put("recordCount", recordCount);

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