package com.nbclass.szxgl.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nbclass.exception.ParameterException;
import com.nbclass.exception.ServiceException;
import com.nbclass.system.model.User;
import com.nbclass.szxgl.mapper.*;
import com.nbclass.szxgl.model.*;
import com.nbclass.szxgl.service.ProjectService;
import com.nbclass.szxgl.service.ProjectTaskService;
import com.nbclass.util.DateUtil;
import com.nbclass.util.UUIDUtil;
import com.nbclass.wxwork.msg.SendMsgUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;

/**
 * @author wangweifeng
 * @version 1.0 2021/3/10
 */
@Service
public class ProjectTaskServiceImpl implements ProjectTaskService {

    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private ProjectTaskMapper projectTaskMapper;

    @Resource
    private ProjectTaskJournalMapper projectTaskJournalMapper;

    @Resource
    private ProjectTaskUserMapper projectTaskUserMapper;

    @Resource
    SyUsersMapper syUsersMapper;

    @Resource
    PerMsgMapper perMsgMapper;

    @Resource
    ProjectUserMapper projectUserMapper;

    @Resource
    ProjectService projectService;

    @Resource
    private ProjectTaskTermMapper projectTaskTermMapper;


    @Override
    public boolean deleteProjectTask(String projectId, String[] ids) {
        if(StringUtils.isBlank(projectId)) {
            throw new ParameterException("项目Id不能为空");
        }
        if(ids!=null && ids.length<1) {
            throw new ParameterException("删除任务id数组不能为空");
        }
        for(String id:ids){
            ProjectTask p = projectTaskMapper.findById(id);
            if(p!=null&&p.getProjectId().equals(projectId)){
                // 删除项目任务日志
                projectTaskJournalMapper.deleteByTaskId(p.getId());
                // 删除项目任务人员关联表
                projectTaskUserMapper.deleteByTaskId(p.getId());
                //删除任务
                projectTaskMapper.delete(p);
            }
        }
        return true;
    }

    @Override
    public List<Map> selectMyTaskList(String userid) {
       List<Map> list =  projectTaskMapper.getMyTaskList(userid);
        return list;
    }

