package yangtz.cs.liu.campus.service.impl.schoolDepartmentBudget;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.activiti.service.IProcessService;
import yangtz.cs.liu.campus.domain.schoolDepartmentBudget.SchoolDepartmentBudget;
import yangtz.cs.liu.campus.domain.schoolDepartmentBudget.SchoolDepartmentBudgetProjectmx;
import yangtz.cs.liu.campus.mapper.schoolDepartmentBudget.SchoolDepartmentBudgetMapper;
import yangtz.cs.liu.campus.service.schoolDepartmentBudget.ISchoolDepartmentBudgetService;
import yangtz.cs.liu.campus.vo.schoolDepartmentBudget.SchoolDepartmentBudgetVo;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.core.constant.ProcessCommon.PENDING;
import static com.core.constant.ProcessCommon.SUSPENDSTATE_PENDING;
import static com.core.constant.ProcessDefinition.DEPARTMENTBUDGET;
import static com.core.constant.ProcessVariables.DEPARTMENTAPPLYUSERID;
import static com.core.constant.ProcessVariables.DEPARTMENTUSERID;

/**
 * 科室预算填报Service业务层处理
 *
 * @author ruoyi
 * @date 2023-07-11
 */
@Service
public class SchoolDepartmentBudgetServiceImpl extends ServiceImpl<SchoolDepartmentBudgetMapper, SchoolDepartmentBudget> implements ISchoolDepartmentBudgetService
{
    @Autowired
    private SchoolDepartmentBudgetMapper schoolDepartmentBudgetMapper;
    @Resource
    private IdentityService identityService;
    @Autowired
    private IProcessService processService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;

    /**
     * 查询科室预算填报
     *
     * @param id 科室预算填报主键
     * @return 科室预算填报
     */
    @Override
    public SchoolDepartmentBudgetVo selectSchoolDepartmentBudgetById(Long id)
    {
        return schoolDepartmentBudgetMapper.selectSchoolDepartmentBudgetById(id);
    }

    /**
     * 查询全部科室预算填报列表
     *
     * @param schoolDepartmentBudget 科室预算填报
     * @return 科室预算填报
     */
    @Override
    public List<SchoolDepartmentBudgetVo> selectSchoolDepartmentBudgetList(SchoolDepartmentBudget schoolDepartmentBudget)
    {
        return schoolDepartmentBudgetMapper.selectSchoolDepartmentBudgetList(schoolDepartmentBudget);
    }

    /**
     * 新增科室预算填报
     *
     * @param schoolDepartmentBudget 科室预算填报
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSchoolDepartmentBudget(SchoolDepartmentBudgetVo schoolDepartmentBudget)
    {
        if (StringUtils.isNull(schoolDepartmentBudget.getLeadershipId())){
            throw new ServiceException("请选择分管领导");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        schoolDepartmentBudget.setDeptId(user.getDeptId());
        schoolDepartmentBudget.setInformantId(user.getUserId());
        schoolDepartmentBudget.setInformant(user.getUserName());
        schoolDepartmentBudget.setCreateById(user.getUserId());
        schoolDepartmentBudget.setCreateBy(user.getUserName());
        schoolDepartmentBudget.setTbTime(DateUtils.getNowDate());
        schoolDepartmentBudget.setCreateTime(DateUtils.getNowDate());
        int rows = schoolDepartmentBudgetMapper.insertSchoolDepartmentBudget(schoolDepartmentBudget);
        insertSchoolDepartmentBudgetProjectmx(schoolDepartmentBudget);
        return rows;
    }

    /**
     * 修改科室预算填报
     *
     * @param schoolDepartmentBudget 科室预算填报
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSchoolDepartmentBudget(SchoolDepartmentBudgetVo schoolDepartmentBudget)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        schoolDepartmentBudget.setUpdateById(user.getUserId());
        schoolDepartmentBudget.setUpdateTime(DateUtils.getNowDate());
        schoolDepartmentBudgetMapper.deleteSchoolDepartmentBudgetProjectmxByDepartmentBudgetId(schoolDepartmentBudget.getId());
        insertSchoolDepartmentBudgetProjectmx(schoolDepartmentBudget);
        return schoolDepartmentBudgetMapper.updateSchoolDepartmentBudget(schoolDepartmentBudget);
    }

    /**
     * 批量删除科室预算填报
     *
     * @param ids 需要删除的科室预算填报主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSchoolDepartmentBudgetByIds(Long[] ids)
    {
        schoolDepartmentBudgetMapper.deleteSchoolDepartmentBudgetProjectmxByDepartmentBudgetIds(ids);
        return schoolDepartmentBudgetMapper.deleteSchoolDepartmentBudgetByIds(ids);
    }

    /**
     * 删除科室预算填报信息
     *
     * @param id 科室预算填报主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSchoolDepartmentBudgetById(Long id)
    {
        schoolDepartmentBudgetMapper.deleteSchoolDepartmentBudgetProjectmxByDepartmentBudgetId(id);
        return schoolDepartmentBudgetMapper.deleteSchoolDepartmentBudgetById(id);
    }

    /**
     * 查询本单位科室预算填报列表
     * @param schoolDepartmentBudget
     * @return
     */
    @Override
    public List<SchoolDepartmentBudgetVo> selectSchoolDepartmentBudgetListDw(SchoolDepartmentBudget schoolDepartmentBudget) {
        schoolDepartmentBudget.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        return schoolDepartmentBudgetMapper.selectSchoolDepartmentBudgetList(schoolDepartmentBudget);
    }

