package com.qnfhq.modules.c2c.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qnfhq.common.exception.RenException;
import com.qnfhq.common.service.impl.BaseServiceImpl;
import com.qnfhq.common.service.impl.CrudServiceImpl;
import com.qnfhq.common.utils.MessageUtils;
import com.qnfhq.common.utils.Result;
import com.qnfhq.modules.c2c.dao.C2cMerchantDao;
import com.qnfhq.modules.c2c.dto.C2cMerchantApplyDTO;
import com.qnfhq.modules.c2c.dto.C2cMerchantDTO;
import com.qnfhq.modules.c2c.entity.C2cMerchantConfigEntity;
import com.qnfhq.modules.c2c.entity.C2cMerchantEntity;
import com.qnfhq.modules.c2c.enums.MerchantStatusEnum;
import com.qnfhq.modules.c2c.service.C2cMerchantConfigService;
import com.qnfhq.modules.c2c.service.C2cMerchantService;
import cn.hutool.core.util.StrUtil;
import com.qnfhq.modules.user.entity.AppAssetEntity;
import com.qnfhq.modules.user.entity.AppUserDetailEntity;
import com.qnfhq.modules.user.entity.AppUserEntity;
import com.qnfhq.modules.user.enums.AuditStatusEnum;
import com.qnfhq.modules.user.service.AppAssetService;
import com.qnfhq.modules.user.service.AppUserDetailService;
import com.qnfhq.modules.user.service.AppUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * C2C认证商家表
 *
 * @author yelz 30262728@qq.com
 * @since 1.0.0 2025-11-17
 */
@Service
public class C2cMerchantServiceImpl extends BaseServiceImpl<C2cMerchantDao, C2cMerchantEntity> implements C2cMerchantService {

//    @Override
//    public QueryWrapper<C2cMerchantEntity> getWrapper(Map<String, Object> params){
//        String id = (String)params.get("id");
//
//        QueryWrapper<C2cMerchantEntity> wrapper = new QueryWrapper<>();
//        wrapper.eq(StrUtil.isNotBlank(id), "id", id);
//
//        return wrapper;
//    }

    @Resource
    private C2cMerchantConfigService c2cMerchantConfigService;

    @Resource
    private AppAssetService appAssetService;

    @Resource
    private AppUserService appUserService;

    @Resource
    private AppUserDetailService appUserDetailService;

    @Override
    public C2cMerchantEntity getMerchantEntity(long userId) {
        return baseDao.selectOne(new LambdaQueryWrapper<C2cMerchantEntity>()
                .eq(C2cMerchantEntity::getUserId, userId)
                .last(" limit 1")
        );
    }

    /**
     * 检查商户申请条件
     * @param loginId
     * @return
     */
    public Map<String, Object> checkApply(BigDecimal margin, long loginId) {
        Boolean check = true;
        Map<String, Object> ret = new HashMap<>();
        //冻结保证金
        ret.put("applyMargin",margin);
        //可用资产
        BigDecimal avaAmount = BigDecimal.ZERO;
        List<AppAssetEntity> list = appAssetService.getUserAssets();
        List<AppAssetEntity> ptAsset = list.stream().filter(a -> a.getType()==1).collect(Collectors.toList());
        if(!ptAsset.isEmpty()) {
            avaAmount = ((AppAssetEntity)ptAsset.get(0)).getAvailable();
        }

        if(avaAmount.compareTo(margin) == -1) {
            //您的资金账户至少应有 {0}USDT的可用金额
            ret.put("margin",new Result().error(0,MessageUtils.message("your.account.available.balance.insufficient",margin)));
        } else {
            ret.put("margin",new Result().set(1, MapUtil.of("availableAmount",avaAmount),"ok"));
        }

        AppUserEntity appUser = appUserService.selectById(loginId);
        if(Objects.isNull(appUser) || appUser.getPhone().isEmpty()) {
            ret.put("phone",new Result().error(0,MessageUtils.message("complete.mobile.bind")));
        } else {
            ret.put("phone",new Result().set(1,MapUtil.of("phone",appUser.getPhone()),"ok"));
        }

        if(Objects.isNull(appUser) || appUser.getEmail().isEmpty()) {
            ret.put("email",new Result().error(0,MessageUtils.message("complete.email.bind")));
        } else {
            ret.put("email",new Result().set(1,MapUtil.of("email",appUser.getEmail()),"ok"));
        }

        AppUserDetailEntity appUserDetail = appUserDetailService.selectAppUserDetailByUserId(loginId);
        if(Objects.nonNull(appUserDetail) && appUserDetail.getAuditStatus()==AuditStatusEnum.EXAMINATION_PASSED.getCode()) {
            Map data = MapUtil.of("country",appUserDetail.getCountry());
            data.put("realname",appUserDetail.getRealName());
            ret.put("realname",new Result().set(1, data,"ok"));
        } else {
            ret.put("realname",new Result().error(0,MessageUtils.message("complete.identity.verification")));
        }
        return ret;
    }