    @Transactional
    @Override
    public void addProjectTask(ProjectTask t, Integer isSendMsg, String[] userIds,String listValues) {
        if(t.getStartTime().getTime() > t.getEndTime().getTime()) {
            throw new ParameterException("项目任务时间范围不对！");
        }
        if (userIds == null && userIds.length<1) {
            throw new ParameterException("任务执行人不能为空");
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user==null) {
            throw new ParameterException("登陆失败，请重新登陆！");
        }
        t.setId(UUIDUtil.uuid());
        t.setCreateUserId(user.getUserId());
        t.setCreateTime(DateUtil.currentTimestamp());
        t.setUpdateTime(DateUtil.currentTimestamp());
        t.setSpeed((byte)0);//初始化进度
        t.setNotify((short) 0);//默认0，生产环境改为1
        projectTaskMapper.insert(t);

        JSONArray jsonArray = JSONObject.parseArray(listValues);
        for (int i = 0; i < jsonArray.size(); i++) {
            //添加工期信息
            ProjectTaskTerm projectTaskTerm = jsonArray.getObject(i, ProjectTaskTerm.class);
            projectTaskTerm.setProjectId(t.getId());
            projectTaskTerm.setId(UUIDUtil.uuid());
            projectTaskTermMapper.addProjectTaskTerm(projectTaskTerm);
        }


        // 等待保存的对象集合
        List<ProjectTaskUser> c = new ArrayList<ProjectTaskUser>();
        Set<String> sendIds = new HashSet<String>();// 需要发送消息提醒的用户

        if (userIds != null && userIds.length > 0) {
            for (String id : userIds) {
                ProjectTaskUser pu = new ProjectTaskUser();
                pu.setId(UUIDUtil.uuid());
                pu.setProjectId(t.getProjectId());
                pu.setProjectTaskId(t.getId());
                pu.setUserId(id);
                pu.setCreateTime(DateUtil.currentTimestamp());
                pu.setUpdateTime(DateUtil.currentTimestamp());
                c.add(pu);
            }
        }
        if (isSendMsg != null && isSendMsg == 1) {
            Byte type = 32;
            saveMsgWarn(type, t.getId(), sendIds, null);// 发送消息提醒
        }

        //判断当前项目状态
        Project p = projectMapper.findById(t.getProjectId());
        if(p==null){
            throw new ServiceException("任务关联的项目不存在，可能已被删除！");
        }

        //导入
        for(ProjectTaskUser projectTaskUser: c) {
            projectTaskUserMapper.insert(projectTaskUser);
        }
        boolean success = true;
        if (success) {
            String touser = "", toUserNames = "";
            if (userIds != null && userIds.length > 0){
                touser += (StringUtils.isBlank(touser) ? "" : "|") + StringUtils.join(userIds, "|");
                for (String userid : userIds) {
                    String tempName = syUsersMapper.findByUserName(userid).getTrueName();
                    if(StringUtils.isNotBlank(tempName))toUserNames += (StringUtils.isBlank(toUserNames) ? "" : ", ") + tempName;
                }
            }

            String description =
                    "<div class=\"gray\">"+DateUtil.date2String(new Date(), "yyyy年MM月dd日 HH:mm")+"</div><br><br>"
                            + "项目名称："+p.getName()+"<br>"
                            + "任务名称："+t.getName()+"<br>"
                            + "计划时间：" + DateUtil.date2String(t.getStartTime(), "MM-dd") + " ~ "
                            + DateUtil.date2String(t.getEndTime(), "MM-dd") + "<br>"
                            + "执行人："+ toUserNames;
            if (StringUtils.isNotBlank(touser)) {
                SendMsgUtil.sendWxMsgByNewTask(touser, t.getProjectId(), description);
            }
        }
    }

