package com.sagacloud.cache.cachedObject.pojo;
/*
 * Author: Jxing
 * Create Time: 2018/8/27
 */


import com.google.common.base.Strings;
import com.sagacloud.cache.EhCaches;
import com.sagacloud.cache.ProPasCache;
import com.sagacloud.cache.cachedObject.pojo.venders.*;
import com.sagacloud.utils.Const;
import com.sagacloud.utils.HttpRequestUtil;
import com.sagacloud.utils.OssUtils;
import de.jkeylockmanager.manager.KeyLockManager;
import de.jkeylockmanager.manager.KeyLockManagers;
import org.ehcache.Cache;
//import org.json.JSONArray;
//import org.json.JSONObject;
import com.alibaba.fastjson.*;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class VenderInfoMap {
    static private final KeyLockManager lockManager = KeyLockManagers.newLock();
    private static final String VENDER_ID = "venderId";
    private static final String NAME = "name";
    private static final String WEBSITE = "website";
    private static final String VENDER_CONTRACTS = "contracts";
    private static final String VENDER_CONTACTS = "contacts";

    // 生产商相关Map
    private Map<String, VendersEntity> manufacturerMap = new HashMap<>(); // 生产商只有venderId 和 venderName;
    private Map<String, BrandEntity> brandMap = new HashMap<>();
    private Map<String, ModelEntity> modelMap = new HashMap<>();
    private Map<String, String> relModelBrandMap = new HashMap<>();
    private Map<String, String> relModelManufacturerMap = new HashMap<>();

    // 供应商相关Map
    private Map<String, VendersEntity> supplierMap = new HashMap<>();

    // 保险商相关Map
    private Map<String, VendersEntity> insuranceMap = new HashMap<>();
    private Map<String, WarrantyEntity> warrantyMap = new HashMap<>();
    private Map<String, String> relWarrantyInsuranceMap = new HashMap<>();

    // 维修商相关Map
    private Map<String, VendersEntity> maintainanceMap = new HashMap<>();

    public Map<String, VendersEntity> getManufacturerMap() {
        return manufacturerMap;
    }

    public void setManufacturerMap(Map<String, VendersEntity> manufacturerMap) {
        this.manufacturerMap = manufacturerMap;
    }

    public Map<String, BrandEntity> getBrandMap() {
        return brandMap;
    }

    public void setBrandMap(Map<String, BrandEntity> brandMap) {
        this.brandMap = brandMap;
    }

    public Map<String, ModelEntity> getModelMap() {
        return modelMap;
    }

    public void setModelMap(Map<String, ModelEntity> modelMap) {
        this.modelMap = modelMap;
    }

    public Map<String, String> getRelModelBrandMap() {
        return relModelBrandMap;
    }

    public void setRelModelBrandMap(Map<String, String> relModelBrandMap) {
        this.relModelBrandMap = relModelBrandMap;
    }

    public Map<String, String> getRelModelManufacturerMap() {
        return relModelManufacturerMap;
    }

    public void setRelModelManufacturerMap(Map<String, String> relModelManufacturerMap) {
        this.relModelManufacturerMap = relModelManufacturerMap;
    }

    public Map<String, VendersEntity> getSupplierMap() {
        return supplierMap;
    }

    public void setSupplierMap(Map<String, VendersEntity> supplierMap) {
        this.supplierMap = supplierMap;
    }

    public Map<String, VendersEntity> getInsuranceMap() {
        return insuranceMap;
    }

    public void setInsuranceMap(Map<String, VendersEntity> insuranceMap) {
        this.insuranceMap = insuranceMap;
    }

    public Map<String, WarrantyEntity> getWarrantyMap() {
        return warrantyMap;
    }

    public void setWarrantyMap(Map<String, WarrantyEntity> warrantyMap) {
        this.warrantyMap = warrantyMap;
    }

    public Map<String, String> getRelWarrantyInsuranceMap() {
        return relWarrantyInsuranceMap;
    }

    public void setRelWarrantyInsuranceMap(Map<String, String> relWarrantyInsuranceMap) {
        this.relWarrantyInsuranceMap = relWarrantyInsuranceMap;
    }

    public Map<String, VendersEntity> getMaintainanceMap() {
        return maintainanceMap;
    }

    public void setMaintainanceMap(Map<String, VendersEntity> maintainanceMap) {
        this.maintainanceMap = maintainanceMap;
    }

    public static VenderInfoMap get() {
        Cache<String, VenderInfoMap> venderInfoCache = EhCaches.getCache(EhCaches.VENDER_CACHE, String.class,
                VenderInfoMap.class);
        final VenderInfoMap venderInfoMap = new VenderInfoMap();
        ;
        //double-check模式
        if (venderInfoCache.get(EhCaches.VENDER_CACHE) == null) {
            lockManager.executeLocked(EhCaches.VENDER_CACHE, () -> {
                if (venderInfoCache.get(EhCaches.VENDER_CACHE) == null) {
                    venderInfoMap.getVenderInfo();
                    venderInfoCache.put(EhCaches.VENDER_CACHE, venderInfoMap);
                }
            });
            return venderInfoMap;
        }
        return venderInfoCache.get(EhCaches.VENDER_CACHE);
    }

    public static void clearCache() {
        EhCaches.getCache(EhCaches.VENDER_CACHE, String.class, VenderInfoMap.class).clear();
    }


    private void getVenderInfo() {
        String url = OssUtils.getProperty("vender.url");
        String result = HttpRequestUtil.sendPost(url, "{\"type\":[\"insurance\", \"supplier\", \"maintenance\", " +
                "\"manufacturer\"]}");
        if (result.equals(""))
            return;
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getString("result") == null || !jsonObject.getString("result").equals("success")) {
            return;
        }
        JSONObject content = jsonObject.getJSONObject("content");
        JSONArray manufacturer = content.getJSONArray("manufacturer");
        JSONArray supplier = content.getJSONArray("supplier");
        JSONArray maintenance = content.getJSONArray("maintenance");
        JSONArray insurance = content.getJSONArray("insurance");
        generateManufacturer(manufacturer);
        generateVenderMap(supplier, supplierMap);
        generateVenderMap(maintenance, maintainanceMap);
        generateVenderMap(insurance, insuranceMap);
        //System.out.println();
    }

    // 构建厂商Map, (生产商结构不同, 不适用)
    private void generateVenderMap(JSONArray insurance, Map<String, VendersEntity> vendersEntityMap) {
        if (insurance == null)
            return;
        for (int i = 0; i < insurance.size(); ++i) {
            JSONObject singleVender = insurance.getJSONObject(i);
            VendersEntity vendersEntity = new VendersEntity();
            vendersEntity.setVenderId(Strings.nullToEmpty(singleVender.getString(VENDER_ID)));
            vendersEntity.setName(Strings.nullToEmpty(singleVender.getString(NAME)));
            vendersEntity.setWebsite(Strings.nullToEmpty(singleVender.getString(WEBSITE)));
            vendersEntity.setContactMap(getContactMap(singleVender.getJSONArray(VENDER_CONTACTS)));
            createWarrantyMap((JSONArray) singleVender.get(VENDER_CONTRACTS), vendersEntity.getVenderId());
            if (!vendersEntityMap.containsKey(vendersEntity.getVenderId()))
                vendersEntityMap.put(vendersEntity.getVenderId(), vendersEntity);
        }
    }

    // 构建保单Map, 保单和厂商关系的Map
    private void createWarrantyMap(JSONArray warrantyJSONArray, String venderId) {
        if (warrantyJSONArray == null || warrantyJSONArray.size() == 0)
            return;
        for (int i = 0; i < warrantyJSONArray.size(); ++i) {
            JSONObject singleWarranty = warrantyJSONArray.getJSONObject(i);
            if (singleWarranty.getString("contractFile") == null || singleWarranty.getString("contractFile").length() == 0)
                continue;
            WarrantyEntity warrantyEntity = new WarrantyEntity();
            warrantyEntity.setContractFile(Strings.nullToEmpty(singleWarranty.getString("contractFile")));
            warrantyEntity.setExpireDate(Strings.nullToEmpty(singleWarranty.getString("expireDate")));
            warrantyEntity.setInsuranceNo(Strings.nullToEmpty(singleWarranty.getString("insuranceNo")));
            warrantyEntity.setProjectId(Strings.nullToEmpty(singleWarranty.getString("projectId")));
            if (!warrantyMap.containsKey(warrantyEntity.getInsuranceNo())) {
                warrantyMap.put(warrantyEntity.getInsuranceNo(), warrantyEntity);
            }
            if (venderId != null && venderId.length() > 0 && !relWarrantyInsuranceMap.containsKey(warrantyEntity.getInsuranceNo())) {
                relWarrantyInsuranceMap.put(warrantyEntity.getInsuranceNo(), venderId);
            }
        }
    }

    // 生成联系人Map
    private Map<String, ContactEntity> getContactMap(JSONArray contactArray) {
        Map<String, ContactEntity> contactMap = new HashMap<>();
        if (contactArray == null || contactArray.size() == 0)
            return contactMap;
        for (int i = 0; i < contactArray.size(); ++i) {
            JSONObject obj = contactArray.getJSONObject(i);
            if (obj.getString(Const.PROJECT_ID) == null || obj.getString(Const.PROJECT_ID).length() < 2)
                continue;
            if (!obj.getString(Const.PROJECT_ID).startsWith("Pj") || ProPasCache.get(obj.getString(Const.PROJECT_ID)) == null)
                continue;
            ContactEntity contactEntity = new ContactEntity();
            contactEntity.setEmail(obj.getString("email"));
            contactEntity.setFax(obj.getString("fax"));
            contactEntity.setName(obj.getString("name"));
            contactEntity.setPhone(obj.getString("phone"));
            contactMap.put(obj.getString(Const.PROJECT_ID), contactEntity);
        }
        return contactMap;
    }

    private void generateManufacturer(JSONArray manufacturer) {
        //    private Map<String, VendersEntity> manufacturerMap = new HashMap<>(); // 生产商只有venderId 和 venderName;
        //    private Map<String, BrandEntity> brandMap = new HashMap<>();
        //    private Map<String, ModelEntity> modelMap = new HashMap<>();
        //    private Map<String, Set<String>> relManufacturerBrandMap = new HashMap<>();
        //    private Map<String, String> relModelManufacturerMap = new HashMap<>();
        if (manufacturer == null || manufacturer.size() == 0)
            return;
        for (int i = 0; i < manufacturer.size(); ++i) {
            JSONObject singleManufacturer = manufacturer.getJSONObject(i);
            VendersEntity vendersEntity = new VendersEntity();
            vendersEntity.setVenderId(singleManufacturer.getString(VENDER_ID));
            vendersEntity.setName(singleManufacturer.getString(NAME));
            createBrandMap(singleManufacturer.getJSONArray("brands"), vendersEntity.getVenderId());
            if (!manufacturerMap.containsKey(vendersEntity.getVenderId()))
                manufacturerMap.put(vendersEntity.getVenderId(), vendersEntity);
        }
    }

    private void createBrandMap(JSONArray brands, String venderId) {
        if (brands == null || brands.size() == 0)
            return;
        for (int i = 0; i < brands.size(); ++i) {
            JSONObject singleBrand = brands.getJSONObject(i);
            if (singleBrand == null)
                continue;
            BrandEntity brandEntity = new BrandEntity();
            brandEntity.setBrandId(singleBrand.getString("brandId"));
            brandEntity.setName(singleBrand.getString(NAME));
            if (!brandMap.containsKey(brandEntity.getBrandId()))
                brandMap.put(brandEntity.getBrandId(), brandEntity);
            //createRelManufacturerBrandMap(venderId, brandEntity.getBrandId());
            createProduct(singleBrand.getJSONArray("products"), venderId, brandEntity.getBrandId());
        }

    }

    private void createProduct(JSONArray products, String venderId, String brandId) {
        if (products == null || products.size() == 0)
            return;
        for (int i = 0; i < products.size(); ++i) {
            JSONObject singleProduct = products.getJSONObject(i);
            JSONArray model = singleProduct.getJSONArray("specifications");
            if (model == null || model.size() == 0)
                continue;
            for (int j = 0; j < model.size(); ++j) {
                JSONObject singleModel = model.getJSONObject(j);
                ModelEntity modelEntity = new ModelEntity();
                modelEntity.setSpecificationId(singleModel.getString("specificationId"));
                modelEntity.setName(singleModel.getString(NAME));
                modelEntity.setFamily(singleProduct.getString("eqFamily"));
                modelEntity.setInfos(singleModel.getJSONObject("infos"));
                if (!modelMap.containsKey(modelEntity.getSpecificationId())) {
                    modelMap.put(modelEntity.getSpecificationId(), modelEntity);
                }
                if (!relModelManufacturerMap.containsKey(modelEntity.getSpecificationId())) {
                    relModelManufacturerMap.put(modelEntity.getSpecificationId(), venderId);
                }
                if (!relModelBrandMap.containsKey(modelEntity.getSpecificationId())) {
                    relModelBrandMap.put(modelEntity.getSpecificationId(), brandId);
                }
            }
        }
    }
}
