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

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.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
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.util.CollectionUtils;
import yangtz.cs.liu.activiti.service.IProcessService;
import yangtz.cs.liu.campus.domain.area.SchoolAreaApply;
import yangtz.cs.liu.campus.domain.office.SchoolOfficePurchase;
import yangtz.cs.liu.campus.mapper.area.SchoolAreaApplyMapper;
import yangtz.cs.liu.campus.mapper.area.SchoolAreaDetailMapper;
import yangtz.cs.liu.campus.service.area.ISchoolAreaApplyService;
import yangtz.cs.liu.campus.vo.area.AreaApplyByIdVo;
import yangtz.cs.liu.campus.vo.area.AreaApplyTodoVo;
import yangtz.cs.liu.campus.vo.area.AreaApplyVo;
import yangtz.cs.liu.campus.vo.office.OfficeTodoListVO;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.core.constant.ProcessCommon.*;
import static com.core.constant.ProcessVariables.CHARGEUSERIDS;

/**
 * 学校场地申请Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-09-29
 */
@Service
public class SchoolAreaApplyServiceImpl extends ServiceImpl<SchoolAreaApplyMapper, SchoolAreaApply> implements ISchoolAreaApplyService {
    @Autowired
    private SchoolAreaApplyMapper schoolAreaApplyMapper;
    @Autowired
    private IProcessService processService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Resource
    private IdentityService identityService;
    @Autowired
    private SchoolAreaDetailMapper schoolAreaDetailMapper;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ISysUserService userService;


//    @Override
//    public List<AreaApplyTodoVo> findTodoTasks(String key, SchoolAreaApply entity, String userId) {
//        List<AreaApplyTodoVo> list = new ArrayList<>();
//        //当前登录人待办任务集合
//        List<Task> taskList = processService.findTodoList(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查询出我们业务对象
//            SchoolAreaApply schoolAreaApply = schoolAreaApplyMapper.selectById(new Long(businessKey));
//            if(StringUtils.isNotNull(schoolAreaApply)){
//                //转vo
//                AreaApplyTodoVo areaApplyTodoVo = new AreaApplyTodoVo();
//                BeanUtils.copyProperties(schoolAreaApply,areaApplyTodoVo);
//                areaApplyTodoVo.setTaskId(taskImpl.getId());
//                if (SUSPENDSTATE_PENDING.equals(taskImpl.getSuspensionState())) {
//                    //挂起
//                    areaApplyTodoVo.setTaskName(PENDING);
//                }else{
//                    areaApplyTodoVo.setTaskName(taskImpl.getName());
//                }
//                list.add(areaApplyTodoVo);
//            }
//        }
//        return list;
//    }

    @Override
    public List<AreaApplyTodoVo> findTodoTasks(String key, SchoolAreaApply entity, String userId) {
        //当前登录人待办任务集合
        List<Task> taskList = processService.findCandidateTasks(userId, key);
        return getTodoList(taskList);
    }

