package com.ruoyi.jarvis.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.jarvis.domain.JDOrder;
import com.ruoyi.jarvis.domain.dto.QuickRecordModelShopOption;
import com.ruoyi.jarvis.mapper.JDOrderMapper;
import com.ruoyi.jarvis.service.IJDOrderModelShopService;
import com.ruoyi.jarvis.util.QuickRecordModelShopOptionUtil;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JDOrderModelShopServiceImpl implements IJDOrderModelShopService {

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private JDOrderMapper jdOrderMapper;

    @Override
    public List<QuickRecordModelShopOption> loadShopOptions() {
        String raw = sysConfigService.selectConfigByKey(QuickRecordModelShopOptionUtil.CONFIG_KEY);
        return QuickRecordModelShopOptionUtil.parseOptions(raw);
    }

    @Override
    public void normalizeOrder(JDOrder order) {
        QuickRecordModelShopOptionUtil.normalizeOrderModelShop(order, loadShopOptions());
    }

    @Override
    public String fullModel(JDOrder order) {
        return QuickRecordModelShopOptionUtil.fullModelNumber(order);
    }

    @Override
    public String lookupModelBase(String rawModel) {
        return QuickRecordModelShopOptionUtil.lookupModelBase(rawModel, loadShopOptions());
    }

    @Override
    public Map<String, Object> migrateExistingOrders() {
        List<QuickRecordModelShopOption> options = loadShopOptions();
        Map<String, Object> result = new HashMap<>();
        if (options.isEmpty()) {
            result.put("updated", 0);
            result.put("skipped", 0);
            result.put("message", "未配置店铺选项（quickRecord.modelShopOptions），请先配置后再迁移");
            return result;
        }
        List<JDOrder> candidates = jdOrderMapper.selectOrdersPendingModelShopMigration();
        int updated = 0;
        int skipped = 0;
        for (JDOrder row : candidates) {
            String beforeBase = StringUtils.trim(row.getModelNumber());
            String beforeShop = StringUtils.trim(row.getModelShop());
            normalizeOrder(row);
            String afterBase = StringUtils.trim(row.getModelNumber());
            String afterShop = StringUtils.trim(row.getModelShop());
            if (beforeBase.equals(afterBase) && beforeShop.equals(afterShop)) {
                skipped++;
                continue;
            }
            jdOrderMapper.updateModelShopFields(row.getId(), row.getModelNumber(), row.getModelShop());
            updated++;
        }
        result.put("updated", updated);
        result.put("skipped", skipped);
        result.put("total", candidates.size());
        result.put("message", String.format("迁移完成：更新 %d 条，无变化 %d 条（共扫描 %d 条）", updated, skipped, candidates.size()));
        return result;
    }
}
