package org.dromara.pay.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.pay.domain.PayApp;
import org.dromara.pay.domain.bo.PayAppBo;
import org.dromara.pay.domain.vo.PayAppVo;
import org.dromara.pay.mapper.PayAppMapper;
import org.dromara.pay.service.PayAppService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 支付应用Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class PayAppServiceImpl implements PayAppService {

    private final PayAppMapper baseMapper;

    /**
     * 查询支付应用
     */
    @Override
    public PayAppVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询支付应用列表
     */
    @Override
    public TableDataInfo<PayAppVo> queryPageList(PayAppBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayApp> lqw = buildQueryWrapper(bo);
        Page<PayAppVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询支付应用列表
     */
    @Override
    public List<PayAppVo> queryList(PayAppBo bo) {
        LambdaQueryWrapper<PayApp> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayApp> buildQueryWrapper(PayAppBo bo) {
        LambdaQueryWrapper<PayApp> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(bo.getName()), PayApp::getName, bo.getName());
        lqw.eq(bo.getStatus() != null, PayApp::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增支付应用
     */
    @Override
    public Boolean insertByBo(PayAppBo bo) {
        PayApp add = MapstructUtils.convert(bo, PayApp.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改支付应用
     */
    @Override
    public Boolean updateByBo(PayAppBo bo) {
        PayApp update = MapstructUtils.convert(bo, PayApp.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PayApp entity){
        // 校验应用名称不能为空
        if (StringUtils.isBlank(entity.getName())) {
            throw new ServiceException("应用名称不能为空");
        }
        // 校验回调地址格式
        if (StringUtils.isNotBlank(entity.getPayNotifyUrl())) {
            if (!entity.getPayNotifyUrl().startsWith("http://") && !entity.getPayNotifyUrl().startsWith("https://")) {
                throw new ServiceException("支付回调地址格式不正确");
            }
        }
        if (StringUtils.isNotBlank(entity.getRefundNotifyUrl())) {
            if (!entity.getRefundNotifyUrl().startsWith("http://") && !entity.getRefundNotifyUrl().startsWith("https://")) {
                throw new ServiceException("退款回调地址格式不正确");
            }
        }
    }

    /**
     * 批量删除支付应用
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            // 校验应用是否有关联的支付渠道
            for (Long id : ids) {
                // 这里可以添加检查是否有关联的支付渠道或订单
                // 暂时只检查应用是否存在
                PayApp app = baseMapper.selectById(id);
                if (app == null) {
                    throw new ServiceException("支付应用不存在");
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