    /**
     * 商户申请
     * 校验保证金是否足额
     * 是否实名认证
     * 邮箱、号码是否绑定
     * @param loginId
     * @return
     */
    @Override
    public void apply(C2cMerchantApplyDTO appUserMerchant, long loginId) {
        //冻结保证金
        C2cMerchantConfigEntity merchantConfig = c2cMerchantConfigService.getMerchantConfig(appUserMerchant.getLegalCoin().toUpperCase());
        if(merchantConfig==null) {
            throw new RenException(MessageUtils.message("c2c.merchant.apply.not.config"));//未配置认证商家保证金
        }
        Integer marginL = merchantConfig.getMargin();
        BigDecimal margin = new BigDecimal(marginL);

        BigDecimal avaAmount = BigDecimal.ZERO;
        List<AppAssetEntity> assetList = appAssetService.getUserAssets();
        List<AppAssetEntity> ptAsset = assetList.stream().filter(a -> a.getType()==1).collect(Collectors.toList());
        if(!ptAsset.isEmpty()) {
            avaAmount = ((AppAssetEntity)ptAsset.get(0)).getAvailable();
        }
        if(avaAmount.compareTo(margin) == -1) {
            //您的资金账户至少应有 {0}USDT的可用金额
            throw new RenException(MessageUtils.message("your.account.available.balance.insufficient",margin));
        }

        AppUserEntity appUser = appUserService.selectById(loginId);
        if(Objects.isNull(appUser) || appUser.getPhone().isEmpty()) {
            throw new RenException(MessageUtils.message("complete.mobile.bind"));//完成手机号绑定
        }
        if(Objects.isNull(appUser) || appUser.getEmail().isEmpty()) {
            throw new RenException(MessageUtils.message("complete.email.bind"));//完成邮箱绑定
        }

        AppUserDetailEntity appUserDetail = appUserDetailService.selectAppUserDetailByUserId(loginId);
        if(Objects.nonNull(appUserDetail) && appUserDetail.getAuditStatus()!=AuditStatusEnum.EXAMINATION_PASSED.getCode()) {
            throw new RenException(MessageUtils.message("complete.identity.verification"));//完成身份验证
        }

        C2cMerchantEntity merchant = getMerchantEntity(loginId);
        if(Objects.isNull(merchant)) {
            merchant = new C2cMerchantEntity();
            merchant.setUserId(loginId);
            merchant.setMargin(marginL);
            merchant.setUserName(appUserDetail.getRealName());
            merchant.setLegalCoin(appUserMerchant.getLegalCoin().toUpperCase());
            merchant.setSocialType(appUserMerchant.getSocialType());
            merchant.setSocialAccount(appUserMerchant.getSocialAccount());
            merchant.setStatus(MerchantStatusEnum.PENDING.getCode());//0 审批中
            merchant.setCreateTime(new Date());
            merchant.setUpdateTime(new Date());
            insert(merchant);
        }
    }



}