package com.seer.teach.pay.admin.pay.service;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AESUtils;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.pay.admin.pay.controller.req.AdminPayChannelSaveReq;
import com.seer.teach.pay.admin.pay.controller.req.AdminPayChannelUpdateReq;
import com.seer.teach.pay.admin.pay.controller.resp.PayChannelResp;
import com.seer.teach.pay.admin.pay.convert.PayChannelConvert;
import com.seer.teach.pay.admin.pay.util.PayConfigEncryptUtils;
import com.seer.teach.pay.entity.PayChannelEntity;
import com.seer.teach.pay.service.IPayChannelService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class AdminPayChannelService {

    private final IPayChannelService payChannelService;

    /**
     * 获取支付渠道列表
     * @return
     */
    public List<PayChannelResp> getPayChannelList() {
        List<PayChannelEntity> payChanneList = payChannelService.list();
        AssertUtils.notEmpty(payChanneList, ResultCodeEnum.PAY_CHANNEL_IS_NOT_EXIST);
        return PayChannelConvert.INSTANCE.convertList(payChanneList);
    }

    /**
     * 新增支付渠道
     * @param params
     */
    public void addPayChannel(AdminPayChannelSaveReq params) {
        PayChannelEntity one = payChannelService.getOne(new LambdaQueryWrapper<PayChannelEntity>()
                .eq(PayChannelEntity::getChannelCode, params.getChannelCode())
                );
        AssertUtils.isNull(one, ResultCodeEnum.PAY_CHANNEL_ALREADY_EXISTS);
        // 获取配置信息并加密
        Map<String, String> encryptedConfig = PayConfigEncryptUtils.encryptConfig(params.getConfig());
        String json = JSON.toJSONString(encryptedConfig);

        // 转换实体并保存
        PayChannelEntity entity = PayChannelConvert.INSTANCE.convertTwo(params);
        entity.setConfigJson(json);
        payChannelService.save(entity);
        log.info("新增支付渠道成功：{}", params.getChannelName());
    }

    /**
     * 删除支付渠道
     * @param id
     */
    public void deletePayChannel(Integer id) {
        // 查询要删除的支付渠道列表
        log.info("准备删除支付渠道，ID：{}", id);
        PayChannelEntity channels = payChannelService.getById(id);
        AssertUtils.notNull(channels, ResultCodeEnum.PAY_CHANNEL_IS_NOT_EXIST);
        // 检查是否有启用的支付渠道（状态为1代表启用）
        if(channels.getStatus() == 1){
            AssertUtils.fail(ResultCodeEnum.ENABLED_PAY_CHANNEL_CANNOT_BE_DELETED);
        }
        payChannelService.removeById(id);
        log.info("删除支付渠道成功，删除的ID：{}", id);
    }

    /**
     * 修改支付渠道
     * @param params
     */
    public void updatePayChannel(Integer id,AdminPayChannelUpdateReq params) {
        PayChannelEntity payChannel = payChannelService.getById(id);
        AssertUtils.notNull(payChannel, ResultCodeEnum.PAY_CHANNEL_IS_NOT_EXIST);
        Map<String, String> encryptedConfig = PayConfigEncryptUtils.encryptConfig(params.getConfig());
        String json = JSON.toJSONString(encryptedConfig);
        PayChannelEntity payChannelEntity = PayChannelConvert.INSTANCE.convertThree(params);
        payChannelEntity.setId(id);
        payChannelEntity.setConfigJson(json);
        // 执行更新
        payChannelService.updateById(payChannelEntity);
        log.info("修改支付渠道成功：{}", payChannelEntity.getChannelName());
    }

    /**
     * 获取支付渠道详情
     * @param id
     * @return
     */
    public PayChannelResp getPayChannelDetail(Integer id) {
        PayChannelEntity payChannel = payChannelService.getById(id);
        AssertUtils.notNull(payChannel, ResultCodeEnum.PAY_CHANNEL_IS_NOT_EXIST);
        PayChannelResp resp = PayChannelConvert.INSTANCE.convertOne(payChannel);
        Map<String, String> decrypted = PayConfigEncryptUtils.decryptConfig(resp.getPayInfo());
        resp.setPayInfo(decrypted);
        return resp;
    }
}