package cn.quant.baa.pay.model;

import cn.quant.baa.pay.acquirer.AcquirerProperties;
import cn.quant.baa.pay.config.DictionaryViewer;
import cn.quant.baa.pay.dict.DictType;
import cn.quant.baa.pay.model.web.MerchantAcquirerProperties;
import cn.quant.baa.pay.model.web.MerchantChannelResponseData;
import cn.quant.spring.NotSupportedException;
import cn.quant.spring.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * Created by Administrator on 2021/8/23 0023.
 */
@Service
public class ModelBuilder {

    @Autowired
    private DictionaryViewer dictionaryViewer;

    public MerchantAcquirerProperties toModel(AcquirerProperties profile) {
        MerchantAcquirerProperties response = new MerchantAcquirerProperties();
        response.setAccessCode(profile.getAccessCode().name());
        response.setAccessType(profile.getAccessType().name());
        response.setChanCode(profile.getPayChanCode());
        response.setChanId(profile.getMchChanId());
        response.setChanType(profile.getPayChanType().name());
        response.setName(profile.getName());
        response.setVersion(profile.getVersion());
        response.setDescText(profile.getDescText());
        return response;
    }

    public Collection<MerchantAcquirerProperties> toModel(Collection<AcquirerProperties> profiles) {
        LinkedList<MerchantAcquirerProperties> list = new LinkedList<>();
        for (AcquirerProperties profile : profiles) {
            list.add(toModel(profile));
        }
        return list;
    }

    public Map<String, MerchantChannelResponseData> toModel(Map<String, Collection<AcquirerProperties>> profiles, String access) {
        Map<String, MerchantChannelResponseData> models = new HashMap<>();
        for (String code : profiles.keySet()) {
            DictionaryItem item = dictionaryViewer.get(DictType.PAY, code);
            if (item == null) {
                throw new NotSupportedException(StringUtils.format("Dictionary item is null({}, {}).", DictType.PAY, code));
            }
            Collection<AcquirerProperties> collection = profiles.get(code);
            MerchantChannelResponseData book = new MerchantChannelResponseData();
            book.setCode(code);
            book.setName(item.getName());
            book.setImageUrl(item.getImageUrl());
            for (AcquirerProperties profile : collection) {
                if ((access != null) && (!access.equals(profile.getAccessCode().name()))) {
                    continue;
                }
                book.add(toModel(profile));
            }
            models.put(book.getCode(), book);
        }
        return models;
    }
}
