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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
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.device.SchoolDeviceClaim;
import yangtz.cs.liu.campus.mapper.device.SchoolDeviceClaimMapper;
import yangtz.cs.liu.campus.mapper.device.SchoolDeviceMapper;
import yangtz.cs.liu.campus.service.device.ISchoolDeviceClaimService;
import yangtz.cs.liu.campus.vo.device.ClaimListVo;
import yangtz.cs.liu.campus.vo.device.ClaimTodoVo;
import javax.annotation.Resource;
import static com.core.constant.ProcessCommon.*;
import static com.core.constant.ProcessVariables.CHARGEUSERIDS;


/**
 * 设备领用Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-16
 */
@Service
public class SchoolDeviceClaimServiceImpl extends ServiceImpl<SchoolDeviceClaimMapper, SchoolDeviceClaim> implements ISchoolDeviceClaimService
{
    @Autowired
    private SchoolDeviceClaimMapper schoolDeviceClaimMapper;
    @Autowired
    private SchoolDeviceMapper schoolDeviceMapper;
    @Autowired
    private IProcessService processService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Resource
    private IdentityService identityService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ISysUserService userService;

    @Override
    public List<ClaimListVo> queryList(String submitState,ClaimListVo claim) {

        List<ClaimListVo> claimList = schoolDeviceClaimMapper.queryList(submitState,claim);
        if(claimList.size()<0 && claimList!=null){
            //throw new ServiceException("数据为空");
            return new ArrayList<>();
        }
        for(ClaimListVo claimListVo : claimList){
            if (StringUtils.isNotBlank(claimListVo.getInstanceId())){
                List<Task> taskList = taskService.createTaskQuery()
                        .processInstanceId(claimListVo.getInstanceId())
                        .list();
                if (!CollectionUtils.isEmpty(taskList)) {
                    TaskEntityImpl task = (TaskEntityImpl) taskList.get(0);
                    claimListVo.setTaskId(task.getId());
                    if (task.getSuspensionState() == 2) {
                        claimListVo.setTaskName("已挂起");
                        claimListVo.setSuspendState("2");
                    } else {
                        claimListVo.setTaskName(task.getName());
                        claimListVo.setSuspendState("1");
                    }
                } else {
                    // 已办结或者已撤销
                    claimListVo.setTaskName("已结束");
                }
            }else {
                claimListVo.setTaskName("未启动");
            }
        }
        return claimList;
    }

    @Override
    public ClaimListVo getInfo(Long id) {
        return schoolDeviceClaimMapper.getInfo(id);
    }

    @Override
    public int submitApply(SchoolDeviceClaim schoolDeviceClaim, String userName, String type, Map<String, Object> variables) {
        // 业务type 表示是什么流程类型, businessKey表示场地申请id
        String businessKey = schoolDeviceClaim.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();
        //与我们的业务表开始建立关系
        schoolDeviceClaim.setInstanceId(instanceId);
        return schoolDeviceClaimMapper.updateById(schoolDeviceClaim);
    }

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

//    @Override
//    public List<ClaimTodoVo> findTodoTasks(String key, SchoolDeviceClaim entity, String userId) {
//        List<ClaimTodoVo> 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查询出我们业务对象
//            SchoolDeviceClaim schoolDeviceClaim = schoolDeviceClaimMapper.selectById(new Long(businessKey));
//            //转vo
//            ClaimTodoVo claimTodoVo = new ClaimTodoVo();
//            BeanUtils.copyProperties(schoolDeviceClaim,claimTodoVo);
//            String deviceName = schoolDeviceMapper.selectById(schoolDeviceClaim.getDeviceId()).getDeviceName();
//            claimTodoVo.setDeviceName(deviceName);
//            claimTodoVo.setTaskId(taskImpl.getId());
//            if (SUSPENDSTATE_PENDING.equals(taskImpl.getSuspensionState())) {
//                //挂起
//                claimTodoVo.setTaskName(PENDING);
//            }else{
//                claimTodoVo.setTaskName(taskImpl.getName());
//            }
//            list.add(claimTodoVo);
//        }
//        return list;
//    }

    @Override
    public List<ClaimTodoVo> findDoneTasks(String key, SchoolDeviceClaim entity, String userId) {

        List<ClaimTodoVo> 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查询出我们业务对象
            SchoolDeviceClaim schoolDeviceClaim = schoolDeviceClaimMapper.selectById(new Long(businessKey));
            if(StringUtils.isNotNull(schoolDeviceClaim)){
                //转vo
                ClaimTodoVo claimTodoVo = new ClaimTodoVo();
                BeanUtils.copyProperties(schoolDeviceClaim,claimTodoVo);
                String deviceName = schoolDeviceMapper.selectById(schoolDeviceClaim.getDeviceId()).getDeviceName();
                claimTodoVo.setDeviceName(deviceName);
                claimTodoVo.setTaskName(instance.getName());
                list.add(claimTodoVo);
            }

        }
        return list;
    }

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

    /**
     * @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<ClaimTodoVo> getTodoList(List<Task> taskList) {
        List<ClaimTodoVo> 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查询出我们业务对象
            SchoolDeviceClaim schoolDeviceClaim = schoolDeviceClaimMapper.selectById(new Long(businessKey));
            if(StringUtils.isNotNull(schoolDeviceClaim)){
                //转vo
                ClaimTodoVo claimTodoVo = new ClaimTodoVo();
                BeanUtils.copyProperties(schoolDeviceClaim, claimTodoVo);
                String deviceName = schoolDeviceMapper.selectById(schoolDeviceClaim.getDeviceId()).getDeviceName();
                claimTodoVo.setDeviceName(deviceName);
                claimTodoVo.setTaskId(taskImpl.getId());
                if (SUSPENDSTATE_PENDING.equals(taskImpl.getSuspensionState())) {
                    //挂起
                    claimTodoVo.setTaskName(PENDING);
                } else {
                    claimTodoVo.setTaskName(taskImpl.getName());
                }
                results.add(claimTodoVo);
            }

        }
        return results;
    }

}
