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 com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.pay.domain.PayChannel;
import org.dromara.pay.domain.bo.PayChannelBo;
import org.dromara.pay.domain.vo.PayChannelVo;
import org.dromara.pay.mapper.PayChannelMapper;
import org.dromara.pay.service.PayChannelService;
import org.springframework.stereotype.Service;

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

/**
 * 支付渠道Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class PayChannelServiceImpl implements PayChannelService {

    private final PayChannelMapper baseMapper;

    /**
     * 查询支付渠道
     */
    @Override
    public PayChannelVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询支付渠道列表
     */
    @Override
    public TableDataInfo<PayChannelVo> queryPageList(PayChannelBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayChannel> lqw = buildQueryWrapper(bo);
        Page<PayChannelVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询支付渠道列表
     */
    @Override
    public List<PayChannelVo> queryList(PayChannelBo bo) {
        LambdaQueryWrapper<PayChannel> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayChannel> buildQueryWrapper(PayChannelBo bo) {
        LambdaQueryWrapper<PayChannel> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), PayChannel::getCode, bo.getCode());
        lqw.eq(bo.getStatus() != null, PayChannel::getStatus, bo.getStatus());
        lqw.eq(bo.getAppId() != null, PayChannel::getAppId, bo.getAppId());
        return lqw;
    }

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

    /**
     * 修改支付渠道
     */
    @Override
    public Boolean updateByBo(PayChannelBo bo) {
        PayChannel update = MapstructUtils.convert(bo, PayChannel.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PayChannel entity){
        // 校验渠道编码不能为空
        if (StringUtils.isBlank(entity.getCode())) {
            throw new ServiceException("渠道编码不能为空");
        }
        // 校验渠道编码唯一性（同一应用下）
        if (entity.getAppId() != null) {
            LambdaQueryWrapper<PayChannel> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PayChannel::getAppId, entity.getAppId())
                    .eq(PayChannel::getCode, entity.getCode());
            if (entity.getId() != null) {
                wrapper.ne(PayChannel::getId, entity.getId());
            }
            Long count = baseMapper.selectCount(wrapper);
            if (count > 0) {
                throw new ServiceException("该应用下渠道编码已存在");
            }
        }
        // 校验配置JSON格式
        if (StringUtils.isNotBlank(entity.getConfig())) {
            try {
                org.dromara.common.json.utils.JsonUtils.parseMap(entity.getConfig());
            } catch (Exception e) {
                throw new ServiceException("渠道配置JSON格式不正确");
            }
        }
    }

    /**
     * 批量删除支付渠道
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            // 校验渠道是否存在
            for (Long id : ids) {
                PayChannel channel = baseMapper.selectById(id);
                if (channel == null) {
                    throw new ServiceException("支付渠道不存在");
                }
                // 可以添加检查是否有关联的订单
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
