package com.ruoyi.web.controller.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.zqt.ZQTPageModel;
import com.ruoyi.system.domain.task.*;
import com.ruoyi.system.domain.task.utils.WorkMSGUtils;
import com.ruoyi.system.domain.task.vo.BsGridRegionUser;
import com.ruoyi.system.service.system.ISysRoleService;
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.*;

/**
 * @Date 2019/3/28 18:38
 * @Author GuoWei
 * @Description:
 */
@Api(tags = "工单 巡查 子任务")
@RestController
@RequestMapping("/api/task/roundSubtask")
public class RoundSubTaskController {

    @Autowired
    TkRoundSubtaskService tkRoundSubTaskService;
    @Autowired
    TkRoundTaskService tkRoundTaskService;
    @Autowired
    DiyService diyService;
    @Autowired
    TkCommonTaskService tkCommonTaskService;
    @Autowired
    TkRoundPlanService tkRoundPlanService;
    @Autowired
    private TkRoundSubtaskService tkRoundSubtaskService;
    @Autowired
    private WorkMSGUtils workMSGUtils;
    @Autowired
    private ISysRoleService sysRoleService;

    @ApiOperation("各对象类型的巡查记录统计")
    @RequestMapping(value = "subtaskNumByDXLX", method = RequestMethod.GET)
    @ResponseBody
    public String getSubTaskNumByDXLX() {
        Map<String, Object> map = diyService.getSubTaskNumByDXLX();
        return JSON.toJSONString(AjaxResult.build(200, "success", map));
    }

