package com.huigou.topsun.product.application.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.topsun.product.application.BrandApplication;
import com.huigou.topsun.product.application.ProductApplication;
import com.huigou.topsun.product.domain.*;
import com.huigou.topsun.product.repository.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 16508
 * @description 针对表【product(产品)】的数据库操作Service实现
 * @createDate 2023-11-22 10:24:31
 */
@Service
@RequiredArgsConstructor//通过构造方法注入 ProductApplication(Class a) { this.a = a; }
public class ProductApplicationImpl implements ProductApplication {

    private final  ProductRepository productRepository;
    private final ProductDetailRepository detailRepository;
    // 类型
    private final BrandRepository brandRepository;
    private final BrandApplication brandService;
    private final FactoryRepository factoryRepository;
    private final ColorRepository colorRepository;
    private final ProductCategoryRepository categoryRepository;
    // 详细信息
    private final ProductTypesetConfRepository typesetConfRepository;
    private final ProductLookedRepository lookedRepository;
    private final ProductPublishedConfRepository publishedConfRepository;
    private final ProductLossRepository lossRepository;
    private final ProductMaterialRepository materialRepository;

    private final ProductFaceRepository faceRepository;
    private final ProductFaceColorRepository faceColorRepository;

    @Override
    public ArrayList<Map<String, Object>> findProductPage(int page, int size) {
//        PageRequest pageRequest = new PageRequest(page, size);
//        Page<Product> productPage = productRepository.findAll(pageRequest);
//        mapList.getContent().stream().map(Product::toString).forEach(System.out::println);
        ArrayList<Product> productPage = (ArrayList<Product>) productRepository.findAll();
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<Map<String, Object>> mapList = (ArrayList<Map<String, Object>>) mapper.convertValue(productPage, List.class);

//        convert = mapList.stream().collect(Collectors.toMap(index -> index, Function.identity(),
//                (oldV, newV) -> oldV));

        return mapList;
    }

    /**
     * description 查询产品所有详细信息
     * @param productId 产品ID
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author qinzhenguan
     * @create: 2023/11/29 13:19
     */
    @Override
    public Map<String, Object> queryDetailAll(int productId) {
        Map<String, Object> resultMap = new HashMap<>();
        ProductDetail productDetail = detailRepository.findByProductIdEquals((long)productId);
        resultMap.put("detail", productDetail);
//        EntityManager manager = JPAUtils.getEntityManger();
//        manager.getTransaction().begin();
//        manager.flush();
//        manager.close();

        // ---------------------------------  类别查询 ---------------------------------
        ArrayList<Brand> brands = (ArrayList<Brand>)brandRepository.findAll();
        ArrayList<Factory> factorys = (ArrayList<Factory>)factoryRepository.findAll();
        ArrayList<Color> colors = (ArrayList<Color>)colorRepository.findAll();
        ArrayList<ProductCategory> categorys = (ArrayList<ProductCategory>)categoryRepository.findAll();

        // ---------------------------------  详情查询 ---------------------------------
        ProductTypesetConf typesetConf = typesetConfRepository.findByProductIdEquals(Long.toString(productId));
        System.err.println(Long.toString(productId));
        ProductLooked looked = lookedRepository.findByProductId(Long.toString(productId));
        ProductPublishedConf publishedConf = publishedConfRepository.findByProductIdEquals(Long.toString(productId));
        ProductLoss loss = lossRepository.findByProductIdEquals(Long.toString(productId));
        ProductMaterial material = materialRepository.findByProductIdEquals(Long.toString(productId));
        resultMap.put("typesetConf", typesetConf);
        resultMap.put("looked", looked);
        resultMap.put("publishedConf", publishedConf);
        resultMap.put("loss", loss);
        resultMap.put("material", material);

        // ---------------------------------  版面查询 ---------------------------------
        if(productDetail != null) {
            if(productDetail.getBackProductFaceId() != null) {
                ProductFace frontFace = faceRepository.findByProductFaceIdEquals(productDetail.getBackProductFaceId());
                ProductFaceColor fronColor = faceColorRepository.findByProductFaceIdEquals(productDetail.getBackProductFaceId());
                resultMap.put("frontFace", frontFace);
                resultMap.put("fronColor", fronColor);
            }
            if(productDetail.getBackProductFaceId() != null) {
                ProductFace backFace = faceRepository.findByProductFaceIdEquals(productDetail.getBackProductFaceId());
                ProductFaceColor backColor = faceColorRepository.findByProductFaceIdEquals(productDetail.getBackProductFaceId());
                resultMap.put("backFace", backFace);
                resultMap.put("backColor", backColor);
            }
        }

        resultMap.put("selectedBrand", convertToMap(Brand.class, "brandName", "brandId", brands));
        resultMap.put("selectedFactory", convertToMap(Factory.class, "factoryName", "factoryId", factorys));
        resultMap.put("selectedColor", convertToMap(Color.class, "colorName", "colorId", colors));
        resultMap.put("selectedCategory", convertToMap(ProductCategory.class, "productCategoryId",
                "productCategoryName", categorys));
        return resultMap;
    }

    /**
     * description
     * @param clazz Bean
     * @param displayProperty   需要显示的属性
     * @param valueProperty     连接的属性
     * @param list  需要转换的 List
     * @return java.util.Map<java.lang.Object, java.lang.Object>
     * @author qinzhenguan
     * @create: 2023/12/1 16:09
     */
    public Map<Object, Object> convertToMap(Class<?> clazz, String displayProperty, String valueProperty,
                                            List<?> list) {
        Set<String> set = new HashSet();
        set.add(displayProperty);
        set.add(valueProperty);
        if(checkClassesAndProperties(clazz, set, list.size())) {
            ObjectMapper mapper = new ObjectMapper();
            List<Map<String, Object>> mapList = mapper.convertValue(list, List.class);
            return mapList.stream().collect(Collectors.toMap(map -> map.get(displayProperty), map -> map.get(valueProperty),
                    (oldV, newV) -> oldV));
        }
        return null;
    }

