package com.srs.teacher.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.model.LoginUser;
import com.srs.common.doman.dto.ProcessResultDto;
import com.srs.common.exception.ServiceException;
import com.srs.common.utils.SecurityUtils;
import com.srs.flowable.service.IFlowDefinitionService;
import com.srs.teacher.domain.SysTeacherKpiFillingStuMgt;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.IdentityService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.teacher.mapper.SysTeacherKpiFillingMapper;
import com.srs.teacher.domain.SysTeacherKpiFilling;
import com.srs.teacher.service.ISysTeacherKpiFillingService;

/**
 * 业绩考核-个人填报Service业务层处理
 *
 * @author chc
 * @date 2024-06-06
 */
@Service
@Slf4j
public class SysTeacherKpiFillingServiceImpl extends ServiceImpl<SysTeacherKpiFillingMapper, SysTeacherKpiFilling> implements ISysTeacherKpiFillingService {
    @Autowired
    private SysTeacherKpiFillingMapper sysTeacherKpiFillingMapper;

    /**
     * 查询业绩考核-个人填报
     *
     * @param id 业绩考核-个人填报主键
     * @return 业绩考核-个人填报
     */
    @Override
    public SysTeacherKpiFilling selectSysTeacherKpiFillingById(Long id) {
        return sysTeacherKpiFillingMapper.selectSysTeacherKpiFillingById(id);
    }

    @Override
    public SysTeacherKpiFilling selectSysTeacherKpiFillingByFdyName(String fdyName, String fillingYear, String fillingMonth) {
        return sysTeacherKpiFillingMapper.selectSysTeacherKpiFillingByFdyName(fdyName, fillingYear, fillingMonth);
    }

    /**
     * 查询业绩考核-个人填报列表
     *
     * @param sysTeacherKpiFilling 业绩考核-个人填报
     * @return 业绩考核-个人填报
     */
    @Override
    public List<SysTeacherKpiFilling> selectSysTeacherKpiFillingList(SysTeacherKpiFilling sysTeacherKpiFilling) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        System.out.println(loginUser);
        return sysTeacherKpiFillingMapper.selectSysTeacherKpiFillingList(sysTeacherKpiFilling);
    }

    /**
     * 查询业绩考核-个人填报列表
     *
     * @return 业绩考核-个人填报
     */
    @Override
    public List<SysTeacherKpiFilling> selectListKpiFilling() {
        return sysTeacherKpiFillingMapper.selectListKpiFilling();
    }

    /**
     * 新增业绩考核-个人填报
     *
     * @param sysTeacherKpiFilling 业绩考核-个人填报
     * @return 结果
     */
    @Override
    public int insertSysTeacherKpiFilling(SysTeacherKpiFilling sysTeacherKpiFilling) {
        sysTeacherKpiFilling.setJobNumber(SecurityUtils.getLoginUser().getUser().getUserName());
        // 6-21改：前端获取的部门名称不正确
        sysTeacherKpiFilling.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
        // 如果前端没有填写 getFdyName 那么获取当前登录用户名称
        if (sysTeacherKpiFilling.getFdyName() == null) {
            sysTeacherKpiFilling.setFdyName(SecurityUtils.getLoginUser().getUser().getNickName());
        }
//        if (sysTeacherKpiFilling.getAuditStatus() != null && sysTeacherKpiFilling.getAuditStatus() == 0) {
//            // 开启工作流
//            ProcessResultDto processResultDto = startLeaveProcess(sysTeacherKpiFilling);
//        }
        if (sysTeacherKpiFilling.getId() != null) {
//            sysTeacherKpiFilling.setRoleAudit(0L);
//            sysTeacherKpiFilling.setAuditStatus(0L);
            return sysTeacherKpiFillingMapper.updateSysTeacherKpiFilling(sysTeacherKpiFilling);
        }
        // 判断填报记录是否填报
        SysTeacherKpiFilling teacherKpiFilling = sysTeacherKpiFillingMapper.selectSysTeacherKpiFillingByFdyName(sysTeacherKpiFilling.getFdyName(), sysTeacherKpiFilling.getFillingYear(), sysTeacherKpiFilling.getFillingMonth());
        if (teacherKpiFilling != null) {
            throw new ServiceException("申请已提交，请勿重复提交", 500);
        }
        return sysTeacherKpiFillingMapper.insertSysTeacherKpiFilling(sysTeacherKpiFilling);
    }

    /**
     * 修改业绩考核-个人填报
     *
     * @param sysTeacherKpiFilling 业绩考核-个人填报
     * @return 结果
     */
    @Override
    public int updateSysTeacherKpiFilling(SysTeacherKpiFilling sysTeacherKpiFilling) {
//        sysTeacherKpiFilling.setJobNumber(SecurityUtils.getLoginUser().getUser().getUserName());
        if (sysTeacherKpiFilling.getFdyName() == null) {
            sysTeacherKpiFilling.setFdyName(SecurityUtils.getLoginUser().getUser().getNickName());
        }
//        if (sysTeacherKpiFilling.getAuditStatus() != null && sysTeacherKpiFilling.getAuditStatus() == 0) {
//
//            // 开启工作流
//            ProcessResultDto processResultDto = startLeaveProcess(sysTeacherKpiFilling);
//
////            if (processResultDto != null) {
////                sysTeacherKpiFilling.setProcessInstanceId(processResultDto.getProcessInstanceId());
////                sysTeacherKpiFilling.setDeployId(processResultDto.getDeploymentId());
////            }
//        }
        return sysTeacherKpiFillingMapper.updateSysTeacherKpiFilling(sysTeacherKpiFilling);
    }

    @Override
    public int batchUpdateSysTeacherKpiFilling(List<SysTeacherKpiFilling> sysTeacherKpiFillingList) {
        return sysTeacherKpiFillingMapper.batchUpdateSysTeacherKpiFilling(sysTeacherKpiFillingList);
    }

    /**
     * 批量删除业绩考核-个人填报
     *
     * @param ids 需要删除的业绩考核-个人填报主键
     * @return 结果
     */
    @Override
    public int deleteSysTeacherKpiFillingByIds(Long[] ids) {
        return sysTeacherKpiFillingMapper.deleteSysTeacherKpiFillingByIds(ids);
    }

    /**
     * 删除业绩考核-个人填报信息
     *
     * @param id 业绩考核-个人填报主键
     * @return 结果
     */
    @Override
    public int deleteSysTeacherKpiFillingById(Long id) {
        return sysTeacherKpiFillingMapper.deleteSysTeacherKpiFillingById(id);
    }

    @Autowired
    IFlowDefinitionService flowDefinitionService;

    @Autowired
    TaskService taskService;

    @Autowired
    IdentityService identityService;

