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

import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.goOut.BpmOAGoOutCreateReqVO;
import cn.iocoder.yudao.framework.common.pojo.UploadUserFile;
import cn.iocoder.yudao.module.bpm.convert.oa.BpmOAGoOutConvert;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOAGoOutDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.BpmOAGoOutMapper;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceResultEnum;
import cn.iocoder.yudao.module.bpm.service.task.BpmHistoryProcessInstanceService;
import cn.iocoder.yudao.module.bpm.service.task.BpmProcessInstanceService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.OA_GOOut_NOT_EXISTS;

/**
 * OA 外出申请 Service 实现类
 *
 * @author 符溶馨

 */
@Service
@Validated
public class BpmOAGoOutServiceImpl extends BpmOABaseService implements BpmOAGoOutService{

    /**
     * OA 外出对应的流程定义 KEY
     */
    public static final String PROCESS_KEY = "oa_go_out_2";

    @Resource
    private BpmOAGoOutMapper goOutMapper;

    @Resource
    private BpmProcessInstanceService processInstanceService;

    @Resource
    private BpmHistoryProcessInstanceService historyProcessInstanceService;

    @Resource
    private AdminUserApi userApi;

    @Override
    public Long createGoOut(Long userId, BpmOAGoOutCreateReqVO createReqVO) {

        //插入OA 出差申请
        BpmOAGoOutDO goOut = BpmOAGoOutConvert.INSTANCE.convert(createReqVO).setUserId(userId)
                .setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
        goOutMapper.insert(goOut) ;

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

        // 将工作流的编号，更新到 OA 请假单中
        goOutMapper.updateById(new BpmOAGoOutDO().setId(goOut.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) ;
        }

        // 发起外出申请后，判断是否是当天的外出
        if (goOut.getStartTime().toLocalDate().isEqual(LocalDate.now())) {
            // 设置外勤打卡权限
            userApi.updateFieldworkType(Collections.singletonList(userId), 1);
        }

        return goOut.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGoOutResult(String processInstanceId, Long id, Integer result) {
        validateLeaveExists(id);

        // -- 自己取消
        // -- 审核拒绝
        if (BpmProcessInstanceResultEnum.REJECT.getResult().equals(result)
                || BpmProcessInstanceResultEnum.CANCEL.getResult().equals(result)
                || BpmProcessInstanceResultEnum.BACK.getResult().equals(result)) {

            // 发起外出申请后，设置关闭外勤打卡权限
            userApi.updateFieldworkType(Collections.singletonList(getLoginUserId()), 0);
        }

        goOutMapper.updateById(new BpmOAGoOutDO().setId(id).setResult(result));
    }

    @Override
    public BpmOAGoOutDO getByProcessInstanceId(String processInstanceId) {

        return goOutMapper.selectOne(BpmOAGoOutDO::getProcessInstanceId, processInstanceId);
    }

    @Override
    public BpmOAGoOutDO getGoOut(Long id) {
        return goOutMapper.selectById(id);
    }

    @Override
    public List<BpmOAGoOutDO> getGoOutByStartTime(String time) {

        return goOutMapper.selectList(new LambdaQueryWrapperX<BpmOAGoOutDO>()
                .likeIfPresent(BpmOAGoOutDO::getStartTime, time));
    }

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