    /**
     * description  只检查传入属性是否合法
     * @param clazz Bean
     * @param set   需要检查的 Propertys
     * @param listSize  需要检查的 ListSize
     * @return java.lang.Boolean    true of false
     * @author qinzhenguan
     * @create: 2023/12/1 15:58
     */
    public Boolean checkClassesAndProperties(Class<?> clazz, Set<String> set, int listSize) {
        if(listSize == 0) {
            System.err.println("[checkClassesAndProperties] :  List< "+clazz.getName()+" > 需要转换的列表没有元素。请检查~！");
            return false;
        }
        Field[] fields = clazz.getDeclaredFields();
        Method[] methods = clazz.getDeclaredMethods();
        for(String item : set) {
            Field field = Arrays.stream(fields).filter(f -> item.equals(f.getName())).findFirst().orElse(null);
            if(field == null) {
                System.err.println("[checkClassesAndProperties] : " + clazz.getName() + " 无法找到 ： " + item + " " +
                        "该属性。请检查~！");
                return false;
            }
            Method method = Arrays.stream(methods)
                    .filter(m -> m.getName().toLowerCase().contains("get" + item.toLowerCase())).findFirst().orElse(null);
            if (method == null) {
                System.err.println("[checkClassesAndProperties] : " + item + " 该属性无法找到构造方法。请检查~！");
                return false;
            }
        }
        return true;
    }

    /**
     * description 转换成 Map 不需要转换为实体
     * @param clazz Bean
     * @param propertyName 连接的 property
     * @param list  需要转换的 List
     * @return java.util.Map<java.lang.Object, java.lang.Object>
     * @author qinzhenguan
     * @create: 2023/11/29 11:36
     */
    public Map<Object, Object> convertToMap(Class<?> clazz, String propertyName, List<?> list) {
        return convertToMap(clazz, propertyName, list, false);
    }

    /**
     * description 转换成 Map 保留映射
     * @param clazz Bean
     * @param propertyName  连接的 property
     * @param list  需要转换的 List
     * @param isBean    是否需要转换为实体 （当前应用不需要返回实体）
     * @return java.util.Map<java.lang.Object, java.lang.Object>
     * @author qinzhenguan
     * @create: 2023/11/29 11:34
     */
    public Map<Object, Object> convertToMap(Class<?> clazz, String propertyName, List<?> list, boolean isBean) {
        Map<String, Object> checkMap = checkClassesAndProperties(clazz, propertyName, list.size());
        if(!(Boolean) checkMap.get("isOk")) {
            return null;
        }
        Method method = (Method) checkMap.get("method");
        ObjectMapper mapper = new ObjectMapper();
        List<Map<String, Object>> mapList = mapper.convertValue(list, List.class);
        Map<Object, Object> resultMap = new HashMap<>();
        Map<Object, Object> convert = new HashMap<>();
        if(isBean) {
            // ---------------------------------  实体 ---------------------------------
            try {
                for (int i = 0; i < mapList.size(); i++) {
                    Object o = clazz.newInstance();
                    BeanUtils.populate(o, mapList.get(i));
                    Object key = method.invoke(o);
                    convert.put(key, o);
                }
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        } else {
            // ---------------------------------  非实体 ---------------------------------
            convert = mapList.stream().collect(Collectors.toMap(map -> map.get(propertyName), Function.identity(),
                    (oldV, newV) -> oldV));
            //此处仍需处理 Key == null;
        }
        resultMap.put("map", convert);
        resultMap.put("list", list);
        return resultMap;
    }

    /**
     * description 检查传入参数是否合法 并返回构造方法
     * 
     * @param clazz Bean
     * @param propertyName property
     * @return java.util.HashMap<java.lang.String, java.lang.Object> { "isOk" : 是否通过检查, "method"：获取得到的 method }
     * @author qinzhenguan
     * @create: 2023/11/29 11:05
     */
    public HashMap<String, Object> checkClassesAndProperties(Class<?> clazz, String propertyName, int listSize) {
        HashMap<String, Object> map = new HashMap<>();
        if(listSize == 0) {
            System.err.println("[checkClassesAndProperties] :  List< "+clazz.getName()+" > 需要转换的列表没有元素。请检查~！");
            map.put("isOk", false);
            return map;
        }
        Field[] fields = clazz.getDeclaredFields();
        Field field = Arrays.stream(fields).filter(f -> propertyName.equals(f.getName())).findFirst().orElse(null);
        if(field == null) {
            System.err.println("[checkClassesAndProperties] : " + clazz.getName() + " 无法找到 ： " + propertyName + " " +
                    "该属性。请检查~！");
            map.put("isOk", false);
            return map;
        }
        Method[] methods = clazz.getDeclaredMethods();
        Method method = Arrays.stream(methods)
                .filter(m -> m.getName().toLowerCase().contains("get" + propertyName.toLowerCase())).findFirst().orElse(null);
        if (method == null) {
            System.err.println("[checkClassesAndProperties] : " + propertyName + " 该属性无法找到构造方法。请检查~！");
            map.put("isOk", false);
            return map;
        }
        map.put("isOk", true);
        map.put("method", method);
        return map;
    }
}
