package com.ruoyi.system.service.task.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.zqt.ZQTHttpHelper;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.vo.GridWgBean;
import com.ruoyi.system.domain.task.*;
import com.ruoyi.system.domain.task.dto.TaskCommonParams;
import com.ruoyi.system.domain.task.utils.WorkMSGUtils;
import com.ruoyi.system.domain.task.vo.LeaderPojo;
import com.ruoyi.system.domain.task.vo.UserPojo;
import com.ruoyi.system.listener.MyBaseService;
import com.ruoyi.system.mapper.task.TkCommonTaskMapper;
import com.ruoyi.system.mapper.task.ext.TkCommonTaskExtMapper;
import com.ruoyi.system.service.BaseServiceImpl;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.system.service.grid.GridRegionUserService;
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 org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author Cesar
 * @date ${cTime}
 * @desc TkCommonTaskService实现
 */
@Service
@MyBaseService
public class TkCommonTaskServiceImpl extends BaseServiceImpl<TkCommonTaskMapper, TkCommonTask, TkCommonTaskExample> implements TkCommonTaskService {

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

    @Autowired
    TkCommonTaskExtMapper tkCommonTaskExtMapper;

    @Autowired
    TkCommonTaskDynamicService tkCommonTaskDynamicService;

    @Autowired
    TkCommonAssignedService tkCommonAssignedService;

    @Autowired
    TkCommonReportService tkCommonReportService;

    @Autowired
    TkCommonLeaderService tkCommonLeaderService;

    @Autowired
    private GridRegionService gridRegionService;

    @Autowired
    private GridRegionUserService gridRegionUserService;

    @Autowired
    private TkCommonXietiaoService tkCommonXietiaoService;
    @Autowired
    private TkCommonQianpiService tkCommonQianpiService;
    @Autowired
    private TkCommonReceiveService tkCommonReceiveService;
    @Resource
    private TkRoundSubtaskService tkRoundSubtaskService;

    @Autowired
    private TkWorkService tkWorkService;

    @Autowired
    private WorkMSGUtils workMSGUtils;

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

    @Value("${app.sms.switch}")
    private boolean smsswitch;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysDeptService deptService;

