package com.gtiit.shr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.gtiit.shr.common.QueryPageBean;
import com.gtiit.shr.entity.enums.TaskNameEnum;
import com.gtiit.shr.entity.vo.ExceptionRequestVo;
import com.gtiit.shr.mapper.ExceptionRequestVoMapper;
import com.gtiit.shr.service.ExceptionService;
import com.gtiit.shr.utils.FinalParamUtil;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ExceptionServiceImpl extends ServiceImpl<ExceptionRequestVoMapper, ExceptionRequestVo> implements ExceptionService {
    @Autowired
    ExceptionRequestVoMapper exceptionRequestVoMapper;


    public int insertException(ExceptionRequestVo exceptionRequestVo) {
        return this.exceptionRequestVoMapper.insert(exceptionRequestVo);
    }

    public int insertBatchException(List<ExceptionRequestVo> exceptionRequestVos) {
        return this.exceptionRequestVoMapper.insertBatch(exceptionRequestVos);
    }

    public PageInfo<ExceptionRequestVo> findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        LambdaQueryWrapper<ExceptionRequestVo> query = new LambdaQueryWrapper();
        if (StringUtil.isNotEmpty(queryPageBean.getTaskType())) {
            query.eq(ExceptionRequestVo::getTaskType, queryPageBean.getTaskType());
        }

        if (StringUtil.isNotEmpty(queryPageBean.getType())) {
            query.eq(ExceptionRequestVo::getType, queryPageBean.getType());
        }

        if (queryPageBean.getStartDate() != null && queryPageBean.getEndDate() != null) {
            query.ge(ExceptionRequestVo::getExcuteDate, FinalParamUtil.getFirstDate(queryPageBean.getStartDate()));
            query.le(ExceptionRequestVo::getExcuteDate, FinalParamUtil.getLastDate(queryPageBean.getEndDate()));
        }

        if (StringUtil.isNotEmpty(queryPageBean.getIsSucess())) {
            query.eq(ExceptionRequestVo::getIsSucess, queryPageBean.getIsSucess());
        }

        query.orderByDesc(ExceptionRequestVo::getExcuteDate);
        PageInfo<ExceptionRequestVo> pageInfo = new PageInfo(this.exceptionRequestVoMapper.selectList(query));
        this.processResult(pageInfo);
        return pageInfo;
    }

    private void processResult(PageInfo<ExceptionRequestVo> pageInfo) {
        if (pageInfo != null) {
            List<ExceptionRequestVo> list = pageInfo.getList();
            list.forEach((a) -> {
                a.setTaskType(TaskNameEnum.fromVal(a.getTaskType()).getName());
            });
        }

    }
}
