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

import java.util.ArrayList;
import java.util.HashMap;
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.DateUtils;
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.domain.device.SchoolDeviceRecord;
import yangtz.cs.liu.campus.domain.office.SchoolOfficePurchase;
import yangtz.cs.liu.campus.mapper.device.SchoolDeviceClaimMapper;
import yangtz.cs.liu.campus.mapper.device.SchoolDeviceRecordMapper;
import yangtz.cs.liu.campus.service.device.ISchoolDeviceClaimService;
import yangtz.cs.liu.campus.service.device.ISchoolDeviceRecordService;
import yangtz.cs.liu.campus.vo.device.*;
import yangtz.cs.liu.campus.vo.office.OfficeTodoListVO;

import javax.annotation.Resource;

import static com.core.constant.ProcessCommon.*;
import static com.core.constant.ProcessVariables.*;

/**
 * 设备维修Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-16
 */
@Service
public class SchoolDeviceRecordServiceImpl extends ServiceImpl<SchoolDeviceRecordMapper, SchoolDeviceRecord> implements ISchoolDeviceRecordService
{
    @Autowired
    private SchoolDeviceRecordMapper schoolDeviceRecordMapper;
    @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<RecordListVo> queryList(String submitState,RecordListVo record) {
        List<RecordListVo> recordList = schoolDeviceRecordMapper.queryList(submitState,record);
        if(recordList.size()<0 && recordList!=null){
            return new ArrayList<>();
        }
        for(RecordListVo recordListVo : recordList){
            if (StringUtils.isNotBlank(recordListVo.getInstanceId())){
                List<Task> taskList = taskService.createTaskQuery()
                        .processInstanceId(recordListVo.getInstanceId())
                        .list();
                if (!CollectionUtils.isEmpty(taskList)) {
                    TaskEntityImpl task = (TaskEntityImpl) taskList.get(0);
                    recordListVo.setTaskId(task.getId());
                    if (task.getSuspensionState() == 2) {
                        recordListVo.setTaskName("已挂起");
                        recordListVo.setSuspendState("2");
                    } else {
                        recordListVo.setTaskName(task.getName());
                        recordListVo.setSuspendState("1");
                    }
                } else {
                    // 已办结或者已撤销
                    recordListVo.setTaskName("已结束");
                }
            }else {
                recordListVo.setTaskName("未启动");
            }
        }
//        List<RecordListVo> list = new ArrayList<>();
//        for(SchoolDeviceRecord entity : recordList){
//            RecordListVo recordListVo = new RecordListVo();
//            BeanUtils.copyProperties(entity,recordListVo);
//            switch (recordListVo.getRepairType()){  //保修类型
//                case ("0"):recordListVo.setRepairType("故障维修");break;
//                case ("1"):recordListVo.setRepairType("设备更换");break;
//            }
//            list.add(recordListVo);
//        }
        return recordList;
    }

    @Override
    public List<RecordListVo> getByIds(List<Long> ids) {
        return schoolDeviceRecordMapper.getByIds(ids);
    }

    @Override
    public RecordByIdVo getInfo(Long id) {
        return schoolDeviceRecordMapper.getInfo(id);
    }

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


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


//    @Override
//    public List<RecordTodoVo> findTodoTasks(String key, SchoolDeviceRecord entity, String userId) {
//        List<RecordTodoVo> 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查询出我们业务对象
//            SchoolDeviceRecord schoolDeviceRecord = schoolDeviceRecordMapper.selectById(new Long(businessKey));
//            //转vo
//            RecordTodoVo recordTodoVo = new RecordTodoVo();
//            BeanUtils.copyProperties(schoolDeviceRecord,recordTodoVo);
//            switch (recordTodoVo.getRepairType()){  //保修类型
//                case ("0"):recordTodoVo.setRepairType("故障维修");break;
//                case ("1"):recordTodoVo.setRepairType("设备更换");break;
//            }
//            recordTodoVo.setTaskId(taskImpl.getId());
//            if (SUSPENDSTATE_PENDING.equals(taskImpl.getSuspensionState())) {
//                //挂起
//                recordTodoVo.setTaskName(PENDING);
//            }else{
//                recordTodoVo.setTaskName(taskImpl.getName());
//            }
//            list.add(recordTodoVo);
//        }
//        return list;
//    }




    @Override
    public List<RecordTodoVo> findDoneTasks(String key, SchoolDeviceRecord entity, String userId) {

        List<RecordTodoVo> 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查询出我们业务对象
            SchoolDeviceRecord schoolDeviceRecord = schoolDeviceRecordMapper.selectById(new Long(businessKey));
            if(StringUtils.isNotNull(schoolDeviceRecord)){
                //转vo
                RecordTodoVo recordTodoVo = new RecordTodoVo();
                BeanUtils.copyProperties(schoolDeviceRecord,recordTodoVo);
                switch (recordTodoVo.getRepairType()){  //保修类型
                    case ("0"):recordTodoVo.setRepairType("故障维修");break;
                    case ("1"):recordTodoVo.setRepairType("设备更换");break;
                }
                list.add(recordTodoVo);
            }
//            RecordTodoVo recordTodoVo = new RecordTodoVo();
//            BeanUtils.copyProperties(schoolDeviceRecord,recordTodoVo);
//            recordTodoVo.setTaskName(instance.getName());
            //list.add(recordTodoVo);
        }
        return list;
    }

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

    public List<RecordTodoVo> getTodoList(List<Task> taskList) {
        List<RecordTodoVo> 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查询出我们业务对象
            SchoolDeviceRecord schoolDeviceRecord = schoolDeviceRecordMapper.selectById(new Long(businessKey));
            if(StringUtils.isNotNull(schoolDeviceRecord)){
                //转vo
                RecordTodoVo recordTodoVo = new RecordTodoVo();
                BeanUtils.copyProperties(schoolDeviceRecord, recordTodoVo);
                switch (recordTodoVo.getRepairType()){  //保修类型
                    case ("0"):recordTodoVo.setRepairType("故障维修");break;
                    case ("1"):recordTodoVo.setRepairType("设备更换");break;
                }
                recordTodoVo.setTaskId(taskImpl.getId());

                if (SUSPENDSTATE_PENDING.equals(taskImpl.getSuspensionState())) {
                    //挂起
                    recordTodoVo.setTaskName(PENDING);
                } else {
                    recordTodoVo.setTaskName(taskImpl.getName());
                }
                results.add(recordTodoVo);
            }

        }
        return results;
    }

    /**
     * @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;
    }


}