    /**
     * 任务发布
     *
     * @param tkCommonTask
     * @return
     */
    @Transactional
    public int saveTask(TkCommonTask tkCommonTask, TkCommonReport tkCommonReport, List<GridItemDaily> itemDailyList, AjaxResult result, TkCommonAssigned tkCommonAssigned,AjaxResult result2) {

        //发布日常任务
        if (this.insert(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        if (tkCommonTask.getHandleType() != 0) {//不为自动指派  则是上报上级 上报中心 这要保存上报表
            if (tkCommonReportService.insert(tkCommonReport) == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                return 0;
            }
        }
        //自行处理  保存指派表  自己指派给自己
        if (tkCommonAssigned != null) {
            if (tkCommonAssignedService.insert(tkCommonAssigned) == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                return 0;
            }
            tkCommonTask.setAssignedUserId(tkCommonTask.getReleaseUserId());
            tkCommonTask.setAssignedUserName(tkCommonTask.getReleaseUserName());
            tkCommonTask.setPerformUserId(tkCommonTask.getReleaseUserId());
            tkCommonTask.setPerformUserName(tkCommonTask.getReleaseUserName());
            this.updateByPrimaryKey(tkCommonTask);
        }

        //保存操作记录
        if (saveDynamic(tkCommonTask.getId(), tkCommonTask.getReleaseUserName(), tkCommonTask.getLoginUserGrid(), tkCommonTask.getReleaseTime(), "发布了工作任务", null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        //自行指派
        if (itemDailyList.size() > 0) {
            //有数据 则需要进行自行指派了。
            //获取到了指派人信息
            if (result == null) {
                return 1;
            }
            if (result.isSuccess()) {
                JSONArray objects = JSONArray.parseArray(JSONObject.toJSONString(result.get(AjaxResult.DATA_TAG)));
                String AssignedUserId = "";//指派人id
                String AssignedUserName = "";//指派人姓名
                String wgCode = "";//指派type
                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 = jsonObject.getString("ylzd1");
                            wgCode = jsonObject.getString("wgId");
                        }
                    }

                }
                if (AssignedUserId.equals("") || AssignedUserName.equals("") || wgCode.equals("")) {//没有找到管理员
                    return 1;
                }

                GridItemDaily itemDaily = itemDailyList.get(0);
                //bsRcsxb.getSxmc();//事项名称
                String performUserName = itemDaily.getZyccbm();//分管领导   执行人
                String performUserId = itemDaily.getYlzd2();//执行人id
                if (performUserName == null || performUserName.equals("")) {
                    return 1;
                }
                if (performUserId == null || performUserId.equals("")) {
                    return 1;
                }
                String clsx = itemDaily.getClsx();//处理时限
                if (StringUtils.isEmpty(clsx)) {
                    clsx = "4";
                }
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar c = Calendar.getInstance();
                //System.out.println("当前日期:"+sf.format(c.getTime()));
                c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(clsx));
                //System.out.println("增加一天后日期:"+sf.format(c.getTime()));

                tkCommonTask.setTkStatus(12);//任务指派
                tkCommonTask.setAssignedEndTime(c.getTime());//完成期限
                tkCommonTask.setAssignedUserId(AssignedUserId);
                tkCommonTask.setAssignedUserName(AssignedUserName);

                TkCommonAssigned TkCommonAssigned = new TkCommonAssigned();//任务指派实体类
                TkCommonAssigned.setId(UUID.randomUUID().toString());
                TkCommonAssigned.setCommonTkId(tkCommonTask.getId());
                TkCommonAssigned.setAssignedUserId(AssignedUserId);//指派人id
                TkCommonAssigned.setAssignedUserName(AssignedUserName);//指派人姓名
                TkCommonAssigned.setAssignedEndTime(c.getTime());
                TkCommonAssigned.setAssignedRole(Integer.parseInt(tkCommonTask.getStandby2()));//指派人角色等级
                TkCommonAssigned.setBeassignedUserId(performUserId);//被指派人用户id
                TkCommonAssigned.setBeassignedUserName(performUserName);//被指派人用户名
                TkCommonAssigned.setBeassignedRole(Integer.parseInt("3"));//被指派人角色等级   !!!!!!!!投机  写死  领导指派查询用到这个字段
                TkCommonAssigned.setCreateTime(new Date());
                TkCommonAssigned.setAssignedStatus(1);//没数据就设为 1


                //获取指派人
                List<GridRegion> assignedWg = getWgInfoByUserId(tkCommonTask, wgCode);
                if (assignedWg.size() == 0) {
                    return 1;
                }

                //根据执行人id获取网格id
                GridRegionUserExample gridRegionUserExample = new GridRegionUserExample();
                GridRegionUserExample.Criteria criteria1 = gridRegionUserExample.createCriteria();
                criteria1.andIsValidEqualTo("1");
                criteria1.andUserIdEqualTo(performUserId);
                List<GridRegionUser> gridRegionUsers = gridRegionUserService.selectByExample(gridRegionUserExample);
                if (gridRegionUsers.size() == 0) {
                    return 1;
                }
                // 根据网格id获取网格名称
                List<GridRegion> performWg = getWgInfoByUserId(tkCommonTask, gridRegionUsers.get(0).getWgId());
                if (performWg.size() == 0) {
                    return 1;
                }

                if (smsEnable) {//正式环境执行下面代码
                    //发送通知
                    List<String> beassignedUserIds = new ArrayList<>();
                    beassignedUserIds.add(performUserId);
                    String body = tkCommonTask.getTkName() + "已被指派";
                    workMSGUtils.sendMsg(AssignedUserId, AssignedUserName, beassignedUserIds,body, tkCommonTask.getMatterType(), tkCommonTask.getId());
                }


                //更改日常任务（任务指派数据保存）
                if (this.updateByPrimaryKey(tkCommonTask) == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                    return 0;
                }

                //保存指派表数据
                if (tkCommonAssignedService.insert(TkCommonAssigned) == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                    return 0;
                }

                //塞入指派信息
                TkCommonTaskDynamic tkCommonTaskDynamic = getTkCommonTaskDynamic(tkCommonTask.getId(), AssignedUserName, assignedWg.get(0).getWgName(), performUserName, performWg.get(0).getWgName());
                if (tkCommonTaskDynamicService.insert(tkCommonTaskDynamic) == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                    return 0;
                }

                //正式环境执行下面代码
                if (smsEnable) {
                    //创建待办
                    List<String> beassignedUserIds2 = new ArrayList<String>();
                    beassignedUserIds2.add(TkCommonAssigned.getBeassignedUserId());
                    String workName = tkCommonTask.getTkName() + "待接收";
                    String ret = workMSGUtils.createWork(tkCommonTask, AssignedUserId, beassignedUserIds2, workName);
                    if (ret != null) {
                        JSONObject jo = JSONObject.parseObject(ret);
                        System.out.println("-------" + jo);
                        if (jo.get("msg").equals("success")) {//接口访问成功
                            JSONObject data = JSONObject.parseObject(jo.get("data").toString());
                            TkWork tkWork = new TkWork();
                            tkWork.setId(UUID.randomUUID().toString());
                            tkWork.setCommonTaskId(tkCommonTask.getId());
                            tkWork.setWorkId(data.get("workId").toString());
                            tkWork.setCreateTime(new Date());
                            if (tkWorkService.insert(tkWork) == 0) {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                                return 0;
                            }
                        }
                    }
                }

            }

        } else {
            //走到这边 可能是上报中心以后不需要自动指派  也可能是三级上报上级//上报中心
            List<String> beassignedUserIds = new ArrayList<String>();
            //上报中心
            if (tkCommonTask.getHandleType() == 2) {
                if (daizhipai(tkCommonTask,result2, beassignedUserIds)) return 0;
            }


            //三级上报上级
            if (tkCommonTask.getHandleType() == 1 && tkCommonTask.getLoginUserRole().equals("3")) {
                if (daizhipai(tkCommonTask,result2, beassignedUserIds)) return 0;
            }
        }

        if (smsEnable && StringUtils.isNotBlank(tkCommonTask.getQprIds())) {
            //发送签批人通知
            List<String> qprIds = Arrays.asList(tkCommonTask.getQprIds().split(","));
            List<SysUser> qprUsers = sysUserService.listByIds(qprIds);

            for (SysUser qprUser : qprUsers) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("name", qprUser.getNickName());
                map.put("address", tkCommonTask.getBelongGrid());
                map.put("taskId", tkCommonTask.getId());
                map.put("taskName", tkCommonTask.getTkName());
                workMSGUtils.sendSms(qprUser,map);
            }
        }
        return 1;
    }

    //待指派
    private boolean daizhipai(TkCommonTask tkCommonTask,AjaxResult result2, List<String> beassignedUserIds) {
        if (tkCommonTask.getLoginUserRole().equals("3")) {
            Map<String, Object> map = new HashMap<>();
            String wgCode = tkCommonTask.getWgCode().substring(0, 12);
            map.put("wgCode", wgCode);
            map.put("roleCode", "twogrid");
            beassignedUserIds = tkCommonTaskExtMapper.getUserByRoleCodeAndWgCode(map);
        } else {
            if (result2 != null) {
                Object data = result2.get(AjaxResult.DATA_TAG);
                if (data != null) {
                    String s = JSONObject.toJSONString(data);
                    JSONArray ja = JSONArray.parseArray(s);
                    if (ja.size() > 0) {
                        for (int i = 0; i < ja.size(); i++) {
                            beassignedUserIds.add(((JSONObject) ja.get(i)).getString("userId"));
                        }
                    }
                }
            }
        }
        //正式环境执行下面代码
        if (smsEnable) {
            //发送通知
            String body = tkCommonTask.getTkName() + "上报";
            workMSGUtils.sendMsg(tkCommonTask.getReleaseUserId(), tkCommonTask.getReleaseUserName(), beassignedUserIds, body, tkCommonTask.getMatterType(), tkCommonTask.getId());

            //不自动指派  直接创建待办
            String workName = tkCommonTask.getTkName() + "待指派";
            String ret = workMSGUtils.createWork(tkCommonTask, tkCommonTask.getReleaseUserId(), beassignedUserIds, workName);
            if (ret != null) {
                JSONObject jo = JSONObject.parseObject(ret);
                System.out.println("-------" + jo);
                if (jo.get("msg").equals("success")) {//接口访问成功
                    JSONObject data = JSONObject.parseObject(jo.get("data").toString());
                    TkWork tkWork = new TkWork();
                    tkWork.setId(UUID.randomUUID().toString());
                    tkWork.setCommonTaskId(tkCommonTask.getId());
                    tkWork.setWorkId(data.get("workId").toString());
                    tkWork.setCreateTime(new Date());
                    if (tkWorkService.insert(tkWork) == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                        return true;
                    }
                }
            }
        }

        return false;
    }

    private List<GridRegion> getWgInfoByUserId(TkCommonTask tkCommonTask, String wgCode) {
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");
        if (StringUtils.isNotEmpty(wgCode)) {
            criteria.andWgCodeEqualTo(wgCode);
        }
        example.setOrderByClause(" update_time asc ");
        return gridRegionService.selectByExampleWithBLOBs(example);
    }


    /**
     * 上报上级
     *
     * @param tkCommonTask
     * @param tkCommonReport
     * @return
     */
    @Transactional
    @Override
    public int reportLeader(TkCommonTask tkCommonTask, TkCommonReport tkCommonReport, String loginUserName, String loginUserGrid, String loginUserId, AjaxResult result2) {

        //修改任务信息
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        //保存上报上级数据
        if (tkCommonReportService.insert(tkCommonReport) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        //保存操作记录
        if (saveDynamic(tkCommonTask.getId(), loginUserName, loginUserGrid, null, "上报任务", null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        //正式环境执行代码
        if (smsEnable) {
            //先改变最后一条待办的状态
            //--------------------修改待办任务状态------------------------
            TkWorkExample tkWorkExample = new TkWorkExample();
            TkWorkExample.Criteria criteria2 = tkWorkExample.createCriteria();
            criteria2.andCommonTaskIdEqualTo(tkCommonTask.getId());
            tkWorkExample.setOrderByClause("create_time desc");
            List<TkWork> tkWorks = tkWorkService.selectByExample(tkWorkExample);
            if (tkWorks.size() > 0) {
                workMSGUtils.updateWork(loginUserId, tkWorks.get(0).getWorkId(), 1);
            }
            //--------------------修改待办任务状态-------------------
        }


        //发送待办 发送通知
        List<String> beassignedUserIds = new ArrayList<String>();
        if (daizhipai(tkCommonTask, result2, beassignedUserIds))
            return 0;

        return 1;
    }

    //自行处理接口
    //上报上级后的自行处理接口
    @Transactional
    @Override
    public int solveBySelf(TkCommonTask tkCommonTask, String loginUserName, String loginUserBelongGrid, TkCommonAssigned TkCommonAssigned) {
        //更改日常任务（任务指派数据保存）
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        //保存指派表数据
        if (tkCommonAssignedService.insert(TkCommonAssigned) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        //操作历史
        TkCommonTaskDynamic tkCommonTaskDynamic = new TkCommonTaskDynamic();
        tkCommonTaskDynamic.setId(UUID.randomUUID().toString());
        tkCommonTaskDynamic.setCommonTkId(tkCommonTask.getId());
        tkCommonTaskDynamic.setName(loginUserName);//当前登录人
        tkCommonTaskDynamic.setAddress(loginUserBelongGrid);
        tkCommonTaskDynamic.setNote("自行处理任务");
        tkCommonTaskDynamic.setTkTime(new Date());
        tkCommonTaskDynamic.setCreateTime(new Date());
        int a = tkCommonTaskDynamicService.insert(tkCommonTaskDynamic);
        if (a == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        return 1;
    }

    @Override
    public TkCommonTaskDynamic getTkCommonTaskDynamic(String id, String loginUserName, String loginUserBelongGrid, String performUserName, String performUserGrid) {
        //保存操作记录
        //【邮塘村】周茂将任务指派给 【邮塘村】李欣
        TkCommonTaskDynamic tkCommonTaskDynamic = new TkCommonTaskDynamic();
        tkCommonTaskDynamic.setId(UUID.randomUUID().toString());
        tkCommonTaskDynamic.setCommonTkId(id);
        tkCommonTaskDynamic.setName(loginUserName);//当前登录人
        tkCommonTaskDynamic.setAddress(loginUserBelongGrid);
        tkCommonTaskDynamic.setNote("将任务指派给【" + performUserGrid + "】" + performUserName);
        tkCommonTaskDynamic.setTkTime(new Date());
        tkCommonTaskDynamic.setCreateTime(new Date());
        return tkCommonTaskDynamic;
    }


    @Override
    public PageInfo<TkCommonTask> selectList(TaskCommonParams map, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<TkCommonTask> list = tkCommonTaskExtMapper.selectList(map);
        return new PageInfo<TkCommonTask>(list);
    }

    @Override
    public List<TkCommonTask> selectListByExport(TaskCommonParams map) {
        List<TkCommonTask> list = tkCommonTaskExtMapper.selectList(map);
        for (TkCommonTask tkCommonTask : list) {
            //按userId查询处置单位
            if (StringUtils.isNotBlank(tkCommonTask.getPerformUserId())){
                List<SysRole> roles = roleService.selectRolesByUserId(tkCommonTask.getPerformUserId());
                if (CollectionUtils.isNotEmpty(roles)){
                    if (roles.stream().anyMatch(new Predicate<SysRole>() {
                        @Override
                        public boolean test(SysRole sysRole) {
                            return sysRole.getRoleName().contains("三级网格员");
                        }
                    })){
                        //查所属网格
                        List<GridRegionUser> gridRegionUsers = gridRegionUserService.getPermissionWgCodes(tkCommonTask.getPerformUserId());
                        if (CollectionUtils.isNotEmpty(gridRegionUsers)){
                            Map<String,String> gridRegions = gridRegionService.getMapByWgCodes(gridRegionUsers.stream().map(GridRegionUser::getWgId).collect(Collectors.toList()));
                            if (CollectionUtils.isNotEmpty(gridRegions)){
                                tkCommonTask.setPerformUnit(
                                        gridRegions.values().stream().collect(Collectors.joining(","))
                                );
                            }
                        }
                    }else {
                        //查所属部门
                        SysUser sysUser = sysUserService.selectUserById(tkCommonTask.getPerformUserId());
                        if (sysUser!=null && sysUser.getDept()!=null){
                            tkCommonTask.setPerformUnit(sysUser.getDept().getDeptName());
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> bigWindowWGCount(Map map) {
        return tkCommonTaskExtMapper.bigWindowWGCount(map);
    }

    @Override
    public List<Map<String, Object>> taskCountByComeFrom(Map map) {
        return tkCommonTaskExtMapper.taskCountByComeFrom(map);
    }

    @Override
    public List<Map<String, Object>> taskCountByBaseId(Map map) {
        return tkCommonTaskExtMapper.taskCountByBaseId(map);
    }

    @Override
    public List<Map<String, Object>> selectMatterRank(Map map) {
        return tkCommonTaskExtMapper.selectMatterRank(map);
    }

    @Override
    public List<Map<String, Object>> selectMatterRankThreeType(Map map) {
        return tkCommonTaskExtMapper.selectMatterRankThreeType(map);
    }

    @Override
    public boolean checkCuiBan(String id) {
        int count = tkCommonTaskExtMapper.checkCuiBan(id);

        return count > 0 ? true : false;
    }

    @Override
    public int saveDynamic2(String id, String userName, String address, Date time, String node, String cuiBanReason) {
        return saveDynamic(id, userName, address, time, node, null, cuiBanReason, null);
    }

    @Override
    public int panding(TkCommonTask tkCommonTask, String userName, String address, Date time, String node, String reason) {
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        if (saveDynamicByType(tkCommonTask.getId(), userName, address, time, node, reason) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        if (smsswitch) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", tkCommonTask.getReleaseUserName());
            map.put("address", address);
            map.put("taskName", tkCommonTask.getTkName());
            //根据用户id获取用户信息
            SysUser userInfo = sysUserService.selectUserById(tkCommonTask.getReleaseUserId());
            workMSGUtils.sendPanDingDXSMS(userInfo, map);
        }

        return 1;
    }


    @Override
    public int pingfen(TkCommonTask tkCommonTask, String userName, String address, Date time, String node, String reason) {
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        if (saveDynamicByType(tkCommonTask.getId(), userName, address, time, node, reason) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        return 1;
    }

    @Override
    @Transactional
    public int agreeTask(TkCommonTask tkCommonTask, String id, String userName, String address, Date time, String node, boolean isAgree, String returnReason, String loginUserId) {
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        if (saveDynamic(id, userName, address, time, node, returnReason, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        //--------------------修改待办任务状态------------------------
        //不管接受还是拒绝 都要改变下待办任务的状态
        TkCommonAssignedExample tkAssEx = new TkCommonAssignedExample();
        TkCommonAssignedExample.Criteria criteria = tkAssEx.createCriteria();
        criteria.andCommonTkIdEqualTo(id);
        tkAssEx.setOrderByClause("assigned_status desc");
        List<TkCommonAssigned> tkCommonAssigneds = tkCommonAssignedService.selectByExample(tkAssEx);

        TkWorkExample tkWorkExample = new TkWorkExample();
        TkWorkExample.Criteria criteria2 = tkWorkExample.createCriteria();
        criteria2.andCommonTaskIdEqualTo(tkCommonTask.getId());
        tkWorkExample.setOrderByClause("create_time desc");
        List<TkWork> tkWorks = tkWorkService.selectByExample(tkWorkExample);
        if (smsEnable) {
            if (tkWorks.size() > 0) {
                workMSGUtils.updateWork(tkCommonAssigneds.get(0).getBeassignedUserId(), tkWorks.get(0).getWorkId(), 1);
            }
        }
        //--------------------修改待办任务状态-------------------

        if (!isAgree) {
            //退回


            if (smsEnable) {
                //发送通知
                String body = tkCommonTask.getTkName() + "任务申请退回";
                List<String> userIds = new ArrayList<String>();
                userIds.add(tkCommonTask.getAssignedUserId());
                workMSGUtils.sendMsg(loginUserId, userName, userIds, body, tkCommonTask.getMatterType(), tkCommonTask.getId());
                //创建待办任务---------------
                List<String> beassignedUserIds = new ArrayList<String>();
                beassignedUserIds.add(tkCommonTask.getAssignedUserId());
                String workName = tkCommonTask.getTkName() + "申请退回处理";
                String ret = workMSGUtils.createWork(tkCommonTask, loginUserId, beassignedUserIds, workName);
                if (ret != null) {
                    JSONObject jo = JSONObject.parseObject(ret);
                    System.out.println("-------" + jo);
                    if (jo.get("msg").equals("success")) {//接口访问成功
                        JSONObject data = JSONObject.parseObject(jo.get("data").toString());
                        TkWork tkWork = new TkWork();
                        tkWork.setId(UUID.randomUUID().toString());
                        tkWork.setCommonTaskId(tkCommonTask.getId());
                        tkWork.setWorkId(data.get("workId").toString());
                        tkWork.setCreateTime(new Date());
                        if (tkWorkService.insert(tkWork) == 0) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                            return 0;
                        }
                    }
                }
            }


        }

        return 1;
    }

    @Override
    @Transactional
    public int agreeBack(TkCommonTask tkCommonTask, String id, String userName, String address, Date time, String node, boolean isAgree, String returnReason, String loginUserId) {
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        if (saveDynamic(id, userName, address, time, node, returnReason, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        TkCommonAssignedExample tkAssEx = new TkCommonAssignedExample();
        TkCommonAssignedExample.Criteria criteria = tkAssEx.createCriteria();
        criteria.andCommonTkIdEqualTo(id);
        tkAssEx.setOrderByClause("assigned_status desc");
        List<TkCommonAssigned> tkCommonAssigneds = tkCommonAssignedService.selectByExample(tkAssEx);

        if (isAgree) {//退回

            if (tkCommonAssignedService.deleteByStringPrimaryKey(tkCommonAssigneds.get(0).getId()) == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                return 0;
            }


        }

        return 1;
    }


    /**
     * 开始任务
     *
     * @param tkCommonTask
     * @param id
     * @param userName
     * @param address
     * @param time
     * @param node
     * @param loginUserRole
     * @param loginUserId
     * @param result2
     * @return
     */
    @Override
    @Transactional
    public int startTask(TkCommonTask tkCommonTask, String id, String userName, String address, Date time, String node, String loginUserRole, String loginUserId, AjaxResult result2, String loginWgCode, String level) {
        //int i=this.updateByPrimaryKey(tkCommonTask);
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        //保存操作记录
        if (saveDynamic(id, userName, address, time, node, null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        Map<String, Object> map = new HashMap<>();
        if (level != null && level.equals("3")) {
            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andWgCodeEqualTo(loginWgCode);
            List<GridRegion> bsWgxxbList = gridRegionService.selectByExampleWithBLOBs(example);
            if (bsWgxxbList != null && bsWgxxbList.size() > 0) {
                String parentWGId = bsWgxxbList.get(0).getWgParentId();
                map.put("wgCode", parentWGId);
                map.put("roleCode", "twogrid");
            }
        } else {
            map.put("wgCode", loginWgCode);
            map.put("roleCode", "twogrid");
        }

        List<String> beassignedUserIds = tkCommonTaskExtMapper.getUserByRoleCodeAndWgCode(map);
        if (smsEnable) {
            //不自动指派  直接创建待办
            String workName = tkCommonTask.getTkName() + "待指派核查";
            String ret = workMSGUtils.createWork(tkCommonTask, loginUserId, beassignedUserIds, workName);
            if (ret != null) {
                JSONObject jo = JSONObject.parseObject(ret);
                System.out.println("-------" + jo);
                if (jo.get("msg").equals("success")) {//接口访问成功
                    JSONObject data = JSONObject.parseObject(jo.get("data").toString());
                    TkWork tkWork = new TkWork();
                    tkWork.setId(UUID.randomUUID().toString());
                    tkWork.setCommonTaskId(tkCommonTask.getId());
                    tkWork.setWorkId(data.get("workId").toString());
                    tkWork.setCreateTime(new Date());
                    if (tkWorkService.insert(tkWork) == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                        return 0;
                    }
                }
            }
        }
        return 1;
    }


    //指派核查人
    @Override
    @Transactional
    public int verificationPerson(TkCommonTask tkCommonTask, String id, String userName, String address, Date time, String node, String loginUserId) {
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        //保存操作记录
        if (saveDynamic(id, userName, address, time, node, null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        if (smsEnable) {
            //--------------------修改待办任务状态------------------------

            TkWorkExample tkWorkExample = new TkWorkExample();
            TkWorkExample.Criteria criteria2 = tkWorkExample.createCriteria();
            criteria2.andCommonTaskIdEqualTo(tkCommonTask.getId());
            tkWorkExample.setOrderByClause("create_time desc");
            List<TkWork> tkWorks = tkWorkService.selectByExample(tkWorkExample);
            if (tkWorks.size() > 0) {
                workMSGUtils.updateWork(loginUserId, tkWorks.get(0).getWorkId(), 1);
            }
            //--------------------修改待办任务状态-------------------
            //创建待办
            List<String> beassignedUserIds = new ArrayList<String>();
            beassignedUserIds.add(tkCommonTask.getVerificationUserId());//接收人
            String workName = tkCommonTask.getTkName() + "待核查";
            String ret = workMSGUtils.createWork(tkCommonTask, loginUserId, beassignedUserIds,workName);
            if (ret != null) {
                JSONObject jo = JSONObject.parseObject(ret);
                System.out.println("-------" + jo);
                if (jo.get("msg").equals("success")) {//接口访问成功
                    JSONObject data = JSONObject.parseObject(jo.get("data").toString());
                    TkWork tkWork = new TkWork();
                    tkWork.setId(UUID.randomUUID().toString());
                    tkWork.setCommonTaskId(tkCommonTask.getId());
                    tkWork.setWorkId(data.get("workId").toString());
                    tkWork.setCreateTime(new Date());
                    if (tkWorkService.insert(tkWork) == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                        return 0;
                    }
                }
            }
        }


        return 1;
    }


    //跳过核查
    @Override
    @Transactional
    public int jumpOverHecha(TkCommonTask tkCommonTask, String id, String userName, String address, Date time, String node, String loginUserId) {
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        //保存操作记录
        if (saveDynamic(id, userName, address, time, node, null, null, tkCommonTask.getVerificationNode()) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        if (smsEnable) {
            //--------------------修改待办任务状态------------------------
            TkWorkExample tkWorkExample = new TkWorkExample();
            TkWorkExample.Criteria criteria2 = tkWorkExample.createCriteria();
            criteria2.andCommonTaskIdEqualTo(tkCommonTask.getId());
            tkWorkExample.setOrderByClause("create_time desc");
            List<TkWork> tkWorks = tkWorkService.selectByExample(tkWorkExample);
            if (tkWorks.size() > 0) {
                workMSGUtils.updateWork(loginUserId, tkWorks.get(0).getWorkId(), 1);
            }
            //--------------------修改待办任务状态-------------------
        }

        return 1;
    }

    //核查通过
    @Override
    @Transactional
    public int verificationPerson2(TkCommonTask tkCommonTask, String id, String userName, String address, Date time, String node, String loginUserId) {
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        //日常任务通过 判断是否是巡查异常跳过来的任务，如果是异常跳过来的任务则需要修改下巡查的一个状态
        if (tkCommonTask.getTkStatus() == 40) {//日常任务通过
            if (StringUtils.isNotEmpty(tkCommonTask.getRoundSubtaskId())) {
                TkRoundSubtask tkRoundSubtask = tkRoundSubtaskService.selectByPrimaryKey(tkCommonTask.getRoundSubtaskId());
                if (tkRoundSubtask != null) {
                    tkRoundSubtask.setStatus("1");
                    tkRoundSubtaskService.updateByPrimaryKey(tkRoundSubtask);
                }

            }
        }

        //保存操作记录
        if (saveDynamic(id, userName, address, time, node, null, null, tkCommonTask.getVerificationNode()) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        if (smsEnable) {
            //--------------------修改待办任务状态------------------------
            TkWorkExample tkWorkExample = new TkWorkExample();
            TkWorkExample.Criteria criteria2 = tkWorkExample.createCriteria();
            criteria2.andCommonTaskIdEqualTo(tkCommonTask.getId());
            tkWorkExample.setOrderByClause("create_time desc");
            List<TkWork> tkWorks = tkWorkService.selectByExample(tkWorkExample);
            if (tkWorks.size() > 0) {
                workMSGUtils.updateWork(loginUserId, tkWorks.get(0).getWorkId(), 1);
            }
            //--------------------修改待办任务状态-------------------
            //不要发送一个待办给需要评价的人吗？
        }
        return 1;
    }


    /**
     * 核查任务
     *
     * @param tkCommonTask
     * @param id
     * @param userName
     * @param address
     * @param time
     * @param node
     * @return
     */
    @Override
    @Transactional
    public int verificationTask(TkCommonTask tkCommonTask, String id, String userName, String address, Date time, String node) {
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        //保存操作记录
        if (saveDynamic(id, userName, address, time, node, null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        return 1;
    }


    /**
     * 任务评价
     *
     * @param tkCommonTask
     * @param id
     * @param userName
     * @param address
     * @param time
     * @param node
     * @return
     */
    @Override
    @Transactional
    public int evaluationTask(TkCommonTask tkCommonTask, String id, String userName, String address, Date time, String node) {
        int i = this.updateByPrimaryKey(tkCommonTask);
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        //保存操作记录
        if (saveDynamic(id, userName, address, time, node, null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        return 1;

    }


    /**
     * 报存指派和操作记录和发送消息
     *
     * @return 1领导指示 2 转督办
     */
    @Override
    @Transactional
    public int saveReceiveAndDynaAndMSG(LeaderPojo pojo, int type) {

        TkCommonTask tkCommonTask = this.selectByPrimaryKey(pojo.getId());
        List<UserPojo> leaders = pojo.getLeaders();
        String leaderNames = "";
        String node = saveReceiveAndBackNode(pojo.getId(), pojo.getNote(), type, leaders, leaderNames);
        //保存操作记录
        if (saveDynamicByType(pojo.getId(), pojo.getLoginUserName(), pojo.getLoginUserBelongGrid(), null, node, pojo.getNote()) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        if (smsEnable) {
            //发送通知
            String body = "";
            if (type == 1) {
                body = tkCommonTask.getTkName() + "申请领导指示";
            } else if (type == 2) {
                body = tkCommonTask.getTkName() + "工单转督办";
            }

            List<String> userIds = new ArrayList<String>();
            for (int i = 0; i < leaders.size(); i++) {
                UserPojo up = leaders.get(i);
                userIds.add(up.getUserId());
            }
            workMSGUtils.sendMsg(pojo.getLoginUserId(), pojo.getLoginUserName(), userIds, body, tkCommonTask.getMatterType(), tkCommonTask.getId());
        }

        return 1;
    }

    @Override
    public String saveReceiveAndBackNode(String id, String note, int type, List<UserPojo> leaders, String leaderNames) {
        for (int i = 0; i < leaders.size(); i++) {
            TkCommonReceive tkCommonReceive = new TkCommonReceive();
            tkCommonReceive.setId(UUID.randomUUID().toString());
            tkCommonReceive.setCommonTkId(id);
            tkCommonReceive.setStatus("0");
            tkCommonReceive.setUserId(leaders.get(i).getUserId());
            tkCommonReceive.setUserName(leaders.get(i).getUserName());
            tkCommonReceive.setType(type);//1领导指示 2转督办
            tkCommonReceive.setNote(note);
            tkCommonReceiveService.insert(tkCommonReceive);
            leaderNames += leaders.get(i).getUserName() + ",";
        }

        String node = "";
        if (type == 1) {
            node = "申请领导指示：" + leaderNames;
        } else if (type == 2) {
            node = "工单转督办：" + leaderNames;
        } else if (type == 3) {
            node = "工单指派抄送：" + leaderNames;
        }
        return node;
    }


    /**
     * 留言
     *
     * @return 1领导指示 2 转督办
     */
    @Override
    @Transactional
    public int leaveMessage(LeaderPojo pojo) {
        TkCommonTask tkCommonTask = this.selectByPrimaryKey(pojo.getId());
        List<UserPojo> leaders = pojo.getLeaders();
        String node = "留言:";
        node += pojo.getNote();

        //保存操作记录
        if (saveDynamicByType(pojo.getId(), pojo.getLoginUserName(), pojo.getLoginUserBelongGrid(), null, node, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        if (smsEnable) {
            //发送通知
            String body = "";
            body = tkCommonTask.getTkName() + "," + node;

            if (leaders == null || leaders.size() == 0) {
                return 1;
            }
            List<String> userIds = new ArrayList<String>();
            for (int i = 0; i < leaders.size(); i++) {
                UserPojo up = leaders.get(i);
                userIds.add(up.getUserId());
            }
            workMSGUtils.sendMsg(pojo.getLoginUserId(), pojo.getLoginUserName(), userIds, body, tkCommonTask.getMatterType(), tkCommonTask.getId());
        }

        return 1;
    }


    /**
     * 确认按钮的操作记录
     *
     * @return
     */
    @Override
    @Transactional
    public int querenDy(String id, String loginUserName, String loginUserBelongGrid, String node, String reason) {

        //保存操作记录
        if (saveDynamicByType(id, loginUserName, loginUserBelongGrid, null, node, reason) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        return 1;
    }

    /**
     * 转督办
     *
     * @param id
     * @param loginUserId
     * @param leaders
     * @param loginUserName
     * @param loginUserGri
     * @return
     */
    @Override
    @Transactional
    public int insertLeaders(String id, String loginUserId, JSONArray leaders, String loginUserName, String loginUserGri) {

        TkCommonTask tkCommonTask = this.selectByPrimaryKey(id);

        String leaderNames = tkCommonTask.getStandby3();//获取任务标中的督办名，隔开
        if (leaderNames == null) {
            leaderNames = "";
        }
        for (int i = 0; i < leaders.size(); i++) {
            JSONObject jo = JSONObject.parseObject(leaders.get(i).toString());
            String userId = jo.get("userId").toString();

            TkCommonLeaderExample tkCommonLeaderExample = new TkCommonLeaderExample();
            TkCommonLeaderExample.Criteria criteria = tkCommonLeaderExample.createCriteria();
            criteria.andTkIdEqualTo(id);
            criteria.andUserIdEqualTo(userId);
            int count = tkCommonLeaderService.countByExample(tkCommonLeaderExample);
            //没保存过
            if (count == 0) {
                TkCommonLeader tkCommonLeader = new TkCommonLeader();
                tkCommonLeader.setId(UUID.randomUUID().toString());
                tkCommonLeader.setTkId(id);
                tkCommonLeader.setUserId(userId);
                tkCommonLeader.setUserName(jo.get("userName").toString());
                tkCommonLeader.setCreateTime(new Date());
                if (tkCommonLeaderService.insert(tkCommonLeader) == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                    return 0;
                }
                leaderNames += jo.get("userName").toString() + ",";
            }
        }
        tkCommonTask.setStandby3(leaderNames);
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        //保存操作记录
        if (saveDynamic(id, loginUserName, loginUserGri, null, "转督办了任务", null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        if (smsEnable) {
            //发送通知
            String body = tkCommonTask.getTkName() + "已转督办";
            List<String> userIds = new ArrayList<String>();
            for (int i = 0; i < leaders.size(); i++) {
                JSONObject jo = (JSONObject) leaders.get(i);
                userIds.add(jo.getString("userId"));
            }
            workMSGUtils.sendMsg(loginUserId, loginUserName, userIds, body, tkCommonTask.getMatterType(), tkCommonTask.getId());
        }

        return 1;
    }

    /**
     * 协调协助
     *
     * @param id
     * @param loginUserId
     * @param leaders
     * @param loginUserName
     * @param loginUserGri
     * @return
     */
    @Override
    @Transactional
    public int insertXieTiao(String id, String loginUserId, JSONArray leaders, String loginUserName, String loginUserGri) {

        TkCommonTask tkCommonTask = this.selectByPrimaryKey(id);

        String xietiaoNames = "";//获取任务标中的协调协助，隔开
        for (int i = 0; i < leaders.size(); i++) {
            JSONObject jo = JSONObject.parseObject(leaders.get(i).toString());
            String userId = jo.get("userId").toString();
            TkCommonXietiao tkCommonXietiao = new TkCommonXietiao();
            tkCommonXietiao.setId(UUID.randomUUID().toString());
            tkCommonXietiao.setTkId(id);
            tkCommonXietiao.setUserId(userId);
            tkCommonXietiao.setUserName(jo.get("userName").toString());
            tkCommonXietiao.setCreateTime(new Date());
            if (tkCommonXietiaoService.insert(tkCommonXietiao) == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                return 0;
            }
            xietiaoNames += jo.get("userName").toString() + ",";
        }
        tkCommonTask.setXietiao(xietiaoNames);
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        //保存操作记录
        if (saveDynamic(id, loginUserName, loginUserGri, null, "协调" + xietiaoNames.substring(0, xietiaoNames.length() - 1) + "处理", null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        if (smsEnable) {
            //发送通知
            String body = tkCommonTask.getTkName() + "请求协调处理";
            List<String> userIds = new ArrayList<String>();
            for (int i = 0; i < leaders.size(); i++) {
                JSONObject jo = (JSONObject) leaders.get(i);
                userIds.add(jo.getString("userId"));
            }
            workMSGUtils.sendMsg(loginUserId, loginUserName, userIds,body, tkCommonTask.getMatterType(), tkCommonTask.getId());
        }

        return 1;
    }


    /**
     * 领导签批
     *
     * @param id
     * @param loginUserId
     * @param leaders
     * @param loginUserName
     * @param loginUserGri
     * @return
     */
    @Override
    @Transactional
    public int insertQianPi(String id, String note, String loginUserId, JSONArray leaders, String loginUserName, String loginUserGri) {

        TkCommonTask tkCommonTask = this.selectByPrimaryKey(id);


        TkCommonQianpi tkCommonQianpi = new TkCommonQianpi();
        tkCommonQianpi.setId(UUID.randomUUID().toString());
        tkCommonQianpi.setTkId(id);
        tkCommonQianpi.setCreateTime(new Date());
        tkCommonQianpi.setLeaderUserId(loginUserId);
        tkCommonQianpi.setLeaderUserName(loginUserName);
        tkCommonQianpi.setNote(note);
        String userId = "";
        String xietiaoNames = "";//获取任务标中的协调协助，隔开
        for (int i = 0; i < leaders.size(); i++) {
            JSONObject jo = JSONObject.parseObject(leaders.get(i).toString());
            userId += jo.get("userId").toString() + ",";
            xietiaoNames += jo.get("userName").toString() + ",";
        }
        tkCommonQianpi.setUserId(userId);
        tkCommonQianpi.setUserName(xietiaoNames);
        if (tkCommonQianpiService.insert(tkCommonQianpi) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }
        String qian = note == null ? "" : note;
        //保存操作记录
        if (saveDynamic(id, loginUserName, loginUserGri, null, loginUserName + "签批" + qian, null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        if (smsEnable) {
            //发送通知
            String body = tkCommonTask.getTkName() + "任务由" + loginUserName + "签批，内容为：" + qian;
            List<String> userIds = new ArrayList<String>();
            for (int i = 0; i < leaders.size(); i++) {
                JSONObject jo = (JSONObject) leaders.get(i);
                userIds.add(jo.getString("userId"));
            }
            workMSGUtils.sendMsg(loginUserId, loginUserName, userIds, body, tkCommonTask.getMatterType(), tkCommonTask.getId());
        }

        return 1;
    }

    /**
     * 申请延时
     *
     * @param tkCommonTask
     * @param loginUserName
     * @param loginUserGrid
     * @return
     */
    @Override
    @Transactional
    public int applyDelay(TkCommonTask tkCommonTask, String loginUserName, String loginUserGrid, String loginUserId) {

        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        //保存操作记录
        if (saveDynamic(tkCommonTask.getId(), loginUserName, loginUserGrid, null, "申请延期至：" + tkCommonTask.getStandby4(), null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        if (smsEnable) {
            //创建待办
            List<String> beassignedUserIds = new ArrayList<String>();
            beassignedUserIds.add(tkCommonTask.getAssignedUserId());//接收人
            String workName = tkCommonTask.getTkName() + "待延时";
            String ret = workMSGUtils.createWork(tkCommonTask, loginUserId, beassignedUserIds,workName);
            if (ret != null) {
                JSONObject jo = JSONObject.parseObject(ret);
                System.out.println("-------" + jo);
                if (jo.get("msg").equals("success")) {//接口访问成功
                    JSONObject data = JSONObject.parseObject(jo.get("data").toString());
                    TkWork tkWork = new TkWork();
                    tkWork.setId(UUID.randomUUID().toString());
                    tkWork.setCommonTaskId(tkCommonTask.getId());
                    tkWork.setWorkId(data.get("workId").toString());
                    tkWork.setCreateTime(new Date());
                    if (tkWorkService.insert(tkWork) == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                        return 0;
                    }
                }
            }
        }


        return 1;
    }

    /**
     * 延时同意 延时拒绝
     *
     * @param tkCommonTask
     * @param tkCommonAssigned
     * @param loginUserName
     * @param loginUserGrid
     * @return
     */
    @Override
    @Transactional
    public int agreeDelay(TkCommonTask tkCommonTask, TkCommonAssigned tkCommonAssigned, String loginUserName, String loginUserGrid, String node, String loginUserId,boolean isAgree, String beAssignedUserId) {

        //保存任务表
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        if (tkCommonAssigned != null) {
            if (tkCommonAssignedService.updateByPrimaryKey(tkCommonAssigned) == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                return 0;
            }
        }


        //保存操作记录
        if (saveDynamic(tkCommonTask.getId(), loginUserName, loginUserGrid, null, node, null, null, null) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }


        if (smsEnable) {
            //--------------------修改待办任务状态------------------------
            TkWorkExample tkWorkExample = new TkWorkExample();
            TkWorkExample.Criteria criteria2 = tkWorkExample.createCriteria();
            criteria2.andCommonTaskIdEqualTo(tkCommonTask.getId());
            tkWorkExample.setOrderByClause("create_time desc");
            List<TkWork> tkWorks = tkWorkService.selectByExample(tkWorkExample);
            if (tkWorks.size() > 0) {
                workMSGUtils.updateWork(loginUserId, tkWorks.get(0).getWorkId(), 1);
            }


            //发送通知
            String body = "";
            if (isAgree) {//延时同意
                body = tkCommonTask.getTkName() + "延时申请通过";
            } else {//延时拒绝
                body = tkCommonTask.getTkName() + "延时申请拒绝";
            }

            List<String> userIds = new ArrayList<String>();//接收人
            userIds.add(beAssignedUserId);
            workMSGUtils.sendMsg(loginUserId, loginUserName, userIds,body, tkCommonTask.getMatterType(), tkCommonTask.getId());

        }
        return 1;
    }

    @Override
    @Transactional
    public int revert(List<TkCommonTask> tkCommonTasks) {

        for (TkCommonTask tkCommonTask : tkCommonTasks) {
            tkCommonTask.setStandby1("0");
            if (this.updateByPrimaryKey(tkCommonTask) == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                return 0;
            }
        }

        return 1;
    }

    @Override
    @Transactional
    public int backPuTong(List<TkCommonTask> tkCommonTasks) {

        for (TkCommonTask tkCommonTask : tkCommonTasks) {
            tkCommonTask.setIsHst(0);
            if (this.updateByPrimaryKey(tkCommonTask) == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                return 0;
            }
        }

        return 1;
    }

    /**
     * 物理删除
     *
     * @return
     */
    @Override
    @Transactional
    public int delete2(String[] split) {
        List<String> strsToList1 = Arrays.asList(split);
        //删除主表
        this.deleteByPrimaryKeys(split);//删除主表 RollbackOnly();//手动回滚

        //删除指派表
        TkCommonAssignedExample tkCommonAssignedExample = new TkCommonAssignedExample();
        TkCommonAssignedExample.Criteria criteria = tkCommonAssignedExample.createCriteria();
        criteria.andCommonTkIdIn(strsToList1);
        tkCommonAssignedService.deleteByExample(tkCommonAssignedExample);//删除指派表

        //删除转督办表
        TkCommonLeaderExample tkCommonLeaderExample = new TkCommonLeaderExample();
        TkCommonLeaderExample.Criteria criteria1 = tkCommonLeaderExample.createCriteria();
        criteria1.andTkIdIn(strsToList1);
        tkCommonLeaderService.deleteByExample(tkCommonLeaderExample);

        //删除上报表
        TkCommonReportExample tkCommonReportExample = new TkCommonReportExample();
        TkCommonReportExample.Criteria criteria2 = tkCommonReportExample.createCriteria();
        criteria2.andCommonTkIdIn(strsToList1);
        tkCommonReportService.deleteByExample(tkCommonReportExample);


        //删除记录表
        TkCommonTaskDynamicExample tkCommonTaskDynamicExample = new TkCommonTaskDynamicExample();
        TkCommonTaskDynamicExample.Criteria criteria3 = tkCommonTaskDynamicExample.createCriteria();
        criteria3.andCommonTkIdIn(strsToList1);
        tkCommonTaskDynamicService.deleteByExample(tkCommonTaskDynamicExample);

        return 1;
    }


    //保存操作记录
    private int saveDynamic(String id, String userName, String address, Date time, String node, String returnReason, String cuiBanReason, String hechaReason) {
        TkCommonTaskDynamic tkCommonTaskDynamic = new TkCommonTaskDynamic();
        tkCommonTaskDynamic.setId(UUID.randomUUID().toString());
        tkCommonTaskDynamic.setCommonTkId(id);
        tkCommonTaskDynamic.setName(userName);
        tkCommonTaskDynamic.setAddress(address);
        tkCommonTaskDynamic.setNote(node);
        tkCommonTaskDynamic.setTkTime(time);
        tkCommonTaskDynamic.setCreateTime(new Date());
        tkCommonTaskDynamic.setReturnReason(returnReason);//退回原因
        tkCommonTaskDynamic.setCuibanReason(cuiBanReason);//催办原因
        tkCommonTaskDynamic.setHechaReason(hechaReason);//核查原因

        return tkCommonTaskDynamicService.insert(tkCommonTaskDynamic);
    }

    //保存操作记录根据type  通用
    @Override
    public int saveDynamicByType(String id, String userName, String address, Date time, String node, String reason) {
        TkCommonTaskDynamic tkCommonTaskDynamic = new TkCommonTaskDynamic();
        tkCommonTaskDynamic.setId(UUID.randomUUID().toString());
        tkCommonTaskDynamic.setCommonTkId(id);
        tkCommonTaskDynamic.setName(userName);
        tkCommonTaskDynamic.setAddress(address);
        tkCommonTaskDynamic.setNote(node);
        tkCommonTaskDynamic.setTkTime(time);
        tkCommonTaskDynamic.setCreateTime(new Date());
        tkCommonTaskDynamic.setCuibanReason(reason);
        return tkCommonTaskDynamicService.insert(tkCommonTaskDynamic);
    }


    public List<Map<String, Object>> manyiRank(Map map) {
        return tkCommonTaskExtMapper.manyiRank(map);
    }

    public List<Map<String, Object>> personManYiTJ(Map map) {
        return tkCommonTaskExtMapper.personManYiTJ(map);
    }

    public List<TkCommonTask> taskListByWgCode(Map map) {
        return tkCommonTaskExtMapper.taskListByWgCode(map);
    }


    @Override
    public List<Map<String, Object>> taskCountByWgcode(Map map) {
        return tkCommonTaskExtMapper.taskCountByWgcode(map);
    }

    @Override
    public List<Map<String, Object>> taskCountBySecWgcode(Map map) {
        return tkCommonTaskExtMapper.taskCountBySecWgcode(map);
    }

    @Override
    public List<Map<String, Object>> taskCountByThirdWgcode(Map map) {
        return tkCommonTaskExtMapper.taskCountByThirdWgcode(map);
    }

    @Override
    public List<Map<String, Object>> groupByMatterType(Map map) {
        return tkCommonTaskExtMapper.groupByMatterType(map);
    }

    @Override
    public List<Map<String, Object>> groupByPriority(Map map) {
        return tkCommonTaskExtMapper.groupByPriority(map);
    }

    @Override
    public List<Map<String, Object>> selectMatterRankByWg(Map map) {
        return tkCommonTaskExtMapper.selectMatterRankByWg(map);
    }

    @Override
    public List<Map<String, Object>> getTaskByUserId(Map map) {
        return tkCommonTaskExtMapper.getTaskByUserId(map);
    }

    //转执法局
    @Override
    @Transactional
    public int zhuanzhifajv(TkCommonTask tkCommonTask) {
        if (this.updateByPrimaryKey(tkCommonTask) == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            return 0;
        }

        try {
            String url = "https://workflow-api.jsspzf.com/api/v3_1/qzjb/saveQzjb";
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");
            Map<String, Object> pam = new HashMap<String, Object>();
            pam.put("bt", tkCommonTask.getTkName());//标题
            pam.put("ly", tkCommonTask.getComplaintsPerson());//来源  举报人
            pam.put("jbrdh", tkCommonTask.getComplaintsPhone());//举报人电话
            pam.put("dz", tkCommonTask.getTkAddress());//地址
            pam.put("xq", tkCommonTask.getTkDetail());//详情
            pam.put("sj", tkCommonTask.getReleaseTime());//举报时间
            pam.put("fj", tkCommonTask.getFilePath());//附件
            String ret = ZQTHttpHelper.doPostJson(url, JSON.toJSONString(pam), headParams);
            JSONObject jo = JSONObject.parseObject(ret);
            if (jo.get("msg").equals("success")) {//接口访问成功
//                    jo.get("data").toString();
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                return 0;
            }
            System.out.println("转执法返回" + ret);//{"data":"保存成功","msg":"success","status":200}

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

    @Override
    public List<Map<String, Object>> enviromentManStatistic(Map map) {
        return tkCommonTaskExtMapper.enviromentManStatistic(map);
    }

    @Override
    public List<Map<String, Object>> enviromentMatterStatistic(Map map) {
        return tkCommonTaskExtMapper.enviromentMatterStatistic(map);
    }

    @Override
    public List<GridWgBean> countTaskBySq(Map map) {
        List<GridWgBean> result = new ArrayList<GridWgBean>();

        List<Map<String, Object>> list = tkCommonTaskExtMapper.countTaskBySq(map);
        GridRegionExample bsWgxxbExample = new GridRegionExample();
        bsWgxxbExample.createCriteria().andWgParentIdEqualTo(map.get("wgCode").toString()).andLevelEqualTo("2");
        List<GridRegion> bsWgxxbList = gridRegionService.selectByExample(bsWgxxbExample);
        for (GridRegion bsWgxxb : bsWgxxbList) {
            GridWgBean resultMap = new GridWgBean();
            int count = 0;
            resultMap.setWgName(bsWgxxb.getWgName());
            for (Map<String, Object> obj : list) {
                if (obj.get("wg_code").toString().contains(bsWgxxb.getWgCode())) {
                    count += Integer.valueOf(obj.get("allNum").toString());
                }
            }
            resultMap.setCount(count);
            result.add(resultMap);
        }


        List<GridWgBean> collect = result.stream().sorted(Comparator.comparing(GridWgBean::getCount).reversed()).collect(Collectors.toList());
        return collect;
    }

    @Override
    public PageInfo<Map<String, Object>> selectTaskList(String userName, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, String> map = new HashMap<>();
        map.put("userName", userName);
        List<Map<String, Object>> taskList = tkCommonTaskExtMapper.selectTaskList(map);
        taskList.forEach(body -> {
            if ((int) body.get("tk_status") == 50) {
                body.put("tk_status_name", "已完成");
            } else {
                body.put("tk_status_name", "处理中");
            }
        });
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(taskList);
        return pageInfo;
    }

}
