package com.czg.service.market.service.impl;

import cn.hutool.core.util.StrUtil;
import com.czg.account.entity.ShopUser;
import com.czg.account.service.ShopInfoService;
import com.czg.account.service.ShopUserService;
import com.czg.account.vo.PointsExchangeSummaryVo;
import com.czg.exception.CzgException;
import com.czg.market.dto.MkPointsGoodsRecordDTO;
import com.czg.market.dto.MkPointsGoodsRecordQueryDTO;
import com.czg.market.entity.MkPointsGoodsRecord;
import com.czg.market.service.MkPointsGoodsRecordService;
import com.czg.service.market.mapper.MkPointsGoodsRecordMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 积分兑换记录 服务层实现。
 *
 * @author ww
 * @since 2025-12-08
 */
@Service
public class MkPointsGoodsRecordServiceImpl extends ServiceImpl<MkPointsGoodsRecordMapper, MkPointsGoodsRecord> implements MkPointsGoodsRecordService {


    @DubboReference
    private ShopInfoService shopInfoService;
    @DubboReference
    private ShopUserService shopUserService;

    @Override
    public PointsExchangeSummaryVo total(MkPointsGoodsRecordQueryDTO param) {
        QueryWrapper queryWrapper = query().eq(MkPointsGoodsRecord::getShopId, param.getShopId())
                .between(MkPointsGoodsRecord::getCreateTime, param.getStartTime(), param.getEndTime())
                .eq(MkPointsGoodsRecord::getShopUserId, param.getShopUserId())
                .eq(MkPointsGoodsRecord::getStatus, param.getStatus())
                .eq(MkPointsGoodsRecord::getIsDel, 0)
                .like(MkPointsGoodsRecord::getPointsGoodsName, param.getPointsGoodsName())
                .like(MkPointsGoodsRecord::getGoodsCategory, param.getGoodsCategory());
        queryWrapper.select("count(*) as count,sum(extra_payment_amount) as totalAmount");
        return getOneAs(queryWrapper, PointsExchangeSummaryVo.class);
    }


    @Override
    public Page<MkPointsGoodsRecordDTO> getGoodsRecordPage(MkPointsGoodsRecordQueryDTO param) {
        Long mainIdByShopId = shopInfoService.getMainIdByShopId(param.getShopId());
        QueryWrapper queryWrapper = query().eq(MkPointsGoodsRecord::getShopId, param.getShopId())
                .between(MkPointsGoodsRecord::getCreateTime, param.getStartTime(), param.getEndTime())
                .eq(MkPointsGoodsRecord::getShopUserId, param.getShopUserId())
                .eq(MkPointsGoodsRecord::getIsDel, 0)
                .like(MkPointsGoodsRecord::getPointsGoodsName, param.getPointsGoodsName())
                .like(MkPointsGoodsRecord::getGoodsCategory, param.getGoodsCategory())
                .orderBy(MkPointsGoodsRecord::getCreateTime, false);

        if (StrUtil.isNotBlank(param.getStatus())) {
            if ("售后".equals(param.getStatus())) {
                queryWrapper.and(wrapper -> {
                    wrapper.eq(MkPointsGoodsRecord::getStatus, "退款中").or(MkPointsGoodsRecord::getStatus).eq("已退款");
                });
                queryWrapper.orderBy(MkPointsGoodsRecord::getStatus, false);
            } else {
                queryWrapper.eq(MkPointsGoodsRecord::getStatus, param.getStatus());
                queryWrapper.orderBy(MkPointsGoodsRecord::getStatus, false);
            }
        }
        Page<MkPointsGoodsRecordDTO> pages = pageAs(Page.of(param.getPage(), param.getSize()), queryWrapper, MkPointsGoodsRecordDTO.class);
        pages.getRecords().forEach(data -> {
            data.fillCouponInfo();
            ShopUser shopUser = shopUserService.getOne(query().eq(ShopUser::getId, data.getShopUserId()).eq(ShopUser::getMainShopId, mainIdByShopId));
            data.setHeadImg(shopUser.getHeadImg());
            data.setNickName(shopUser.getNickName());
            data.setPhone(shopUser.getPhone());
        });
        return pages;
    }

    @Override
    public Page<MkPointsGoodsRecord> userGoodsRecordPage(Integer page, Integer size, Long shopId, String status, Long userId) {
        QueryWrapper queryWrapper = query()
                .eq(MkPointsGoodsRecord::getUserId, userId)
                .eq(MkPointsGoodsRecord::getShopId, shopId)
                .eq(MkPointsGoodsRecord::getIsDel, 0);

        if (StrUtil.isNotBlank(status)) {
            if ("售后".equals(status)) {
                queryWrapper.and(wrapper -> {
                    wrapper.eq(MkPointsGoodsRecord::getStatus, "退款中").or(MkPointsGoodsRecord::getStatus).eq("已退款");
                });
                queryWrapper.orderBy(MkPointsGoodsRecord::getStatus, false);
            } else {
                queryWrapper.eq(MkPointsGoodsRecord::getStatus, status);
                queryWrapper.orderBy(MkPointsGoodsRecord::getStatus, false);
            }
        }
        queryWrapper.orderBy(MkPointsGoodsRecord::getCreateTime, false);
        Page<MkPointsGoodsRecord> pages = page(Page.of(page, size), queryWrapper);
        pages.getRecords().forEach(MkPointsGoodsRecord::fillCouponInfo);
        return pages;
    }

    @Override
    public boolean checkout(String couponCode, Long shopId) {
        MkPointsGoodsRecord record = getOne(query().eq(MkPointsGoodsRecord::getCouponCode, couponCode).eq(MkPointsGoodsRecord::getShopId, shopId));
        if (record == null) {
            throw new CzgException("未找到该兑换码");
        }
        if (!"待核销".equals(record.getStatus()) && !"退款中".equals(record.getStatus())) {
            throw new CzgException("核销失败，该商品不可核销");
        }
        MkPointsGoodsRecord upRecord = new MkPointsGoodsRecord();
        upRecord.setCheckoutTime(LocalDateTime.now());
        upRecord.setStatus("已完成");
        return update(upRecord, query().eq(MkPointsGoodsRecord::getId, record.getId()));
    }
}
