package com.yc.ship.module.ota.service.distributorselfrecharge;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.security.core.LoginUser;
import com.yc.ship.framework.tenant.core.util.TenantUtils;
import com.yc.ship.module.ota.controller.admin.distributor.vo.LoginTypeRespVO;
import com.yc.ship.module.ota.controller.admin.distributorselfrecharge.vo.DistributorSelfRechargePageReqVO;
import com.yc.ship.module.ota.controller.admin.distributorselfrecharge.vo.DistributorSelfRechargeSaveReqVO;
import com.yc.ship.module.ota.controller.admin.distributorselfrecharge.vo.DistributorSelfRechargeSimpleRespVO;
import com.yc.ship.module.ota.dal.dataobject.distributor.DistributorDO;
import com.yc.ship.module.ota.dal.dataobject.distributorselfrecharge.DistributorSelfRechargeDO;
import com.yc.ship.module.ota.dal.mysql.distributorselfrecharge.DistributorSelfRechargeMapper;
import com.yc.ship.module.ota.service.distributor.DistributorService;
import com.yc.ship.module.ota.service.tradelog.TradeLogService;
import com.yc.ship.module.ota.util.OtaAuthUtils;
import com.yc.ship.module.system.api.user.AdminUserApi;
import com.yc.ship.module.system.api.user.dto.AdminUserRespDTO;
import com.yc.ship.module.trade.api.dto.PayOrderReqDTO;
import com.yc.ship.module.trade.api.dto.PayOrderRespDTO;
import com.yc.ship.module.trade.api.trade.TradeApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicReference;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception0;


