package com.pusong.business.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.pusong.business.enums.ApproverStatusEnum;
import com.pusong.business.enums.ApproverTypeEnum;
import com.pusong.business.enums.TaskStatusEnum;
import com.pusong.business.service.approver.ApproverContainer;
import com.pusong.business.service.approver.ApproverService;
import com.pusong.common.core.exception.ServiceException;
import com.pusong.common.core.utils.MapstructUtils;
import com.pusong.common.core.utils.StringUtils;
import com.pusong.common.mybatis.core.page.TableDataInfo;
import com.pusong.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.pusong.business.domain.bo.PsApproverRecordBo;
import com.pusong.business.domain.vo.PsApproverRecordVo;
import com.pusong.business.domain.PsApproverRecord;
import com.pusong.business.mapper.PsApproverRecordMapper;
import com.pusong.business.service.IPsApproverRecordService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 审批记录Service业务层处理
 *
 * @author wls
 * @date 2024-08-05
 */
@RequiredArgsConstructor
@Service
public class PsApproverRecordServiceImpl implements IPsApproverRecordService {

    private final PsApproverRecordMapper baseMapper;
    private final ApproverContainer container;

    /**
     * 查询审批记录
     *
     * @param id 主键
     * @return 审批记录
     */
    @Override
    public PsApproverRecordVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询审批记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 审批记录分页列表
     */
    @Override
    public TableDataInfo<PsApproverRecordVo> queryPageList(PsApproverRecordBo bo, PageQuery pageQuery) {
        ApproverService service = container.getService(bo.getBusinessType());
        Page<PsApproverRecordVo> result = service.queryList(bo, pageQuery);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的审批记录列表
     *
     * @param bo 查询条件
     * @return 审批记录列表
     */
    @Override
    public List<PsApproverRecordVo> queryList(PsApproverRecordBo bo) {
        LambdaQueryWrapper<PsApproverRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PsApproverRecord> buildQueryWrapper(PsApproverRecordBo bo) {
        LambdaQueryWrapper<PsApproverRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getBusinessId() != null, PsApproverRecord::getBusinessId, bo.getBusinessId());
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessType()), PsApproverRecord::getBusinessType, bo.getBusinessType());
        lqw.eq(bo.getApplyDate() != null, PsApproverRecord::getApplyDate, bo.getApplyDate());
        lqw.eq(StringUtils.isNotBlank(bo.getApproverStatus()), PsApproverRecord::getApproverStatus, bo.getApproverStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getApplyDesc()), PsApproverRecord::getApplyDesc, bo.getApplyDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getApproverDesc()), PsApproverRecord::getApproverDesc, bo.getApproverDesc());
        return lqw;
    }

    /**
     * 审批
     *
     * @param operate （2 通过 3拒绝）
     * @param id 审批表id
     * @return
     */
    @Transactional
    public String approver(String operate, Long id,String desc){
        PsApproverRecord info = baseMapper.selectById(id);
        if(!StringUtils.equals(ApproverStatusEnum.INIT.getCode(),info.getApproverStatus())){
            throw new ServiceException("操作失败：该审批状态已变更");
        }
        ApproverService service = container.getService(info.getBusinessType());
        if(StringUtils.equals(ApproverStatusEnum.SUCCESS.getCode(),operate)){
            service.success(info);
            info.setApproverStatus(ApproverStatusEnum.SUCCESS.getCode());
        }else if (StringUtils.equals(ApproverStatusEnum.FAIL.getCode(),operate)){
            service.fail(info);
            info.setApproverStatus(ApproverStatusEnum.FAIL.getCode());
        }else{
            throw new ServiceException("操作失败：不支持的操作类型");
        }
        info.setApproverDate(new Date());
        info.setApproverDesc(desc);
        baseMapper.updateById(info);
        if(StringUtils.equals(info.getBusinessType(),ApproverTypeEnum.PAY.getCode())||
                StringUtils.equals(info.getBusinessType(),ApproverTypeEnum.ROLBACK.getCode())||
                StringUtils.equals(info.getBusinessType(),ApproverTypeEnum.TASKFINISH.getCode())){
            return info.getContractCode();
        }
        return null;
    }

    /**
     *  根据条件查询最后一条审批失败的原因
     * @return
     */
    public String getLastFail(String businessId,String contractCode,List<String> businessTypes){
        PsApproverRecord record = baseMapper.selectOne(Wrappers.<PsApproverRecord>lambdaQuery()
                .select(PsApproverRecord::getApproverStatus,PsApproverRecord::getApproverDesc)
                .eq(StringUtils.isNotBlank(businessId), PsApproverRecord::getBusinessId, businessId)
                .eq(StringUtils.isNotBlank(contractCode), PsApproverRecord::getContractCode, contractCode)
                .in(CollectionUtils.isNotEmpty(businessTypes), PsApproverRecord::getBusinessType, businessTypes)
                .orderByDesc(PsApproverRecord::getApplyDate).last("limit 1"));
        return  record!=null&&StringUtils.equals(ApproverStatusEnum.FAIL.getCode(),record.getApproverStatus())
                ?record.getApproverDesc():null;
    }
//    /**
//     * 新增审批记录
//     *
//     * @param bo 审批记录
//     * @return 是否新增成功
//     */
//    @Override
//    public Boolean insertByBo(PsApproverRecordBo bo) {
//        PsApproverRecord add = MapstructUtils.convert(bo, PsApproverRecord.class);
//        validEntityBeforeSave(add);
//        boolean flag = baseMapper.insert(add) > 0;
//        if (flag) {
//            bo.setId(add.getId());
//        }
//        return flag;
//    }

//    /**
//     * 修改审批记录
//     *
//     * @param bo 审批记录
//     * @return 是否修改成功
//     */
//    @Override
//    public Boolean updateByBo(PsApproverRecordBo bo) {
//        PsApproverRecord update = MapstructUtils.convert(bo, PsApproverRecord.class);
//        validEntityBeforeSave(update);
//        return baseMapper.updateById(update) > 0;
//    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PsApproverRecord entity){
        //TODO 做一些数据校验,如唯一约束
    }

//    /**
//     * 校验并批量删除审批记录信息
//     *
//     * @param ids     待删除的主键集合
//     * @param isValid 是否进行有效性校验
//     * @return 是否删除成功
//     */
//    @Override
//    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
//        if(isValid){
//            //TODO 做一些业务上的校验,判断是否需要校验
//        }
//        return baseMapper.deleteBatchIds(ids) > 0;
//    }
}
