package cn.palmte.work.service;

import cn.palmte.work.model.ProjectTaskRecord;
import cn.palmte.work.model.ProjectTaskRecordRepository;
import cn.palmte.work.utils.ActUtil;
import cn.palmte.work.utils.InterfaceUtil;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.jfunc.common.db.QueryHelper;
import top.jfunc.common.db.utils.Pagination;

import java.util.Date;
import java.util.List;


@Service
public class ProjectTaskRecordService {
    private static final Logger logger = LoggerFactory.getLogger(ProjectTaskRecordService.class);
    @Autowired
    private ProjectTaskRecordRepository projectTaskRecordRepository;

    @Autowired
    Pagination pagination;

    @Autowired
    private ActUtil actUtil;


    /**
     * 保存审批任务记录
     *
     * @param task
     * @param status
     * @param comment
     */
    public void saveTaskRecord(int projectId, Task task, int status, int taskIndex, String comment, String fileUrl) {
        task.getProcessDefinitionId();
        ProjectTaskRecord record = new ProjectTaskRecord();
        record.setProjectId(projectId);
        record.setProcDefId(task.getProcessDefinitionId());
        record.setProcInsId(task.getProcessInstanceId());
        record.setTaskDefKey(task.getTaskDefinitionKey());
        record.setTaskName(task.getName());
        record.setTaskComment(comment);
        record.setTaskStatus(status);
        record.setAssigneeId(InterfaceUtil.getAdminId() + "");
        record.setAssigneeName(InterfaceUtil.getAdmin().getRealName());
        record.setTaskIndex(taskIndex);
        record.setCreateTime(new Date());
        record.setFileUrl(fileUrl);
        try {
            projectTaskRecordRepository.save(record);
        } catch (Exception e) {
            logger.error("", e);
        }
    }


    /**
     * 根据项目id查询审批任务记录
     *
     * @param projectId
     * @return
     */
    public List<ProjectTaskRecord> list(int projectId) {
        String select = "tr.*, su.role_name";
        QueryHelper queryHelper = new QueryHelper(select, " project_task_record tr LEFT JOIN sys_user su on su.id=tr.assignee_id  ");
        queryHelper.addCondition("tr.project_id=?", projectId);
        queryHelper.addOrderProperty("tr.create_time", true);
        return pagination.find(queryHelper.getSql(), ProjectTaskRecord.class);
    }


}
