package com.jeesharp.business.modules.mall.service.impl;

import com.jeesharp.business.modules.mall.convert.MallBargainRecordConvert;
import com.jeesharp.business.modules.mall.entity.MallBargainActivity;
import com.jeesharp.business.modules.mall.entity.MallBargainRecord;
import com.jeesharp.business.modules.mall.mapper.MallBargainRecordMapper;
import com.jeesharp.business.modules.mall.service.MallBargainActivityService;
import com.jeesharp.business.modules.mall.service.MallBargainRecordService;
import com.jeesharp.business.modules.mall.vo.MallBargainRecordInfoVO;
import com.jeesharp.business.modules.mall.vo.MallBargainRecordListVO;
import com.jeesharp.business.modules.mall.vo.MallBargainRecordQueryVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 砍价记录 Service 实现类
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MallBargainRecordServiceImpl extends CrudService<MallBargainRecordMapper, MallBargainRecord, MallBargainRecordQueryVO> implements MallBargainRecordService {

    private static final int ACTIVE_STATUS = 0;
    private static final int COMPLETED_STATUS = 1;
    private static final String IDS_SEPARATOR = ",";

    private final MallBargainActivityService mallBargainActivityService;

    @Override
    public MallBargainRecordInfoVO getRecord(String id) {
        return MallBargainRecordConvert.INSTANCE.toInfoVO(get(id));
    }

    @Override
    public PageRespVO<MallBargainRecordListVO> findRecordPage(Page<MallBargainRecord> page, MallBargainRecordQueryVO query) {
        Page<MallBargainRecord> result = findPage(page, query);
        return MallBargainRecordConvert.INSTANCE.toPageRespVO(result);
    }

    @Override
    @Transactional(readOnly = false)
    public void createRecord(MallBargainRecord entity) {
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateRecord(MallBargainRecord entity) {
        update(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public String startBargain(String activityId, String memberId) {
        MallBargainRecordQueryVO query = new MallBargainRecordQueryVO();
        query.setActivityId(activityId);
        query.setMemberId(memberId);
        List<MallBargainRecord> existing = findList(query);
        if (!existing.isEmpty()) {
            throw new RuntimeException("您已经参与过该砍价活动");
        }

        MallBargainActivity activity = mallBargainActivityService.get(activityId);
        if (activity.getLimitPerUser() != null && activity.getLimitPerUser() > 0) {
            long userParticipations = existing.size();
            if (userParticipations >= activity.getLimitPerUser()) {
                throw new RuntimeException("您已达到该活动的参与上限");
            }
        }

        MallBargainRecord record = new MallBargainRecord();
        record.setActivityId(activityId);
        record.setMemberId(memberId);
        record.setCurrentPrice(activity.getInitialPrice());
        record.setHelpCount(0);
        record.setStatus(ACTIVE_STATUS);
        record.setEndTime(activity.getEndTime());
        createRecord(record);

        List<MallBargainRecord> records = findList(query);
        return records.get(records.size() - 1).getId();
    }

    @Override
    public PageRespVO<MallBargainRecordListVO> getUserBargainRecords(String memberId, Page<MallBargainRecord> page) {
        MallBargainRecordQueryVO query = new MallBargainRecordQueryVO();
        query.setMemberId(memberId);
        return findRecordPage(page, query);
    }

    @Override
    public boolean isBargainCompleted(String recordId) {
        MallBargainRecord record = get(recordId);
        if (record == null) {
            return false;
        }
        MallBargainActivity activity = mallBargainActivityService.get(record.getActivityId());
        if (activity == null) {
            return false;
        }
        return record.getCurrentPrice().compareTo(activity.getBottomPrice()) <= 0;
    }

    @Override
    @Transactional(readOnly = false)
    public void updateBargainStatus(String recordId, Integer status) {
        MallBargainRecord record = get(recordId);
        if (record != null) {
            record.setStatus(status);
            updateRecord(record);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void updateBargainRecord(MallBargainRecord record) {
        updateRecord(record);
    }

    @Override
    public Map<String, Object> calculateBargainProgress(String recordId) {
        MallBargainRecord record = get(recordId);
        if (record == null) {
            return null;
        }
        MallBargainActivity activity = mallBargainActivityService.get(record.getActivityId());
        if (activity == null) {
            return null;
        }

        Map<String, Object> progress = new HashMap<>();
        progress.put("currentPrice", record.getCurrentPrice());
        progress.put("bottomPrice", activity.getBottomPrice());
        progress.put("initialPrice", activity.getInitialPrice());
        progress.put("helpCount", record.getHelpCount());
        progress.put("totalHelpCount", activity.getHelpCount());

        BigDecimal cutAmount = activity.getInitialPrice().subtract(record.getCurrentPrice());
        progress.put("cutAmount", cutAmount);

        BigDecimal totalCutAmount = activity.getInitialPrice().subtract(activity.getBottomPrice());
        BigDecimal progressPercent = cutAmount.divide(totalCutAmount, 2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100));
        progress.put("progressPercent", progressPercent);
        return progress;
    }
}