    @ApiOperation("某公司所有状态巡查记录的数量")
    @RequestMapping(value = "objSubtask", method = RequestMethod.GET)
    @ResponseBody
    public String getSubTaskNum(@RequestParam(required = true, value = "objId") String objId) {
        TkRoundSubtask tkRoundSubtask = new TkRoundSubtask();
//        巡查结果 0：未巡查；1：正常；2：异常；
        tkRoundSubtask.setObjId(objId);
        tkRoundSubtask.setStatus("0");

        int toDo = getNumByExample(tkRoundSubtask);

        tkRoundSubtask.setStatus("1");
        int normal = getNumByExample(tkRoundSubtask);

        tkRoundSubtask.setStatus("2");
        int accident = getNumByExample(tkRoundSubtask);

        Map<String, Object> map = new HashMap<>();
//        未巡查
        map.put("toDo", toDo);
//        正常
        map.put("normal", normal);
//        异常
        map.put("accident", accident);
//        已巡查
        map.put("done", normal + accident);

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

    public int getNumByExample(TkRoundSubtask tkRoundSubtask) {
        TkRoundSubtaskExample tkRoundsubTaskExample = new TkRoundSubtaskExample();
        TkRoundSubtaskExample.Criteria criteria = tkRoundsubTaskExample.createCriteria();

        if (StringUtils.isNotBlank(tkRoundSubtask.getObjId())) {
            criteria.andObjIdEqualTo(tkRoundSubtask.getObjId());
        }
        if (StringUtils.isNotBlank(tkRoundSubtask.getStatus())) {
            criteria.andStatusEqualTo(tkRoundSubtask.getStatus());
        }

        int num = tkRoundSubTaskService.countByExample(tkRoundsubTaskExample);
        return num;
    }

    @ApiOperation("某人某月巡查次数")
    @RequestMapping(value = "subtaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String getSubTaskNum(@RequestParam(required = false, value = "id") String id,
                                @RequestParam(required = false, value = "time") String time,
                                @RequestParam(required = false, value = "year") Integer year,
                                @RequestParam(required = false, value = "month") Integer month) {
        TkRoundSubtaskExample tkRoundsubTaskExample = new TkRoundSubtaskExample();
        TkRoundSubtaskExample.Criteria criteria = tkRoundsubTaskExample.createCriteria();

        if (year != null && month != null) {
            if (month < 10) {
                time = year + "-0" + month;
            } else {
                time = year + "-" + month;
            }
        }
        Date time2 = DateUtil.getDate(time, DateUtil.YYYY_MM_DATAFORMAT_STR);
        criteria.andUpdateTimeGreaterThanOrEqualTo(time2);
        Calendar c = Calendar.getInstance();
        c.setTime(time2);
        c.add(Calendar.MONTH, 1);    //利用Calendar 实现 Date日期+1天
        criteria.andUpdateTimeLessThan(c.getTime());
        criteria.andUpdateByEqualTo(id);

        List<TkRoundSubtask> tkRoundSubtaskList = tkRoundSubTaskService.selectByExample(tkRoundsubTaskExample);

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

    /**
     * 根据任务时间范围和企业对象ID获取巡查记录列表
     * 根据巡查对象和发布时间段，分页查询巡查记录的列表的接口（条件：按发布时间段、巡查对象id、来源、
     *
     * @param status 巡查状态： 0：未巡查；1：正常；2：异常；3：已巡查）
     * @return
     */
    @ApiOperation("根据任务时间范围和企业对象ID获取巡查记录列表")
    @RequestMapping(value = "roundSubtask", method = RequestMethod.GET)
    @ResponseBody
    public String getList(@RequestParam(required = false, value = "pageNum", defaultValue = "1") int pageNum,
                          @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize,
                          @RequestParam(required = true, value = "objId") String objId,
                          @RequestParam(required = false, value = "startTime") String startTime,
                          @RequestParam(required = false, value = "origin") String origin,
                          @RequestParam(required = false, value = "status") String status,
                          @RequestParam(required = false, value = "endTime") String endTime
    ) {

        PageHelper.startPage(pageNum, pageSize);
        List<TkRoundSubtask> tkRoundSubTaskList = diyService.selectByParam(objId, startTime, endTime, origin, status, pageNum, pageSize);
        for (TkRoundSubtask tkRoundSubtask : tkRoundSubTaskList) {
            TkRoundTask tkRoundTask = tkRoundTaskService.selectByPrimaryKey(tkRoundSubtask.getTaskId());
            TkRoundPlan tkRoundPlan = tkRoundPlanService.selectByPrimaryKey(tkRoundTask.getRoundPlanId());
            tkRoundSubtask.setPeriodType(tkRoundPlan.getPeriodType());
            tkRoundSubtask.setMatterId(tkRoundPlan.getMatterId());
            // 关联的日常任务
            TkCommonTaskExample commonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria criteria1 = commonTaskExample.createCriteria();
            criteria1.andRoundSubtaskIdEqualTo(tkRoundSubtask.getId());
            List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(commonTaskExample);
            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("待延时");
                }
            }

            tkRoundSubtask.setTkCommonTask(tkCommonTasks.size() > 0 ? tkCommonTasks.get(0) : null);
        }
        int recordCount = diyService.selectByParam(objId, startTime, endTime, origin, status, null, null).size();

        // 分页
        ZQTPageModel zqtongPageListResult = new ZQTPageModel();
        zqtongPageListResult.setItemList(tkRoundSubTaskList);
        //当前页
        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));
    }

    @ApiOperation("催办")
    @RequestMapping(value = "cuiBan", method = RequestMethod.POST)
    @ResponseBody
    public String CuiBan(@RequestBody TkRoundTask param) {
        try {

            String AssignedUserId = "";//周云聪
            String AssignedUserName = "";//周云聪|

            Map<String, String> map = getAdmin();
            AssignedUserId = map.get("AssignedUserId");
            AssignedUserName = map.get("AssignedUserName");

            TkRoundTask task = tkRoundTaskService.selectByPrimaryKey(param.getId());
            String[] ids = task.getUserIds().split(",");
            List<String> idList = Arrays.asList(ids);

            String body = "" + param.getName() + " 提示您有巡查任务（" + task.getName() + "）尚未完成，请及时处理！";

            workMSGUtils.sendMsg(AssignedUserId, AssignedUserName, idList, body, null, null);
        } catch (Exception e) {
            return JSON.toJSONString(AjaxResult.build(500, "fail", "催办失败"));
        }

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

    @ApiOperation("开始巡查")
    @PatchMapping
    @ResponseBody
    public String patch(@RequestBody TkRoundSubtask tkRoundSubtask) {
        Integer result = null;

        // 第一次保存 记录初始结果
        TkRoundSubtask oldTkRoundSubtask = tkRoundSubtaskService.selectByPrimaryKey(tkRoundSubtask.getId());
        if (StringUtils.isBlank(oldTkRoundSubtask.getCode())) {
            tkRoundSubtask.setResult(tkRoundSubtask.getStatus());
        }
        result = diyService.saveSubtask(tkRoundSubtask);

        if (result == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "保存失败！"));
        }

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

    @ApiOperation("子任务详情（这里的id也可以传查询编号code）")
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getById(@PathVariable String id) {

        TkRoundSubtaskExample example = new TkRoundSubtaskExample();
        TkRoundSubtaskExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);

        TkRoundSubtaskExample.Criteria criteriaCode = example.createCriteria();
        criteriaCode.andCodeEqualTo(id);

        example.or(criteriaCode);
        TkRoundSubtask tkRoundSubtask = tkRoundSubtaskService.selectFirstByExampleWithBLOBs(example);
        TkRoundTask tkRoundTask = tkRoundTaskService.selectByPrimaryKey(tkRoundSubtask.getTaskId());

        // 关联的日常任务
        TkCommonTaskExample commonTaskExample = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteria1 = commonTaskExample.createCriteria();
        criteria1.andRoundSubtaskIdEqualTo(tkRoundSubtask.getId());
        List<TkCommonTask> tkCommonTasks = tkCommonTaskService.selectByExample(commonTaskExample);
        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("待延时");
            }
        }

        String matterId = diyService.getMatterId(tkRoundSubtask.getId());

        Map<String, Object> result = new HashMap<>();
        tkRoundSubtask.setObjCode(null);
        result.put("tkRoundSubtask", tkRoundSubtask);
        result.put("tkCommonTask", tkCommonTasks.size() > 0 ? tkCommonTasks.get(0) : null);
        result.put("matterId", matterId);
        result.put("taskName", tkRoundTask.getName());

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

    // 获取当前政府管理员
    private Map<String, String> getAdmin() {
        //指派人id
        String AssignedUserId = "";
        //指派人姓名
        String AssignedUserName = "";

        AjaxResult result = new AjaxResult();
        sysRoleService.getUserByRoleCode("centerman", result);
        if (result.isSuccess()) {
            JSONArray objects = JSONArray.parseArray(JSONObject.toJSONString(result.get("data")));
            //寻找管理员 如果有管理员就可以自行指派
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObject = JSONObject.parseObject(objects.get(i).toString());
                if (jsonObject != null && jsonObject.get("ylzd2") != null) {
                    if (jsonObject.get("ylzd2").toString().equals("1")) {
                        AssignedUserId = jsonObject.getString("userId");
                        AssignedUserName = "管理员";
                    }
                }
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("AssignedUserId", AssignedUserId);
        map.put("AssignedUserName", AssignedUserName);
        return map;
    }
}
