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.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qnfhq.common.utils.DateUtil;
import com.qnfhq.common.utils.MessageUtils;
import com.qnfhq.common.utils.StringUtils;
import com.qnfhq.modules.business.dao.TMingProductMapper;
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.AppUserDetailService;
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 org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 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 AppUserDetailService appUserDetailService;


    @Resource
    private ITMingProductService mingProductService;

    @Resource
    private AppAssetDao appAssetDao;

    @Resource
    private TMingProductUserMapper tMingProductUserMapper;

    @Resource
    private SettingService settingService;

    @Resource
    private TMingProductMapper tMingProductMapper;


    @Override
    public String bugMingOrder(Long planId, BigDecimal amount, Long userId) {
        //获取用户信息
        AppUserEntity user = appUserService.getUserByUserId(userId);
        //获取用户详情
        AppUserDetailEntity tAppUserDetail = appUserDetailService.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";
    }

    @Override
    public IPage<TMingOrder> selectTMingOrderList(TMingOrder tMingOrder) {
        // 构建分页对象（假设已定义）
        IPage<TMingOrder> page = new Page<>(1, 20); // current: 当前页, size: 每页条数
        // 构建查询条件
        LambdaQueryWrapper<TMingOrder> queryWrapper = new LambdaQueryWrapper<>();
        if (tMingOrder.getAmount() != null) {
            queryWrapper.eq(TMingOrder::getAmount, tMingOrder.getAmount());
        }
        if (tMingOrder.getDays() != null) {
            queryWrapper.eq(TMingOrder::getDays, tMingOrder.getDays());
        }
        if (tMingOrder.getStatus() != null) {
            queryWrapper.eq(TMingOrder::getStatus, tMingOrder.getStatus());
        }
        if (tMingOrder.getPlanId() != null) {
            queryWrapper.eq(TMingOrder::getPlanId, tMingOrder.getPlanId());
        }
        if (StringUtils.isNotBlank(tMingOrder.getPlanTitle())) {
            queryWrapper.eq(TMingOrder::getPlanTitle, tMingOrder.getPlanTitle());
        }
        if (StringUtils.isNotBlank(tMingOrder.getOrderNo())) {
            queryWrapper.eq(TMingOrder::getOrderNo, tMingOrder.getOrderNo());
        }
        if (tMingOrder.getEndTime() != null) {
            queryWrapper.eq(TMingOrder::getEndTime, tMingOrder.getEndTime());
        }
        if (tMingOrder.getSettleTime() != null) {
            queryWrapper.eq(TMingOrder::getSettleTime, tMingOrder.getSettleTime());
        }
        if (tMingOrder.getAccumulaEarn() != null) {
            queryWrapper.eq(TMingOrder::getAccumulaEarn, tMingOrder.getAccumulaEarn());
        }
        if (tMingOrder.getMinOdds() != null) {
            queryWrapper.eq(TMingOrder::getMinOdds, tMingOrder.getMinOdds());
        }
        if (tMingOrder.getMaxOdds() != null) {
            queryWrapper.eq(TMingOrder::getMaxOdds, tMingOrder.getMaxOdds());
        }
        if (StringUtils.isNotBlank(tMingOrder.getAdminUserIds())) {
            queryWrapper.apply("FIND_IN_SET({0}, admin_user_ids)", tMingOrder.getAdminUserIds());
        }
        if (StringUtils.isNotBlank(tMingOrder.getCollectionOrder())) {
            queryWrapper.eq(TMingOrder::getCollectionOrder, tMingOrder.getCollectionOrder());
        }
        if (tMingOrder.getUserId() != null) {
            queryWrapper.eq(TMingOrder::getUserId, tMingOrder.getUserId());
        }
        if (tMingOrder.getOrderAmount() != null) {
            queryWrapper.eq(TMingOrder::getOrderAmount, tMingOrder.getOrderAmount());
        }
        // 按创建时间倒序
        queryWrapper.orderByDesc(TMingOrder::getCreateTime);
        // 执行分页查询
        IPage<TMingOrder> result = tMingOrderMapper.selectPage(page, queryWrapper);
        List<TMingOrder> newList = result.getRecords();
        if (CollectionUtils.isEmpty(newList)) {
            return result; // 提前返回，避免后续无意义操作
        }

        for (TMingOrder mingOrder : newList) {
            MingProduct product = tMingProductMapper.selectById(mingOrder.getPlanId());
            mingOrder.setLogo(null != product ? product.getIcon(): null);
        }
        if(!CollectionUtils.isEmpty(newList)){
            newList.forEach(t->{
                Map<String, Object> params = new HashMap<>();
                params.put("createTime", Objects.nonNull(t.getCreateTime())?t.getCreateTime().getTime():0l);
                params.put("endTime", Objects.nonNull(t.getEndTime())?t.getEndTime().getTime():0l);
                t.setParams(params);
            });
        }
        return result;
    }




}