    @Transactional
    @Override
    public void updateProjectTask(ProjectTask t, Integer isSendMsg, String[] userIds) {
        if(t.getStartTime().getTime() > t.getEndTime().getTime()) {
            throw new ParameterException("项目任务时间范围不对！");
        }
        if (userIds == null && userIds.length<1) {
            throw new ParameterException("任务执行人不能为空");
        }

        //判断当前项目状态
        Project p = projectMapper.findById(t.getProjectId());
        if(p==null){
            throw new ServiceException("任务关联的项目不存在，可能已被删除！");
        }

        ProjectTask oldPro = projectTaskMapper.findById(t.getId());
        Map<String, Object> param = new HashMap<String, Object>();
        if (oldPro == null) {
            throw new ParameterException("项目任务不存在，修改失败");
        }
        // 判断是否有修改权限
        if (!projectService.hasPowerForTask(t.getProjectId())) {
            throw new ParameterException("无修改权限，修改失败！");
        }

        oldPro.setName(t.getName());
        oldPro.setContent(t.getContent());
        oldPro.setStartTime(t.getStartTime());
        oldPro.setEndTime(t.getEndTime());
        oldPro.setUpdateTime(DateUtil.currentTimestamp());
        //更新项目
        projectTaskMapper.updateByPrimaryKeySelective(oldPro);


        List<String> zxrIdsOld = new ArrayList<String>(); // 之前数据库的执行人人用户ID
        List<ProjectTaskUser> list = projectTaskUserMapper.selectProjectTaskUserList(t.getId());
        for(ProjectTaskUser tu:list){
            if(tu==null || StringUtils.isBlank(tu.getUserId()))continue;
            zxrIdsOld.add(tu.getUserId());
            boolean has=false;
            for(int i=0,k=userIds.length;i<k;i++){
                if(tu.getUserId().equals(userIds[i])){
                    has=true;
                    break;
                }
            }
            if(!has){
                //删除
                projectTaskUserMapper.delete(tu);
            }
        }

        //等待保存的对象集合
        List<ProjectTaskUser> c=new ArrayList<ProjectTaskUser>();
        for(int i=0,k=userIds.length;i<k;i++){//用户
            boolean has=false;
            for(ProjectTaskUser id:list){
                if(id.getUserId().equals(userIds[i])){
                    has=true;
                    break;
                }
            }
            if(!has){
                ProjectTaskUser tu=new ProjectTaskUser();
                tu.setId(UUIDUtil.uuid());
                tu.setProjectTaskId(oldPro.getId());
                tu.setProjectId(oldPro.getProjectId());
                tu.setUserId(userIds[i]);
                c.add(tu);
            }
        }
        if(isSendMsg!=null&&isSendMsg==1){
            //发送消息提醒
//            saveMsgWarn(32,t.getId() , userIds,null);
        }
        for(ProjectTaskUser pu: c) {
            projectTaskUserMapper.insertOrUpdate(pu.getId(), pu.getProjectId(), pu.getProjectTaskId(), pu.getUserId(), pu.getUpdateTime(), pu.getCreateTime());
        }

        boolean success = true;
        if (success) {
            String toUser = "", toUserNames = "";
            if (userIds != null && userIds.length > 0){
                for (String userid : userIds) {
                    if(!zxrIdsOld.contains(userid)){
                        toUser += (StringUtils.isBlank(toUser) ? "" : "|") + userid;
                    }
                    String tempName = syUsersMapper.findByUserName(userid).getTrueName();
                    if(StringUtils.isNotBlank(tempName))toUserNames += (StringUtils.isBlank(toUserNames) ? "" : ", ") + tempName;
                }
            }

            String description =
                    "<div class=\"gray\">"+DateUtil.date2String(new Date(), "yyyy年MM月dd日 HH:mm")+"</div><br><br>"
                            + "项目名称："+p.getName()+"<br>"
                            + "任务名称："+t.getName()+"<br>"
                            + "计划时间：" + DateUtil.date2String(t.getStartTime(), "MM-dd") + " ~ "
                            + DateUtil.date2String(t.getEndTime(), "MM-dd") + "<br>"
                            + "执行人："+ toUserNames;
            if (StringUtils.isNotBlank(toUser)) {
                SendMsgUtil.sendWxMsgByNewTask(toUser, t.getProjectId(), description);
            }
        }

    }