/**
 * 自助充值明细 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
@Slf4j
public class DistributorSelfRechargeServiceImpl implements DistributorSelfRechargeService {


    @Resource
    private DistributorSelfRechargeMapper distributorSelfRechargeMapper;

    @Resource
    private DistributorService distributorService;

    @Resource
    private TradeLogService tradeLogService;

    @Resource
    private OtaAuthUtils otaAuthUtils;
    @Resource
    private AdminUserApi userApi;

    @Resource
    private TradeApi tradeApi;



    @Override
    public DistributorSelfRechargeSimpleRespVO createDistributorSelfRecharge(DistributorSelfRechargeSaveReqVO createReqVO) {
        LoginUser loginUser = otaAuthUtils.getAgencyLoginUser();
        LoginTypeRespVO loginType = distributorService.getLoginType();
        if (loginType.getType() == 3) {
            throw exception0(11_028, "当前为平台端，不能进行自助充值删除");
        }
        AdminUserRespDTO respDTO = userApi.getUser(loginUser.getId());

        // 处理对公转账逻辑
        if (createReqVO.getPayType() == 9) {
            // 对公转账逻辑：仅保存数据，不调用支付接口
            return handlePublicTransfer(createReqVO, loginType,respDTO);
        } else {
            // 插入
            DistributorSelfRechargeDO distributorSelfRecharge = BeanUtils.toBean(createReqVO, DistributorSelfRechargeDO.class);
            Long id = IdWorker.getId(distributorSelfRecharge);
            String rechargeNo = "CZ" + id;
            distributorSelfRecharge.setId(id);
            distributorSelfRecharge.setDistributorId(loginType.getDistributorId());
            distributorSelfRecharge.setRechargeState(0);
            distributorSelfRecharge.setAccountId(respDTO.getId());
            distributorSelfRecharge.setAccountName(respDTO.getNickname());
            distributorSelfRecharge.setCreator(respDTO.getId().toString());
            distributorSelfRecharge.setTenantId(loginType.getTenantId());

            PayOrderReqDTO payOrderReqDTO = new PayOrderReqDTO();
            payOrderReqDTO.setAccountId(respDTO.getId().toString());
            payOrderReqDTO.setAccountName(respDTO.getNickname());
            payOrderReqDTO.setPayType(distributorSelfRecharge.getPayType());
            payOrderReqDTO.setPayAmount(distributorSelfRecharge.getMoney());
            payOrderReqDTO.setPaySource(101);
            payOrderReqDTO.setOrderId(id);
            payOrderReqDTO.setPayExtraType(0);
            PayOrderReqDTO.PayParams payParams = new PayOrderReqDTO.PayParams();
            payParams.setSubject(loginType.getDistributorName() + "自助充值");
            payParams.setBody(loginType.getDistributorName() + "自助充值");
            payParams.setParam(rechargeNo);
            payOrderReqDTO.setPayParams(payParams);
            PayOrderRespDTO payOrderRespDTO = tradeApi.payOuterOrder(payOrderReqDTO).getCheckedData();
            distributorSelfRecharge.setRechargeNo(payOrderRespDTO.getOrderPayId().toString());
            TenantUtils.execute(loginType.getTenantId(), () -> {
                distributorSelfRechargeMapper.insert(distributorSelfRecharge);
            });
            DistributorSelfRechargeSimpleRespVO respVO = BeanUtils.toBean(distributorSelfRecharge, DistributorSelfRechargeSimpleRespVO.class);
            respVO.setPayPlatResult(payOrderRespDTO.getPayPlatResult());
            return respVO;
        }
    }

    private DistributorSelfRechargeSimpleRespVO handlePublicTransfer(
            DistributorSelfRechargeSaveReqVO createReqVO,
            LoginTypeRespVO loginType,AdminUserRespDTO respDTO) {
        Long distributorId = loginType.getDistributorId();
        // 1. 校验分销商信息
        DistributorDO distributor = distributorService.getDistributor(loginType.getDistributorId());
        if (distributor == null || distributor.getCmbShortNo() == null) {
            throw exception0(11_029, "未能找到对应分销商或招行短号信息");
        }

        // 2. 生成对公账号
        String bankAccount = "717902731210902" + distributor.getCmbShortNo();

        // 3. 构建充值记录对象
        /*DistributorSelfRechargeDO rechargeDO = new DistributorSelfRechargeDO();
        org.springframework.beans.BeanUtils.copyProperties(createReqVO, rechargeDO);
        rechargeDO.setId(IdWorker.getId());
        rechargeDO.setDistributorId(loginType.getDistributorId());
        rechargeDO.setRechargeState(0); // 初始状态：待处理
        rechargeDO.setAccountId(respDTO.getId());
        rechargeDO.setAccountName(respDTO.getNickname());
        rechargeDO.setCreator(respDTO.getId().toString());
        rechargeDO.setTenantId(loginType.getTenantId());*/

        // 4. 保存到数据库
        /*TenantUtils.execute(loginType.getTenantId(), () -> {
            distributorSelfRechargeMapper.insert(rechargeDO);
        });*/

        // 5. 构造响应
        DistributorSelfRechargeSimpleRespVO respVO = new DistributorSelfRechargeSimpleRespVO();
        respVO.setDistributorId(distributorId);
        respVO.setBankAccount(bankAccount);
        return respVO;
    }


    @Override
    public void updateDistributorSelfRecharge(DistributorSelfRechargeSaveReqVO updateReqVO) {
        // 校验存在
        validateDistributorSelfRechargeExists(updateReqVO.getId());
        // 更新
        DistributorSelfRechargeDO updateObj = BeanUtils.toBean(updateReqVO, DistributorSelfRechargeDO.class);
        distributorSelfRechargeMapper.updateById(updateObj);
    }

    @Override
    public void deleteDistributorSelfRecharge(Long id) {
        LoginTypeRespVO loginType = distributorService.getLoginType();
        if (loginType.getType() == 3) {
            throw exception0(11_028, "当前为平台端，不能进行自助充值删除");
        }
        TenantUtils.execute(loginType.getTenantId(), () -> {
            // 校验存在
            validateDistributorSelfRechargeExists(id);
            // 删除
            distributorSelfRechargeMapper.deleteById(id);
        });
    }

    private void validateDistributorSelfRechargeExists(Long id) {
        if (distributorSelfRechargeMapper.selectById(id) == null) {
            throw exception0(11_028, "不存在");
        }
    }

    @Override
    public DistributorSelfRechargeDO getDistributorSelfRecharge(Long id) {
        LoginTypeRespVO loginType = distributorService.getLoginType();
        if (loginType.getType() == 3) {
            return distributorSelfRechargeMapper.selectById(id);
        }
        AtomicReference<DistributorSelfRechargeDO> rechargeReference = new AtomicReference<>();
        TenantUtils.execute(loginType.getTenantId(), () -> {
            rechargeReference.set(distributorSelfRechargeMapper.selectById(id));
        });
        return rechargeReference.get();
    }

    @Override
    public PageResult<DistributorSelfRechargeDO> getDistributorSelfRechargePage(DistributorSelfRechargePageReqVO pageReqVO) {
        LoginTypeRespVO loginType = distributorService.getLoginType();
        if (loginType.getType() != 3) {
            pageReqVO.setDistributorId(loginType.getDistributorId());
            AtomicReference<PageResult<DistributorSelfRechargeDO>> pageReference = new AtomicReference<>();
            TenantUtils.execute(loginType.getTenantId(), () -> {
                pageReference.set(distributorSelfRechargeMapper.selectPage(pageReqVO));
            });
            return pageReference.get();
        }
        return distributorSelfRechargeMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long distributorSelfRecharge(Long id, String payOrderId, Integer payStatus) {
        log.info("自助充值支付完成：{}，{},{}", id, payOrderId, payStatus);
        AtomicReference<Long> tradeLogId = new AtomicReference<>();
        DistributorSelfRechargeDO distributorSelfRecharge = getDistributorSelfRecharge(id);
        if (distributorSelfRecharge.getRechargeState() == 1) {
            throw exception0(11_029, "当前自助充值已处理");
        }
        TenantUtils.execute(distributorSelfRecharge.getTenantId(), () -> {
            distributorSelfRecharge.setRechargeState(payStatus == 1 ? 1 : -1);
            tradeLogId.set(tradeLogService.distributorRecharge(distributorSelfRecharge.getDistributorId(), id, 11, distributorSelfRecharge.getAccountId(), distributorSelfRecharge.getAccountName(), distributorSelfRecharge.getMoney()));
            distributorSelfRechargeMapper.updateById(distributorSelfRecharge);
        });
        return tradeLogId.get();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long distributorCMBRecharge(Long id, String payOrderId, Integer payStatus) {
        log.info("对公转账充值支付完成：{}，{},{}", id, payOrderId, payStatus);
        AtomicReference<Long> tradeLogId = new AtomicReference<>();
        DistributorSelfRechargeDO distributorSelfRecharge = getDistributorSelfRecharge(id);
        if (distributorSelfRecharge.getRechargeState() == 1) {
            throw exception0(11_029, "当前自助充值已处理");
        }
        TenantUtils.execute(distributorSelfRecharge.getTenantId(), () -> {
            distributorSelfRecharge.setRechargeState(payStatus == 1 ? 1 : -1);
            tradeLogId.set(tradeLogService.distributorRecharge(distributorSelfRecharge.getDistributorId(), id, 11, distributorSelfRecharge.getAccountId(), distributorSelfRecharge.getAccountName(), distributorSelfRecharge.getMoney()));
            distributorSelfRechargeMapper.updateById(distributorSelfRecharge);
        });
        return tradeLogId.get();
    }

}