    /**
     * 新增科室预算填报项目明细信息
     *
     * @param schoolDepartmentBudget 科室预算填报对象
     */
    public void insertSchoolDepartmentBudgetProjectmx(SchoolDepartmentBudgetVo schoolDepartmentBudget)
    {
        List<SchoolDepartmentBudgetProjectmx> schoolDepartmentBudgetProjectmxList = schoolDepartmentBudget.getSchoolDepartmentBudgetProjectmxList();
        Long id = schoolDepartmentBudget.getId();
        if (StringUtils.isNotNull(schoolDepartmentBudgetProjectmxList))
        {
            List<SchoolDepartmentBudgetProjectmx> list = new ArrayList<SchoolDepartmentBudgetProjectmx>();
            for (SchoolDepartmentBudgetProjectmx schoolDepartmentBudgetProjectmx : schoolDepartmentBudgetProjectmxList)
            {
                schoolDepartmentBudgetProjectmx.setDepartmentBudgetId(id);
                list.add(schoolDepartmentBudgetProjectmx);
            }
            if (list.size() > 0)
            {
                schoolDepartmentBudgetMapper.batchSchoolDepartmentBudgetProjectmx(list);
            }
        }
    }

    /**
     * 提交申请
     * @param schoolDepartmentBudget
     * @param userName
     * @param key
     * @param variables
     * @return
     */
    @Override
    @Transactional
    public int submitApply(SchoolDepartmentBudget schoolDepartmentBudget, String userName, String key, Map<String, Object> variables) {
        // 业务type 表示是什么流程类型, businessKey表示礼堂预约申请id
        String businessKey = schoolDepartmentBudget.getId().toString();
        identityService.setAuthenticatedUserId(userName);

        //设置申请人
        variables.put(DEPARTMENTAPPLYUSERID,schoolDepartmentBudget.getApplyId());
        //设置分管领导
        variables.put(DEPARTMENTUSERID,schoolDepartmentBudget.getLeadershipId());

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(key, businessKey, variables);
        String instanceId = processInstance.getId();
        //与我们的业务表开始建立关系
        schoolDepartmentBudget.setInstanceId(instanceId);
        schoolDepartmentBudget.setState("1");
        int i = schoolDepartmentBudgetMapper.updateById(schoolDepartmentBudget);
        SchoolDepartmentBudgetVo schoolDepartmentBudgetVo = schoolDepartmentBudgetMapper.selectSchoolDepartmentBudgetById(new Long(businessKey));
        //当前登录人待办任务集合
        String userId = SecurityUtils.getLoginUser().getUser().getUserId().toString();
        List<Task> taskList = processService.findAssigneeTasks(userId, DEPARTMENTBUDGET);
        for (Task task : taskList) {
            TaskEntityImpl taskImpl = (TaskEntityImpl) task;
            //拿到当前任务id
            String processInstanceId = taskImpl.getProcessInstanceId();
            //拿到流程定义对象
            ProcessInstance processInstance1 = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //业务id(我们当时新增的时候指定了businessKey为id)
            String businessKey1 = processInstance1.getBusinessKey();
            if (businessKey1.equals(businessKey)){
                schoolDepartmentBudgetVo.setTaskId(taskImpl.getId());
            }
        }
        String taskId = schoolDepartmentBudgetVo.getTaskId();
        Map<String,Object> variables1 = new HashMap<>();
        variables1.put("comment","同意");
        variables1.put("pass","true");
        processService.completeTask(taskId, instanceId, variables1);
        return i;
    }

