package com.pusong.workflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.pusong.common.core.domain.event.ProcessEvent;
import com.pusong.common.core.domain.event.ProcessTaskEvent;
import com.pusong.common.core.enums.BusinessStatusEnum;
import com.pusong.common.core.service.WorkflowService;
import com.pusong.common.core.utils.MapstructUtils;
import com.pusong.common.core.utils.StreamUtils;
import com.pusong.common.core.utils.StringUtils;
import com.pusong.common.mybatis.core.domain.BaseEntity;
import com.pusong.common.mybatis.core.page.PageQuery;
import com.pusong.common.mybatis.core.page.TableDataInfo;
import com.pusong.workflow.domain.SysUserLeave;
import com.pusong.workflow.domain.bo.SysUserLeaveBo;
import com.pusong.workflow.domain.vo.SysUserLeaveVo;
import com.pusong.workflow.mapper.SysUserLeaveMapper;
import com.pusong.workflow.service.ISysUserLeaveService;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 请假Service业务层处理
 *
 * @author may
 * @date 2023-07-21
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SysUserLeaveServiceImpl implements ISysUserLeaveService {

    private final SysUserLeaveMapper baseMapper;
    private final WorkflowService workflowService;

    /**
     * 查询请假
     */
    @Override
    public SysUserLeaveVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询请假列表
     */
    @Override
    public TableDataInfo<SysUserLeaveVo> queryPageList(SysUserLeaveBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserLeave> lqw = buildQueryWrapper(bo);
        Page<SysUserLeaveVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询请假列表
     */
    @Override
    public List<SysUserLeaveVo> queryList(SysUserLeaveBo bo) {
        LambdaQueryWrapper<SysUserLeave> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserLeave> buildQueryWrapper(SysUserLeaveBo bo) {
        LambdaQueryWrapper<SysUserLeave> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLeaveType()), SysUserLeave::getLeaveType, bo.getLeaveType());
        lqw.ge(bo.getStartLeaveDays() != null, SysUserLeave::getLeaveDays, bo.getStartLeaveDays());
        lqw.le(bo.getEndLeaveDays() != null, SysUserLeave::getLeaveDays, bo.getEndLeaveDays());
        lqw.orderByDesc(BaseEntity::getCreateTime);
        return lqw;
    }

    /**
     * 新增请假
     */
    @Override
    public SysUserLeaveVo insertByBo(SysUserLeaveBo bo) {
        SysUserLeave add = MapstructUtils.convert(bo, SysUserLeave.class);
        if (StringUtils.isBlank(add.getStatus())) {
            add.setStatus(BusinessStatusEnum.DRAFT.getStatus());
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return MapstructUtils.convert(add, SysUserLeaveVo.class);
    }

    /**
     * 修改请假
     */
    @Override
    public SysUserLeaveVo updateByBo(SysUserLeaveBo bo) {
        SysUserLeave update = MapstructUtils.convert(bo, SysUserLeave.class);
        baseMapper.updateById(update);
        return MapstructUtils.convert(update, SysUserLeaveVo.class);
    }

    /**
     * 批量删除请假
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        List<String> idList = StreamUtils.toList(ids, String::valueOf);
        workflowService.deleteRunAndHisInstance(idList);
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 总体流程监听(例如: 提交 退回 撤销 终止 作废等)
     * 正常使用只需#processEvent.key=='leave1'
     * 示例为了方便则使用startsWith匹配了全部示例key
     *
     * @param processEvent 参数
     */
    @EventListener(condition = "#processEvent.key.startsWith('leave')")
    public void processHandler(ProcessEvent processEvent) {
        log.info("当前任务执行了{}", processEvent.toString());
        SysUserLeave testLeave = baseMapper.selectById(Long.valueOf(processEvent.getBusinessKey()));
        testLeave.setStatus(processEvent.getStatus());
        if (processEvent.isSubmit()) {
            testLeave.setStatus(BusinessStatusEnum.WAITING.getStatus());
        }
        baseMapper.updateById(testLeave);
    }

    /**
     * 执行办理任务监听
     * 示例：也可通过  @EventListener(condition = "#processTaskEvent.key=='leave1'")进行判断
     * 在方法中判断流程节点key
     * if ("xxx".equals(processTaskEvent.getTaskDefinitionKey())) {
     * //执行业务逻辑
     * }
     *
     * @param processTaskEvent 参数
     */
    @EventListener(condition = "#processTaskEvent.key=='leave1' && #processTaskEvent.taskDefinitionKey=='Activity_14633hx'")
    public void processTaskHandler(ProcessTaskEvent processTaskEvent) {
        log.info("当前任务执行了{}", processTaskEvent.toString());
        SysUserLeave testLeave = baseMapper.selectById(Long.valueOf(processTaskEvent.getBusinessKey()));
        testLeave.setStatus(BusinessStatusEnum.WAITING.getStatus());
        baseMapper.updateById(testLeave);
    }
}
