package com.artfess.yhxt.task.manager.impl;

import com.artfess.base.context.BaseContext;
import com.artfess.base.id.IdGenerator;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.query.QueryOP;
import com.artfess.uc.api.model.IUser;
import com.artfess.uc.api.service.IUserService;
import com.artfess.uc.util.ContextUtil;
import com.artfess.yhxt.specialcheck.model.SiteInspection;
import com.artfess.yhxt.specialcheck.vo.SiteTaskVo;
import com.artfess.yhxt.task.manager.TaskAlreadyHandleHistoryManager;
import com.artfess.yhxt.task.model.TaskAlreadyHandleHistory;
import com.artfess.yhxt.task.model.TaskWaitHandle;
import com.artfess.yhxt.task.dao.TaskWaitHandleDao;
import com.artfess.yhxt.task.manager.TaskWaitHandleManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.task.vo.TaskWaitHandleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 主要是从各个业务过程中向里面插入待处理的任务数据，然后提供门户进行统一查询跳转并处理 服务实现类
 *
 * @author baseli
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-09-16
 */
@Service
public class TaskWaitHandleManagerImpl extends BaseManagerImpl<TaskWaitHandleDao, TaskWaitHandle> implements TaskWaitHandleManager {


    @Resource
    private IdGenerator idGenerator;
    @Resource
    private BaseContext baseContext;
    @Resource
    private IUserService iUserService;
    @Resource
    private TaskAlreadyHandleHistoryManager taskAlreadyHandleHistoryManager;

    @Override
    public void saveTask(SiteInspection siteInspection, String bizType) {
        //业务ID 业务类型
        String bizId = siteInspection.getId();
        //发送者
        //登录者ID
        String sendUserId = baseContext.getCurrentUserId();
        //登录人账号
        String sendUserAccout = baseContext.getCurrentUserAccout();
        //登录人name
        String sendUserName = baseContext.getCurrentUserName();
        //发送时间
        LocalDateTime sendTime = LocalDateTime.now();
        //发送单位id
        String sendDeptId = baseContext.getCurrentDeptId();
        //发送单位名称
        String sendDeptName = baseContext.getCurrentDeptName();
        //生成工作项_ID 用于任务ID
        List<TaskWaitHandle> taskWaitHandles = this.baseMapper.selectList(new QueryWrapper<TaskWaitHandle>().eq("biz_id", bizId));
        String itemId = null;
        if (taskWaitHandles.size() == 0) {
            itemId = idGenerator.getSuid();
        }
        String itemTitle = sendUserName + "[" + LocalDate.now() + "]创建巡检任务";
        //多个巡检人ID
        String rummagerIds = siteInspection.getRummagerId();
        //巡检人ID集合
        List<String> ids = Arrays.asList(rummagerIds.split(","));
        for (String rummagerId : ids) {
            //代办对象
            TaskWaitHandle taskWaitHandle = new TaskWaitHandle();
            //设置业务相关字段
            taskWaitHandle.setBizId(bizId);
            taskWaitHandle.setBizType(bizType);
            //设置工作项 ID
            if (itemId != null)
                taskWaitHandle.setItemId(itemId);
            //标题
            taskWaitHandle.setItemTitle(itemTitle);
            //来源
            taskWaitHandle.setItemSource(2);
            //类型
            taskWaitHandle.setItemType(1);
            //根据巡检ID查询出相关信息用户
            IUser iUser = iUserService.getUserById(rummagerId);
            //巡检账号/用户账号
            String account = iUser.getAccount();
            //巡检人ID
            String userId = iUser.getUserId();
            //用户姓名
            String fullname = iUser.getFullname();
            //巡检人部门ID
            taskWaitHandle.setReceiveDeptId(ContextUtil.getCurrentDeptId(rummagerId));
            taskWaitHandle.setReceiveDeptName(ContextUtil.getCurrentDeptName(rummagerId));
            if (sendDeptId == null) {
                //发送者相关信息设置
                taskWaitHandle.setSendDeptName(siteInspection.getCompanyName());
                taskWaitHandle.setSendDeptId(siteInspection.getCompanyId());
                taskWaitHandle.setSendDate(sendTime);
               // taskWaitHandle.setSendLoginName(sendUserAccout);
                taskWaitHandle.setSendUserId(siteInspection.getCreateBy());
                taskWaitHandle.setSendUserName(siteInspection.getCreateName());
                taskWaitHandle.setItemTitle(itemTitle);
            } else {
                //发送者相关信息设置
                taskWaitHandle.setSendDeptName(sendDeptName);
                taskWaitHandle.setSendDeptId(sendDeptId);
                taskWaitHandle.setSendDate(sendTime);
                taskWaitHandle.setSendLoginName(sendUserAccout);
                taskWaitHandle.setSendUserId(sendUserId);
                taskWaitHandle.setSendUserName(sendUserName);
                taskWaitHandle.setItemTitle(itemTitle);
            }

            //设置为抢先模式
            taskWaitHandle.setModeType(2);
            //设置优先级 设置为一般
            taskWaitHandle.setPriority(0);
            //接收者相关信息
            taskWaitHandle.setReceiveUserName(fullname);
            taskWaitHandle.setReceiveLoginName(account);
            taskWaitHandle.setReceiveUserId(rummagerId);

            taskWaitHandle.setWorkflowId("cjxjrw");
            taskWaitHandle.setWorkflowName("日常巡检任务");
            taskWaitHandle.setWorkflowInstance(itemId);
            taskWaitHandle.setWorkflowInstanceName(itemTitle);
            taskWaitHandle.setActivitiesId("1");
            this.create(taskWaitHandle);
            TaskAlreadyHandleHistory taskAlreadyHandleHistory = TaskWaitHandle.getTaskAlreadyHandleHistory(taskWaitHandle);
            //保存到已办
            taskAlreadyHandleHistory.setProcessingStatus("1");
            this.taskAlreadyHandleHistoryManager.create(taskAlreadyHandleHistory);
        }
    }