    @Override
    public void addProjectTaskJournal(ProjectTaskJournal j, short speed) {
        ProjectTask t = projectTaskMapper.findById(j.getProjectTaskId());
        if(t==null){
            throw new ParameterException("任务不存在，可能已被删除！");
        }
        //判断当前项目状态
        Project p = projectMapper.findById(t.getProjectId());
        if(p==null){
            throw new ParameterException("任务关联的项目不存在，可能已被删除！");
        }
        if(p.getStatus()!=1){
            throw new ParameterException("项目处于未开始，暂停或结束状态时无法添加进度日志!");
        }
        //当前任务的进度执行人才有添加进度日志的权限,上线后放开
//        if(!myIsExecutorByTaskId(t.getId())){
//            throw new MyRuntimeException("没有添加权限，只有任务的执行人才有添加进度日志的权限。");
//        }
        if(speed>=100) {
            speed = 100;
        } else {
            if(t.getSpeed()>=speed) {
                throw new ServiceException("当前任务进度未变，无法继续添加");
            }
        }
        j.setJournal("修改进度："+t.getSpeed()+"% --> "+speed+"%");
        j.setCreateTime(DateUtil.currentTimestamp());
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user==null) {
            throw new ServiceException("登陆失败，请重新登陆！");
        }
        j.setCreateUserId(user.getUserId());
        t.setSpeed((byte)speed);
        j.setId(UUIDUtil.uuid());
        j.setCreateTime(DateUtil.currentTimestamp());
        int insert = projectTaskJournalMapper.insert(j);
        if(insert>0){
            //更新任务进度
            projectTaskMapper.updateTaskSpeed(t.getId(), speed);
            String projectName = p.getName();
            if(projectName.length()> 20)projectName=projectName.substring(0, 20)+" ...";

            String taskName = t.getName();
            if(taskName.length()> 20)taskName=taskName.substring(0, 20)+" ...";

            String touser = "";

            List<String> taskUserIds = projectTaskUserMapper.selectUserIds(t.getId()); // 任务执行人
            List<String> fzIds=new ArrayList<String>();		// 项目负责人
            List<String> userIds=new ArrayList<String>();	// 项目授权人员
            @SuppressWarnings("unchecked")
            List<ProjectUser> list= projectUserMapper.selectProjectUserList(p.getId());
            if(list!=null && list.size()>0){
                for(ProjectUser pu:list){
                    if(1==pu.getType()){
                        fzIds.add(pu.getTableId());
                    }else if(2==pu.getType()){
                        //	deptIds.add(pu.getTableId());
                    }else{
                        userIds.add(pu.getTableId());
                    }
                }
            }

            if(taskUserIds!=null && taskUserIds.size()>0)touser += (StringUtils.isBlank(touser)?"":"|") + StringUtils.join(taskUserIds, "|");
            if(fzIds!=null && fzIds.size()>0)touser += (StringUtils.isBlank(touser)?"":"|") + StringUtils.join(fzIds, "|");
            if(userIds!=null && userIds.size()>0)touser += (StringUtils.isBlank(touser)?"":"|") + StringUtils.join(userIds, "|");

            String description =
                    "<div class=\"gray\">"+DateUtil.date2String(new Date(), "yyyy年MM月dd日 HH:mm")+"</div><br><br>"
                            + "项目名称："+projectName+"<br>"
                            + "任务名称："+taskName
                            + "<div class=\"highlight\">"+j.getJournal()+"</div><br>"
//                            + "操作用户："+user.getUsername()+"<br>"
                            + "进度说明："+j.getContent();
            if(StringUtils.isNotBlank(touser)){
                SendMsgUtil.sendWxMsgByNewTask(touser, t.getProjectId(), description);
            }
        }
    }

    /**
     * 添加消息提醒
     *
     * @param type    消息类型
     * @param tableId 信息表id
     * @param userIds 提醒用户id集合
     * @param deptIds 提醒部门id集合
     */
    protected void saveMsgWarn(Byte type, String tableId, Collection<String> userIds, Collection<String> deptIds) {

        Set<String> addUserIds = new HashSet<String>();
        if (userIds != null) {
            for (String id : userIds) {
                addUserIds.add(id);
            }
        }
        if (deptIds != null) {
            // 查询出此部门所有的用户id
            for (String id : deptIds) {
                // 通过部门id查询该部门下所有的员工id
                List<String> uid = syUsersMapper.findIdByDeptId(id);
                addUserIds.addAll(uid);
            }
        }
        if (!addUserIds.isEmpty()) {
            List<PerMsg> c = new ArrayList<PerMsg>();
            for (String id : addUserIds) {
                PerMsg msg = new PerMsg();
                msg.setId(UUIDUtil.uuid());
                msg.setMsgTime(DateUtil.currentTimestamp());
                msg.setMsgType(type);
                msg.setReadState((short) 0);
                msg.setTableId(tableId);
                msg.setUserId(id);
                c.add(msg);
            }
            // 批量添加或更新
            // perMsgMapper.insertList(c);
//			projectUserMapper.insertList(c);---此方法只适合id自增长
            for (PerMsg perMsg : c) {
                perMsgMapper.insert(perMsg);
            }
        }
    }

    @Override
    public boolean myIsExecutorByTaskId(String taskId) {
        //判断当前用户是否是任务的执行人
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user==null) {
            throw new ServiceException("登陆失败，请重新登陆！");
        }
        Integer num = projectTaskUserMapper.selectProjectTaskUser(taskId, user.getUserId());
        if(num<1){
            return false;
        }else{
            return true;
        }
    }
}