    @Override
    public List<AreaApplyTodoVo> findDoneTasks(String key, SchoolAreaApply entity, String userId) {

        List<AreaApplyTodoVo> 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查询出我们业务对象
            SchoolAreaApply schoolAreaApply = schoolAreaApplyMapper.selectById(new Long(businessKey));
            if(StringUtils.isNotNull(schoolAreaApply)){
                //转vo
                AreaApplyTodoVo areaApplyTodoVo = new AreaApplyTodoVo();
                BeanUtils.copyProperties(schoolAreaApply,areaApplyTodoVo);
                list.add(areaApplyTodoVo);
            }
        }
        return list;
    }

    @Override
    public int submitApply(SchoolAreaApply schoolAreaApply, String userName, String type, Map<String, Object> variables) {
        // 业务type 表示是什么流程类型, businessKey表示场地申请id
        String businessKey = schoolAreaApply.getId().toString();
        identityService.setAuthenticatedUserId(userName);
        //设置 候选人
        String candidateUsers = candidateUser((String) variables.get(ROLEKEY));
        variables.put(CHARGEUSERIDS, candidateUsers);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(type, businessKey, variables);
        String instanceId = processInstance.getId();
        //与我们的业务表开始建立关系
        schoolAreaApply.setInstanceId(instanceId);
        return schoolAreaApplyMapper.updateById(schoolAreaApply);
    }

    @Override
    public List<AreaApplyVo> queryList(String submitState,SchoolAreaApply schoolAreaApply) {
        List<AreaApplyVo> list = schoolAreaApplyMapper.queryList(submitState,schoolAreaApply);
        if(list.size() == 0 && StringUtils.isNull(list)){
            //throw new ServiceException("数据为空");
            return new ArrayList<>();
        }
//        List<SchoolAreaApply> areaApplyList = schoolAreaApplyMapper.queryList(schoolAreaApply);
//        List<AreaApplyVo> list = new ArrayList<>();
        for (AreaApplyVo areaApplyVo : list){
            //AreaApplyVo areaApplyVo = new AreaApplyVo();
            //String areaNo = schoolAreaDetailMapper.selectById(entity.getDetailId()).getAreaNo();
            //areaApplyVo.setAreaNo(areaNo);
            //BeanUtils.copyProperties(entity,areaApplyVo);
            if (StringUtils.isNotBlank(areaApplyVo.getInstanceId())){
                List<Task> taskList = taskService.createTaskQuery()
                        .processInstanceId(areaApplyVo.getInstanceId())
                        .list();
                if (!CollectionUtils.isEmpty(taskList)) {
                    TaskEntityImpl task = (TaskEntityImpl) taskList.get(0);
                    areaApplyVo.setTaskId(task.getId());
                    if (task.getSuspensionState() == 2) {
                        areaApplyVo.setTaskName("已挂起");
                        areaApplyVo.setSuspendState("2");
                    } else {
                        areaApplyVo.setTaskName(task.getName());
                        areaApplyVo.setSuspendState("1");
                    }
                } else {
                    // 已办结或者已撤销
                    areaApplyVo.setTaskName("已结束");
                }
            }else {
                areaApplyVo.setTaskName("未启动");
            }
        }
        return list;
    }

    @Override
    public List<AreaApplyTodoVo> findMyTodoTasks(String key, SchoolAreaApply entity, String userId) {
        //当前登录人待办任务集合
        List<Task> taskList = processService.findAssigneeTasks(userId, key);
        return getTodoList(taskList);
    }

    @Override
    public AreaApplyVo getInfo(Long id) {
        return schoolAreaApplyMapper.getInfo(id);
    }

    /**
     * @author lyric
     * @date 2022-10-27
     * 设置候选组
     */
    public String candidateUser(String key) {
        if (StringUtils.isEmpty(key)) {
            return "";
        }
        List<SysUser> userList = userService.selectUserListByRoleKey(key);
        List<String> userIds = userList.stream().map(o -> o.getUserId().toString()).collect(Collectors.toList());
        String candidateUsers = String.join(",", userIds);
        return candidateUsers;
    }

    public List<AreaApplyTodoVo> getTodoList(List<Task> taskList) {
        List<AreaApplyTodoVo> results = new ArrayList<>();
        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查询出我们业务对象
            SchoolAreaApply schoolAreaApply = schoolAreaApplyMapper.selectById(new Long(businessKey));
            if(StringUtils.isNotNull(schoolAreaApply)){
                //转vo
                AreaApplyTodoVo areaApplyTodoVo = new AreaApplyTodoVo();
                BeanUtils.copyProperties(schoolAreaApply, areaApplyTodoVo);
                areaApplyTodoVo.setTaskId(taskImpl.getId());
                if (SUSPENDSTATE_PENDING.equals(taskImpl.getSuspensionState())) {
                    //挂起
                    areaApplyTodoVo.setTaskName(PENDING);
                } else {
                    areaApplyTodoVo.setTaskName(taskImpl.getName());
                }
                results.add(areaApplyTodoVo);
            }
        }
        return results;
    }



}
