package cn.iocoder.yudao.module.bpm.service.oa;

import cn.iocoder.yudao.framework.common.pojo.UploadUserFile;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.salaryadjustment.BpmOASalaryAdjustmentCreateReqVO;
import cn.iocoder.yudao.module.bpm.convert.oa.BpmOASalaryAdjustmentConvert;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOASalaryAdjustmentDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.BpmOASalaryAdjustmentMapper;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceResultEnum;
import cn.iocoder.yudao.module.bpm.service.task.BpmHistoryProcessInstanceService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.OA_SALARY_NOT_EXISTS;

/**
 * OA 薪资付款申请 Service 实现类
 *
 * @author 符溶馨
 */
@Service
@Validated
public class BpmOASalaryAdjustmentServiceImpl extends BpmOABaseService implements BpmOASalaryAdjustmentService{

    /**
     * OA 薪资付款对应的流程定义 KEY
     */
    public static final String PROCESS_KEY = "oa_salary_adjustment_2";

    @Resource
    private BpmOASalaryAdjustmentMapper salaryMapper;

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Resource
    private BpmHistoryProcessInstanceService historyProcessInstanceService;

    @Override
    public Long createSalaryAdjustment(Long userId, BpmOASalaryAdjustmentCreateReqVO createReqVO) {

        //插入OA 薪资付款申请
        BpmOASalaryAdjustmentDO salary = BpmOASalaryAdjustmentConvert.INSTANCE.convert(createReqVO).setUserId(userId)
                .setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
        salaryMapper.insert(salary) ;

        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>();
        String processInstanceId = processInstanceApi.createProcessInstance(userId,
                new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                        .setVariables(processInstanceVariables).setBusinessKey(String.valueOf(salary.getId()))).getCheckedData();

        // 将工作流的编号，更新到 OA 用章单中
        salaryMapper.updateById(new BpmOASalaryAdjustmentDO().setId(salary.getId()).setProcessInstanceId(processInstanceId));

        // 判断是否为重新发起的流程
        if (createReqVO.getProcessInstanceId() != null && createReqVO.getResult() == 3) {

            historyProcessInstanceService.createHistoryProcessInstance(processInstanceId, createReqVO.getProcessInstanceId());
        }

        List<UploadUserFile> fileItems = createReqVO.getFileItems() ;
        //这里的逻辑，如果fileItems不为空，且有数据，那么说明是上传了附件的，则需要更工作流文件表对应的实例Id
        if (fileItems != null && !fileItems.isEmpty()) {
            uploadBpmFileProcessInstanceId(processInstanceId,fileItems) ;
        }
        return salary.getId();
    }

    @Override
    public void updateSalaryAdjustmentResult(Long id, Integer result) {
        validateLeaveExists(id);
        salaryMapper.updateById(new BpmOASalaryAdjustmentDO().setId(id).setResult(result));
    }

    private void validateLeaveExists(Long id) {
        if (salaryMapper.selectById(id) == null) {
            throw exception(OA_SALARY_NOT_EXISTS);
        }
    }

    @Override
    public BpmOASalaryAdjustmentDO getSalaryAdjustment(Long id) {

        return salaryMapper.selectById(id);
    }

    @Override
    public BpmOASalaryAdjustmentDO getByProcessInstanceId(String processInstanceId) {

        return salaryMapper.selectOne(BpmOASalaryAdjustmentDO::getProcessInstanceId, processInstanceId);
    }
}