// ...

    private ProcessResultDto startLeaveProcess(SysTeacherKpiFilling sysTeacherKpiFilling) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("approval", SecurityUtils.getUserId());
        variables.put("deptId", SecurityUtils.getDeptId());

        AjaxResult ajaxResult = flowDefinitionService.startProcessInstanceById("flow_kpi:4:317504", variables);
        String code = ajaxResult.get("code").toString();
        if (code.equals("200")) {
            log.info("流程启动成功");

            Object data = ajaxResult.get("data");
            if (data instanceof ProcessResultDto) {
                ProcessResultDto dto = (ProcessResultDto) data;

                // 设置当前用户
                identityService.setAuthenticatedUserId(SecurityUtils.getUserId().toString());

                // 查询待办任务列表
                List<Task> tasks = taskService.createTaskQuery()
                        .processInstanceId(dto.getProcessInstanceId())
                        .taskAssignee(SecurityUtils.getUserId().toString())
                        .active()
                        .list();

                // 保存审核结果到任务变量中（通常是在完成任务时设置）
                // 这里只是示例，您可能需要根据实际情况调整
                Map<String, Object> completionVariables = new HashMap<>();
                completionVariables.put("approved", true);

                // 完成与特定实体相关的任务
                for (Task task : tasks) {
                    // 假设任务ID或其他属性与实体ID有关联
                    // 这里只是一个示例，您需要根据实际情况调整逻辑
                    String taskId = task.getId();
                    // ... 其他逻辑来确认这是否是应该完成的任务

                    // 完成任务
                    String id = taskService.getVariable(taskId, "id").toString();
                    if (id.equals(sysTeacherKpiFilling.getId().toString())) {
                        taskService.complete(task.getId(), completionVariables);
                    }
                }

                // 返回流程结果或其他信息（如果需要）
                return dto;
            } else {
                log.error("返回的数据不是ProcessResultDto类型: {}", data);
                // 处理错误或返回适当的响应
            }
        } else {
            log.error("启动流程实例失败: {}", ajaxResult);
            // 处理错误或返回适当的响应
        }

        // 默认返回null或抛出异常（取决于您的需求）
        return null;
    }
}
