package com.ai.da.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.ai.da.common.context.UserContext;
import com.ai.da.common.utils.RedisUtil;
import com.ai.da.mapper.primary.BrandRelLibraryMapper;
import com.ai.da.mapper.primary.LibraryMapper;
import com.ai.da.mapper.primary.ProductImageAttributeMapper;
import com.ai.da.mapper.primary.entity.BrandRelLibrary;
import com.ai.da.mapper.primary.entity.Library;
import com.ai.da.mapper.primary.entity.ProductImageAttribute;
import com.ai.da.mapper.secondary.entity.AttributeRecognitionJSON;
import com.ai.da.model.dto.ProgressDTO;
import com.ai.da.model.vo.AuthPrincipalVo;
import com.ai.da.python.PythonService;
import com.ai.da.service.ProductImageService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductImageServiceImpl implements ProductImageService {

    @Autowired
    private BrandRelLibraryMapper brandRelLibraryMapper;

    @Autowired
    private LibraryMapper libraryMapper;

    @Autowired
    private ProductImageAttributeMapper productImageAttributeMapper;

    @Autowired
    private PythonService pythonService;

    @Resource
    private RedisUtil redisUtil;
    @Value("${minio.bucketName.users}")
    private String userBucket;
    @Async
    @Override
    public void asyncInitialize(Long brandId, AuthPrincipalVo userHolder) {
        log.info(">>> [asyncInitialize] 当前线程：{}", Thread.currentThread().getName());

        String progressKey = String.valueOf(brandId);
        ProgressDTO progressDTO = redisUtil.getTaskProgressDTO(progressKey);

        if (Objects.isNull(progressDTO)) {
            progressDTO = new ProgressDTO(0, 0, false, null);
        } else {
            progressDTO.setTotal(0);
            progressDTO.setCurrent(0);
        }
        redisUtil.setTaskProgressDTO(progressKey, progressDTO);

        try {
            List<BrandRelLibrary> brandRelLibraries = brandRelLibraryMapper.selectList(
                    new QueryWrapper<BrandRelLibrary>().lambda().eq(BrandRelLibrary::getBrandId, brandId)
            );
            Set<Long> libraryIds = brandRelLibraries.stream().map(BrandRelLibrary::getLibraryId).collect(Collectors.toSet());

            progressDTO.setTotal(libraryIds.size());

            int current = 0;
            int size = libraryIds.size();
            for (Long libraryId : libraryIds) {
                log.info("Brand DNA Compute进度：{} / {}", current, size);
                Library library = libraryMapper.selectById(libraryId);
                if (Objects.isNull(library)){
                    continue;
                }
                String url = library.getUrl();

                QueryWrapper<ProductImageAttribute> qw = new QueryWrapper<>();
                qw.lambda().eq(ProductImageAttribute::getLibraryId, libraryId);
                List<ProductImageAttribute> productImageAttributes = productImageAttributeMapper.selectList(qw);
                if (!CollectionUtil.isNotEmpty(productImageAttributes)) {
                    JSONObject result = pythonService.segProduct(url);
                    JSONArray data = result.getJSONArray("data");
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject obj = data.getJSONObject(i);
                        String gender = library.getLevel3Type();
                        String category = null;
                        category = obj.getString("category_female");
                        /*if (gender.equals("Female")) {
                            category = obj.getString("category_female");
                        }else if (gender.equals("Male")) {
                            category = obj.getString("category_male");
                        }*/
                        String imgUrl = obj.getString("img_url");
                        JSONObject attribute = obj.getJSONObject("attribute");
                        AttributeRecognitionJSON attrJSON = attribute.toJavaObject(AttributeRecognitionJSON.class);
                        ProductImageAttribute attr = toAttrDict(attrJSON);
//                        ProductImageAttribute attr = new ProductImageAttribute();
                        attr.setGender(gender);
                        attr.setCategory(category);
                        attr.setImgUrl(imgUrl);
                        attr.setLibraryId(libraryId);
                        String imageName = UUID.randomUUID().toString();
                        String objectName = userHolder.getId() + "/imageToSketch/" + imageName;
                        String productImagePath = StringUtil.isNullOrEmpty(imgUrl) ? url : imgUrl;
                        String sketchPath = pythonService.imageToSketch(productImagePath, userBucket, objectName, "2", "");
                        attr.setImgUrl(sketchPath);
                        productImageAttributeMapper.insert(attr);
                    }
                }

                // 更新当前进度
                current++;
                progressDTO.setCurrent(current);
                progressDTO.setComputeTime(LocalDateTime.now());
                redisUtil.setTaskProgressDTO(progressKey, progressDTO);
            }

        } catch (Exception e) {
            log.error(e.getMessage());
//            log.error("初始化失败", e);
            redisUtil.setTaskProgressDTO(progressKey, new ProgressDTO(0, 0, true, null));
        }
    }