    @Override
    public PageList<TaskWaitHandleVo> queryTaskWaitHandle(QueryFilter<TaskWaitHandle> queryFilter) {
        //登录者ID
        String userId = baseContext.getCurrentUserId();
        //登录人账号
        String userAccout = baseContext.getCurrentUserAccout();
        //登录人账号
        String userName = baseContext.getCurrentUserName();
        //当前时间
        LocalDateTime time = LocalDateTime.now();
        //登录人单位id
        String deptId = baseContext.getCurrentDeptId();
        //登录人单位名称
        String deptName = baseContext.getCurrentDeptName();
        //发送单位名称
        String sendDeptName = baseContext.getCurrentDeptName();
        queryFilter.addFilter("RECEIVE_USER_ID", userId, QueryOP.EQUAL);
        //queryFilter.addFilter("RECEIVE_LOGIN_NAME", userAccout, QueryOP.EQUAL);
        IPage<TaskWaitHandleVo> result = baseMapper.queryTaskWaitHandleVo(convert2IPage(queryFilter.getPageBean()), convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }

    @Override
    public void updateTask(SiteTaskVo siteTaskVo) {
        //业务ID 业务类型
        String bizId = siteTaskVo.getSiteId();
        //当前操作
        String status = siteTaskVo.getStatus();
        //工作项ID
        String itemId = siteTaskVo.getItemId();
        //发送者
        //登录者ID
        String userId = baseContext.getCurrentUserId();
        //登录人账号
        String userAccout = baseContext.getCurrentUserAccout();
        //登录人name
        String userName = baseContext.getCurrentUserName();
        //当前时间
        LocalDate time = LocalDate.now();
        //登录人单位id
        String deptId = baseContext.getCurrentDeptId();
        //登录人单位名称
        String deptName = baseContext.getCurrentDeptName();



        QueryWrapper<TaskWaitHandle> handleQueryWrapper = new QueryWrapper<>();
        handleQueryWrapper.eq("BIZ_ID", bizId)
                .eq("ITEM_ID", itemId)
                .eq("RECEIVE_USER_ID", userId);
        TaskWaitHandle taskWaitHandle = this.getOne(handleQueryWrapper);
        String activitiesId = taskWaitHandle.getActivitiesId();
        taskWaitHandle.setActivitiesId(status);


        //拼接工作项标题
       String itemTitle = null;
        if (status.equals("6")) {
            itemTitle = userName +"["+ time + "]拒绝巡检任务";
        }
        if (status.equals("2")) {
            itemTitle = userName +"["+ time + "]接受巡检任务";
        }
        if (status.equals("3")) {
            itemTitle = userName +"["+ time + "]完成巡检任务";
        }
        if (status.equals("4")) {
            itemTitle = userName +"["+ time + "]确认无病害";
        }
        if (status.equals("5")) {
            itemTitle = userName +"["+ time + "]填写病害";
        }

        //拒绝巡检
        if (status.equals("6")) {
            //接收者相关信息
            taskWaitHandle.setReceiveUserId(taskWaitHandle.getSendUserId());
            taskWaitHandle.setReceiveUserName(taskWaitHandle.getSendUserName());
            taskWaitHandle.setReceiveLoginName(taskWaitHandle.getSendLoginName());
            taskWaitHandle.setReceiveDeptName(taskWaitHandle.getReceiveDeptName());
            taskWaitHandle.setReceiveDeptId(taskWaitHandle.getSendDeptId());
            //保存到历史表
            TaskAlreadyHandleHistory taskAlreadyHandleHistory = TaskWaitHandle.getTaskAlreadyHandleHistory(taskWaitHandle);
            taskAlreadyHandleHistory.setTransDate(LocalDateTime.now());
            taskAlreadyHandleHistory.setProcessingStatus(siteTaskVo.getProcessingStatus());
            taskAlreadyHandleHistory.setItemTitle(itemTitle);
            this.taskAlreadyHandleHistoryManager.create(taskAlreadyHandleHistory);
        }
        if (!activitiesId.equals("1")){
            //保存到历史表
            TaskAlreadyHandleHistory taskAlreadyHandleHistory = TaskWaitHandle.getTaskAlreadyHandleHistory(taskWaitHandle);
            taskAlreadyHandleHistory.setTransDate(LocalDateTime.now());
            taskAlreadyHandleHistory.setProcessingStatus(siteTaskVo.getProcessingStatus());
            taskAlreadyHandleHistory.setItemTitle(itemTitle);
            this.taskAlreadyHandleHistoryManager.create(taskAlreadyHandleHistory);
        }
        if (status.equals("2")){

            TaskAlreadyHandleHistory taskAlreadyHandleHistory = TaskWaitHandle.getTaskAlreadyHandleHistory(taskWaitHandle);
            taskAlreadyHandleHistory.setTransDate(LocalDateTime.now());
            taskAlreadyHandleHistory.setProcessingStatus(siteTaskVo.getProcessingStatus());
            taskAlreadyHandleHistory.setProcessingStatus(siteTaskVo.getProcessingStatus());
            taskAlreadyHandleHistory.setItemTitle(itemTitle);
            this.taskAlreadyHandleHistoryManager.create(taskAlreadyHandleHistory);
        }
        //判断是否为抢占模式
        if (taskWaitHandle.getModeType() == 2 & status .equals("2")) {
            //如果是抢占模式删除其他相同任务
            String id = taskWaitHandle.getId();
            QueryWrapper<TaskWaitHandle> queryWrapper = new QueryWrapper<>();
            queryWrapper.notIn("ID", id);
            queryWrapper.eq("BIZ_ID", bizId)
                    .eq("ITEM_ID", itemId);
            this.baseMapper.delete(queryWrapper);
        }
        //设置建议
        taskWaitHandle.setAdvice(siteTaskVo.getAdvice());
        //修改待办表
        //taskWaitHandle.setItemTitle(itemTitle);

        this.update(taskWaitHandle);
        if (status.equals("3")){
            //保存到历史表
//            TaskAlreadyHandleHistory taskAlreadyHandleHistory = TaskWaitHandle.getTaskAlreadyHandleHistory(taskWaitHandle);
//            taskAlreadyHandleHistory.setTransDate(LocalDateTime.now());
//            taskAlreadyHandleHistory.setProcessingStatus(siteTaskVo.getProcessingStatus());
           // this.taskAlreadyHandleHistoryManager.create(taskAlreadyHandleHistory);

            QueryWrapper<TaskWaitHandle> wrapper = new QueryWrapper<>();
            wrapper.eq("id",taskWaitHandle.getId());
            wrapper.eq("ITEM_ID",taskWaitHandle.getItemId());
            this.baseMapper.delete(wrapper);

        }


    }

    @Override
    public void otherSendPeople(SiteTaskVo siteTaskVo) {
        //业务ID 业务类型
        String bizId = siteTaskVo.getSiteId();
        //当前操作
        String status = siteTaskVo.getStatus();
        //工作项ID
        String itemId = siteTaskVo.getItemId();
        //发送者
        //登录者ID
        String userId = baseContext.getCurrentUserId();
        //登录人账号
        String userAccout = baseContext.getCurrentUserAccout();
        //登录人name
        String userName = baseContext.getCurrentUserName();
        //当前时间
        LocalDate time = LocalDate.now();
        //登录人单位id
        String deptId = baseContext.getCurrentDeptId();
        //登录人单位名称
        String deptName = baseContext.getCurrentDeptName();

        //另派人员时候去进行查询人员信息
        IUser iUser = null;
        String account = null;

        String fullname = null;
        if (siteTaskVo.getRummagerId() != null) {
            iUser = iUserService.getUserById(siteTaskVo.getRummagerId());
            //巡检账号/用户账号
            account = iUser.getAccount();
            //用户姓名
            fullname = iUser.getFullname();
        }
        QueryWrapper<TaskWaitHandle> handleQueryWrapper = new QueryWrapper<>();
        handleQueryWrapper.eq("BIZ_ID", bizId)
                .eq("ITEM_ID", itemId)
                .eq("RECEIVE_USER_ID", userId);
        TaskWaitHandle taskWaitHandle = this.getOne(handleQueryWrapper);

        //保存到历史表
        TaskAlreadyHandleHistory taskAlreadyHandleHistory = TaskWaitHandle.getTaskAlreadyHandleHistory(taskWaitHandle);
        taskAlreadyHandleHistory.setTransDate(LocalDateTime.now());
        this.taskAlreadyHandleHistoryManager.create(taskAlreadyHandleHistory);

        //发送者相关信息设置
        taskWaitHandle.setSendDeptName(deptName);
        taskWaitHandle.setSendDeptId(deptId);
        taskWaitHandle.setSendLoginName(userAccout);
        taskWaitHandle.setSendUserId(userId);
        taskWaitHandle.setSendUserName(userName);
        //接收者相关信息
        taskWaitHandle.setReceiveUserName(fullname);
         taskWaitHandle.setReceiveLoginName(account);
        String rummagerId = siteTaskVo.getRummagerId();
        taskWaitHandle.setReceiveUserId(rummagerId);
        taskWaitHandle.setReceiveDeptId(ContextUtil.getCurrentDeptId(rummagerId));
        taskWaitHandle.setReceiveDeptName(ContextUtil.getCurrentDeptName(rummagerId));

        //判断是否为抢占模式
/*        if (taskWaitHandle.getModeType() == 2) {
            //如果是抢占模式删除其他相同任务
            String id = taskWaitHandle.getId();
            QueryWrapper<TaskWaitHandle> queryWrapper = new QueryWrapper<>();
            queryWrapper.notIn("ID", id);
            queryWrapper.eq("BIZ_ID", bizId)
                    .eq("ITEM_ID", itemId);
            this.baseMapper.delete(queryWrapper);
        }*/
        String itemTitle = null;
        if (status.equals("6")) {

            itemTitle = userName +"["+ LocalDate.now() + "]另派给" + fullname;
            //发送者相关信息设置
            taskWaitHandle.setSendDeptName(deptName);
            taskWaitHandle.setSendDeptId(deptId);
            taskWaitHandle.setSendLoginName(userAccout);
            taskWaitHandle.setSendUserId(userId);
            taskWaitHandle.setSendUserName(userName);
            taskWaitHandle.setItemTitle(itemTitle);
            //接收者相关信息
            taskWaitHandle.setReceiveUserName(fullname);
            taskWaitHandle.setReceiveLoginName(account);
            taskWaitHandle.setReceiveUserId(siteTaskVo.getRummagerId());
        }
        //设置建议
        taskWaitHandle.setAdvice(siteTaskVo.getAdvice());
        //修改待办表
        taskWaitHandle.setItemTitle(itemTitle);
        taskWaitHandle.setActivitiesId("1");
        this.update(taskWaitHandle);

    }
}