    /**
     * 待办列表
     * @param key
     * @param entity
     * @param userId
     * @return
     */
    @Override
    public List<SchoolDepartmentBudgetVo> findTodoTasks(String key, SchoolDepartmentBudget entity, String userId) {
        List<SchoolDepartmentBudgetVo> list = new ArrayList<>();
        //当前登录人待办任务集合
        List<Task> taskList = processService.findAssigneeTasks(userId, key);
        for (Task task : taskList) {
            TaskEntityImpl taskImpl = (TaskEntityImpl) task;
            //拿到当前任务id
            String processInstanceId = taskImpl.getProcessInstanceId();
            //拿到流程定义对象
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            //业务id(我们当时新增的时候指定了businessKey为id)
            String businessKey = processInstance.getBusinessKey();
            //通过id查询出我们业务对象
            SchoolDepartmentBudget schoolDepartmentBudget = schoolDepartmentBudgetMapper.selectById(new Long(businessKey));
            if (StringUtils.isNull(schoolDepartmentBudget)) {
                continue;
            }
            //转vo
            SchoolDepartmentBudgetVo schoolDepartmentBudgetVo = new SchoolDepartmentBudgetVo();
            BeanUtils.copyProperties(schoolDepartmentBudget, schoolDepartmentBudgetVo);

            schoolDepartmentBudgetVo.setTaskId(taskImpl.getId());

            if (SUSPENDSTATE_PENDING.equals(taskImpl.getSuspensionState())) {
                //挂起
                schoolDepartmentBudgetVo.setTaskName(PENDING);
            } else {
                schoolDepartmentBudgetVo.setTaskName(taskImpl.getName());
            }
            list.add(schoolDepartmentBudgetVo);
        }
        List<SchoolDepartmentBudgetVo> resList = list.stream().sorted(Comparator.comparing(SchoolDepartmentBudgetVo::getApplyTime).reversed()).collect(Collectors.toList());
        return resList;
    }

    @Override
    public List<SchoolDepartmentBudgetVo> findDoneTasks(String key, SchoolDepartmentBudget entity, String userId) {
        List<SchoolDepartmentBudgetVo> list = new ArrayList<>();
        //当前登录人完成的历史集合
        List<HistoricTaskInstance> hisList = processService.findDoneTasks(userId, key);
        for (HistoricTaskInstance instance : hisList) {
            //流程实例key
            String processInstanceId = instance.getProcessInstanceId();
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            //业务id
            String businessKey = processInstance.getBusinessKey();
            //通过id查询出我们业务对象
            SchoolDepartmentBudget schoolDepartmentBudget = schoolDepartmentBudgetMapper.selectById(new Long(businessKey));
            if (StringUtils.isNull(schoolDepartmentBudget)) {
                continue;
            }
            //转vo
            SchoolDepartmentBudgetVo schoolDepartmentBudgetVo = new SchoolDepartmentBudgetVo();
            BeanUtils.copyProperties(schoolDepartmentBudget, schoolDepartmentBudgetVo);
            list.add(schoolDepartmentBudgetVo);
        }
        List<SchoolDepartmentBudgetVo> resList = list.stream().sorted(Comparator.comparing(SchoolDepartmentBudgetVo::getApplyTime).reversed()).collect(Collectors.toList());
        return resList;
    }
}


