//    public double getInitializeProgress(Long brandId) {
//        ProgressDTO dto = redisUtil.getTaskProgressDTO(String.valueOf(brandId));
//        if (dto.getTotal() == 0 || dto.isError()) return 0.0;
//        return (dto.getCurrent() * 1.0 / dto.getTotal());
//    }

    private ProductImageAttribute toAttrDict(AttributeRecognitionJSON attrDictJSON) {
        ProductImageAttribute attributeRetrieval = new ProductImageAttribute();

        // 处理 imgName
//        if (CollectionUtil.isNotEmpty(attrDictJSON.getImgName()) && attrDictJSON.getImgName().get(0) != null) {
//            attributeRetrieval.setImgName(attrDictJSON.getImgName().get(0));
//        }
        // 处理 length
        if (CollectionUtil.isNotEmpty(attrDictJSON.getLength()) && attrDictJSON.getLength().get(0) != null) {
            attributeRetrieval.setLength(attrDictJSON.getLength().get(0));
        }
        // 处理 sleeveLength
        if (CollectionUtil.isNotEmpty(attrDictJSON.getSleeveLength()) && attrDictJSON.getSleeveLength().get(0) != null) {
            attributeRetrieval.setSleeveLength(attrDictJSON.getSleeveLength().get(0));
        }
        // 处理 sleeveShape
        if (CollectionUtil.isNotEmpty(attrDictJSON.getSleeveShape()) && attrDictJSON.getSleeveShape().get(0) != null) {
            attributeRetrieval.setSleeveShape(attrDictJSON.getSleeveShape().get(0));
        }
        // 处理 sleeveShoulder
        if (CollectionUtil.isNotEmpty(attrDictJSON.getSleeveShoulder()) && attrDictJSON.getSleeveShoulder().get(0) != null) {
            attributeRetrieval.setSleeveShoulder(attrDictJSON.getSleeveShoulder().get(0));
        }
        // 处理 neckline
        if (CollectionUtil.isNotEmpty(attrDictJSON.getNeckline()) && attrDictJSON.getNeckline().get(0) != null) {
            attributeRetrieval.setNeckline(attrDictJSON.getNeckline().get(0));
        }
        // 处理 collar
        if (CollectionUtil.isNotEmpty(attrDictJSON.getCollar()) && attrDictJSON.getCollar().get(0) != null) {
            attributeRetrieval.setCollar(attrDictJSON.getCollar().get(0));
        }
        // 处理 design
        if (CollectionUtil.isNotEmpty(attrDictJSON.getDesign()) && attrDictJSON.getDesign().get(0) != null) {
            attributeRetrieval.setDesign(attrDictJSON.getDesign().get(0));
        }
        // 处理 silhouette
        if (CollectionUtil.isNotEmpty(attrDictJSON.getSilhouette()) && attrDictJSON.getSilhouette().get(0) != null) {
            attributeRetrieval.setSilhouette(attrDictJSON.getSilhouette().get(0));
        }
        // 处理 type
        if (CollectionUtil.isNotEmpty(attrDictJSON.getType()) && attrDictJSON.getType().get(0) != null) {
            attributeRetrieval.setType(attrDictJSON.getType().get(0));
        }
        // 处理 openingType
        if (CollectionUtil.isNotEmpty(attrDictJSON.getOpeningType()) && attrDictJSON.getOpeningType().get(0) != null) {
            attributeRetrieval.setOpeningType(attrDictJSON.getOpeningType().get(0));
        }
        // 处理 subtype
        if (CollectionUtil.isNotEmpty(attrDictJSON.getSubtype()) && attrDictJSON.getSubtype().get(0) != null) {
            attributeRetrieval.setSubtype(attrDictJSON.getSubtype().get(0));
        }

        return attributeRetrieval;
    }
}

