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

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qnfhq.common.utils.DateUtil;
import com.qnfhq.common.utils.MessageUtils;
import com.qnfhq.modules.business.dao.TMingProductUserMapper;
import com.qnfhq.modules.business.entity.AddMosaicSetting;
import com.qnfhq.modules.business.entity.MingProduct;
import com.qnfhq.modules.business.entity.MingProductUser;
import com.qnfhq.modules.business.entity.TMingOrder;
import com.qnfhq.modules.business.dao.TMingOrderMapper;
import com.qnfhq.modules.business.service.ITMingOrderService;
import com.qnfhq.modules.business.service.ITMingProductService;
import com.qnfhq.modules.user.dao.AppAssetDao;
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.entity.SettingEntity;
import com.qnfhq.modules.user.enums.AssetEnum;
import com.qnfhq.modules.user.enums.RecordEnum;
import com.qnfhq.modules.user.enums.SettingEnum;
import com.qnfhq.modules.user.service.AppUserService;
import com.qnfhq.modules.user.service.AppWalletRecordService;
import com.qnfhq.modules.user.service.SettingService;
import com.qnfhq.utils.OrderUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * mingService业务层处理
 *
 * @author table
 * @date 2023-08-18
 */
@Service
public class TMingOrderServiceImpl extends ServiceImpl<TMingOrderMapper, TMingOrder> implements ITMingOrderService {
    @Resource
    private TMingOrderMapper tMingOrderMapper;

    @Resource
    private AppWalletRecordService appWalletRecordService;

    @Resource
    private AppUserService appUserService;

    @Resource
    private ITMingProductService mingProductService;

    @Resource
    private AppAssetDao appAssetDao;

    @Resource
    private TMingProductUserMapper tMingProductUserMapper;

    @Resource
    private SettingService settingService;


    @Override
    public String bugMingOrder(Long planId, BigDecimal amount, Long userId) {
        //获取用户信息
        AppUserEntity user = appUserService.getUserByUserId(userId);
        //获取用户详情
        AppUserDetailEntity tAppUserDetail = appUserService.selectUserDetailByUserId(userId);
        Integer tradeFlag = tAppUserDetail.getTradeFlag();
        if (null != tradeFlag) {
            if (1 == tradeFlag) {
                if (tAppUserDetail.getTradeMessage() == null || tAppUserDetail.getTradeMessage().equals("")) {
                    return MessageUtils.message("user.push.message");
                } else {
                    return tAppUserDetail.getTradeMessage();
                }
            }
        }

        //获取产品信息
        MingProduct tMingProduct = mingProductService.selectTMingProductById(planId);
        if(tMingProduct == null) {
            return MessageUtils.message("product.not.exist");
        }

        // 单个用户单笔下注最小金额 和最大金额
        if (null != tMingProduct.getLimitMin()) {
            if (amount.compareTo(tMingProduct.getLimitMin()) < 0) {
                return MessageUtils.message("order.single.min");
            }
        }
        if (null != tMingProduct.getLimitMax()) {
            if (tMingProduct.getLimitMax().compareTo(amount) < 0) {
                return MessageUtils.message("order.single.max");
            }
        }

        ////判断有没有个人购买限制
        MingProductUser tMingProductUser = tMingProductUserMapper
                .selectOne(new LambdaQueryWrapper<MingProductUser>()
                        .eq(MingProductUser::getProductId, planId)
                        .eq(MingProductUser::getAppUserId, userId));
        if (Objects.nonNull(tMingProductUser) && Objects.nonNull(tMingProductUser.getPledgeNum()))
            tMingProduct.setTimeLimit(tMingProductUser.getPledgeNum());
        //判断金额是否足够
        AppAssetEntity tAppAsset = appAssetDao
                .selectOne(new LambdaQueryWrapper<AppAssetEntity>()
                        .eq(AppAssetEntity::getType, AssetEnum.PLATFORM_ASSETS.getCode())
                        .eq(AppAssetEntity::getUserId, userId).eq(AppAssetEntity::getSymbol, tMingProduct.getCoin()));

        // 2. 金额判断
        if (Objects.isNull(tAppAsset)) {
            return MessageUtils.message("order_amount_error");
        }

        if (tAppAsset.getTotal().compareTo(amount) < 0) {
            return MessageUtils.message("order_amount_error");
        }
        // 3. 订单数量判断
        long count = this.count(new LambdaQueryWrapper<TMingOrder>().eq(TMingOrder::getPlanId, tMingProduct.getId()).eq(TMingOrder::getUserId, userId));
        if (count >= tMingProduct.getTimeLimit()) {
            return MessageUtils.message("financial.count.max");
        }
        String days = tMingProduct.getDays();
        TMingOrder mineOrder = new TMingOrder();
        mineOrder.setUserId(userId);
        mineOrder.setPlanId(planId);
        Date now = new DateTime();
        // 下单
        String serialId = "E" + OrderUtils.generateOrderNum();
        //  Date endTime = DateUtil.dateFormatDay(now, Integer.valueOf(days));
        Date settleTime = DateUtil.dateFormatDay(now, Integer.valueOf(tMingProduct.getSettleDay()));

        //当日利率从接口获取，现在取最小利率
        mineOrder.setOrderNo(serialId);
        mineOrder.setPlanId(tMingProduct.getId());
        mineOrder.setCreateTime(new Date());
        mineOrder.setDays(Integer.valueOf(days));
        mineOrder.setSettleTime(settleTime);
        //币种
        mineOrder.setCoin(tMingProduct.getCoin());
        mineOrder.setAmount(amount);
        mineOrder.setAccumulaEarn(BigDecimal.ZERO);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date endTime = null;
        try {
            endTime = sdf.parse("2026-02-17");
        } catch (Exception e) {
//            throw new RuntimeException(e);
        }
        mineOrder.setEndTime(endTime);
        mineOrder.setPlanTitle(tMingProduct.getTitle());
        mineOrder.setMinOdds(tMingProduct.getMinOdds());
        mineOrder.setMaxOdds(tMingProduct.getMaxOdds());
        mineOrder.setAdminUserIds(user.getAdminParentIds());
        mineOrder.setUserId(user.getId());
        mineOrder.setStatus(0);

        //  先扣钱，再下单
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("symbol", tMingProduct.getCoin());
        map.put("money", amount);
        map.put("type", AssetEnum.PLATFORM_ASSETS.getCode());
        appAssetDao.releaseAssetByUserId(map);
        BigDecimal bigDecimal = tAppAsset.getAvailable();


        appWalletRecordService.generateRecord(user.getId(),
                amount,
                RecordEnum.PLEDGE_RECHARGE.getCode(),
                user.getLoginName(),
                serialId,
                "质押认购", bigDecimal, bigDecimal.subtract(amount), tMingProduct.getCoin().toLowerCase(), user.getAdminParentIds());
        tMingOrderMapper.insert(mineOrder);
        //质押打码
       /* SettingEntity setting = settingService.getSetting(SettingEnum.ADD_MOSAIC_SETTING.name());
        if (Objects.nonNull(setting)){
            AddMosaicSetting addMosaic = JSONUtil.toBean(setting.getSettingValue(), AddMosaicSetting.class);
            if (Objects.nonNull(addMosaic) && Objects.nonNull(addMosaic.getIsOpen()) && addMosaic.getIsOpen() && Objects.nonNull(addMosaic.getPledgeIsOpen()) && addMosaic.getPledgeIsOpen()){
                user.setTotleAmont(user.getTotleAmont().add(mineOrder.getAmount()));
                appUserService.updateTotleAmont(user);
            }
        }*/
        return "success";
    }
}

