package com.ruoyi.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.PosStoreNewebpay;
import com.ruoyi.system.domain.dto.StoreNewebpayCredentialDto;
import com.ruoyi.system.domain.vo.PosStoreNewebpayVo;
import com.ruoyi.system.mapper.PosStoreNewebpayMapper;
import com.ruoyi.system.service.IPosStoreNewebpayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 门店蓝新金流支付凭证 Service 实现（纯 DB 操作）。
 *
 * <p>仿 {@link PosStoreEzpayServiceImpl} 状态机与审计字段处理。
 *
 * @author ruoyi
 * @date 2026-06-22
 */
@Service
public class PosStoreNewebpayServiceImpl implements IPosStoreNewebpayService {

    @Autowired
    private PosStoreNewebpayMapper posStoreNewebpayMapper;

    private static final int STATUS_NOT_APPLIED = 0;
    private static final int STATUS_APPLYING = 1;
    private static final int STATUS_ENABLED = 2;

    @Override
    public PosStoreNewebpay getEnabledConfig(Long storeId) {
        PosStoreNewebpay row = getOrCreateByStoreId(storeId);
        if (row == null || row.getId() == null) {
            return null;
        }
        boolean opened = Integer.valueOf(STATUS_ENABLED).equals(row.getNewebpayStatus());
        boolean enabled = row.getIsEnabled() != null && row.getIsEnabled() == 1;
        return (opened && enabled) ? row : null;
    }

    @Override
    public PosStoreNewebpay getOrCreateByStoreId(Long storeId) {
        if (storeId == null) {
            return null;
        }
        PosStoreNewebpay row = posStoreNewebpayMapper.selectOne(
                new LambdaQueryWrapper<PosStoreNewebpay>().eq(PosStoreNewebpay::getStoreId, storeId));
        if (row == null) {
            row = new PosStoreNewebpay();
            row.setStoreId(storeId);
            row.setNewebpayStatus(STATUS_NOT_APPLIED);
            row.setIsEnabled(1);
        }
        return row;
    }

    @Override
    public PosStoreNewebpay getByMerchantId(String merchantId) {
        if (merchantId == null || merchantId.isEmpty()) {
            return null;
        }
        return posStoreNewebpayMapper.selectOne(
                new LambdaQueryWrapper<PosStoreNewebpay>().eq(PosStoreNewebpay::getMerchantId, merchantId));
    }

    @Override
    public List<PosStoreNewebpayVo> selectNewebpayStoreList(PosStoreNewebpayVo query) {
        return posStoreNewebpayMapper.selectNewebpayStoreList(query);
    }

    @Override
    public PosStoreNewebpayVo selectNewebpayStoreDetail(Long storeId) {
        PosStoreNewebpayVo vo = posStoreNewebpayMapper.selectNewebpayStoreDetail(storeId);
        if (vo == null) {
            throw new ServiceException("门店不存在");
        }
        return vo;
    }

    @Override
    public int apply(Long storeId) {
        PosStoreNewebpay row = getOrCreateByStoreId(storeId);
        if (!Integer.valueOf(STATUS_NOT_APPLIED).equals(row.getNewebpayStatus())) {
            throw new ServiceException("当前状态不允许发起申请");
        }
        row.setNewebpayStatus(STATUS_APPLYING);
        row.setApplyTime(new Date());
        return saveOrUpdate(row);
    }

    @Override
    public int enableWithCredentials(StoreNewebpayCredentialDto dto) {
        PosStoreNewebpay row = getOrCreateByStoreId(dto.getStoreId());
        row.setMerchantId(dto.getMerchantId());
        row.setHashKey(dto.getHashKey());
        row.setHashIv(dto.getHashIv());
        if (StrUtil.isNotBlank(dto.getEnabledPayments())) {
            row.setEnabledPayments(dto.getEnabledPayments().toUpperCase());
        } else {
            row.setEnabledPayments("CREDIT");
        }
        row.setNewebpayStatus(STATUS_ENABLED);
        row.setIsEnabled(1);
        row.setApprovedTime(new Date());
        row.setLastVerifyResult("PASS");
        return saveOrUpdate(row);
    }

    @Override
    public int toggleEnable(Long storeId) {
        PosStoreNewebpay row = getOrCreateByStoreId(storeId);
        if (!Integer.valueOf(STATUS_ENABLED).equals(row.getNewebpayStatus())) {
            throw new ServiceException("仅已开通门店可停用/恢复");
        }
        int next = Integer.valueOf(1).equals(row.getIsEnabled()) ? 0 : 1;
        row.setIsEnabled(next);
        return saveOrUpdate(row);
    }

    @Override
    public int reset(Long storeId) {
        PosStoreNewebpay row = getOrCreateByStoreId(storeId);
        row.setNewebpayStatus(STATUS_APPLYING);
        row.setApprovedTime(null);
        return saveOrUpdate(row);
    }

    @Override
    public int setEnabledPayments(Long storeId, String enabledPayments) {
        PosStoreNewebpay row = getOrCreateByStoreId(storeId);
        row.setEnabledPayments(enabledPayments == null || enabledPayments.isEmpty()
                ? "CREDIT" : enabledPayments.toUpperCase());
        return saveOrUpdate(row);
    }

    @Override
    public int recordVerifyResult(Long storeId, String result) {
        PosStoreNewebpay row = getOrCreateByStoreId(storeId);
        row.setLastVerifyResult(truncate(result));
        return saveOrUpdate(row);
    }

    // ===== 内部辅助 =====

    private int saveOrUpdate(PosStoreNewebpay row) {
        Date now = new Date();
        String user = currentUser();
        if (row.getId() == null) {
            row.setCreateTime(now);
            row.setUpdateTime(now);
            row.setCreateBy(user);
            row.setUpdateBy(user);
            return posStoreNewebpayMapper.insert(row);
        }
        row.setUpdateTime(now);
        row.setUpdateBy(user);
        return posStoreNewebpayMapper.updateById(row);
    }

    private String currentUser() {
        try {
            return SecurityUtils.getUsername();
        } catch (Exception e) {
            return "system";
        }
    }

    private static String truncate(String s) {
        if (s == null) {
            return "";
        }
        return s.length() > 240 ? s.substring(0, 240) : s;
    }
}
