package com.zhongshu.card.server.core.service.base;

import com.github.microservice.core.util.net.HttpClient;
import com.mongodb.client.result.UpdateResult;
import com.zhongshu.card.server.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * @author TRX
 * @date 2024/5/31
 */
@Slf4j
@Service
public class CommonService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 编辑数据
     *
     * @param standardData
     * @param collectionName
     * @return
     */
    public Object updateData(Map<String, Object> standardData, String collectionName) {
        collectionName = CommonUtil.getCollectionName(collectionName);
        Object id = standardData.get("id");
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        standardData.forEach((key, value) -> {
            if (!"id".equals(key)) {
                update.set(key, value);
            }
        });
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, collectionName);
        return updateResult.getUpsertedId();
    }

    public Object updateData(String id, Map<String, Object> standardData, String collectionName) {
        collectionName = CommonUtil.getCollectionName(collectionName);
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        standardData.forEach((key, value) -> {
            if (!"id".equals(key)) {
                update.set(key, value);
            }
        });
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, collectionName);
        return updateResult.getUpsertedId();
    }

    public Object updateData(Map<String, Object> where, Map<String, Object> standardData, String collectionName) {
        collectionName = CommonUtil.getCollectionName(collectionName);
        Criteria criteria = new Criteria();
        if (where != null) {
            where.forEach((key, value) -> {
                if (value != null && value instanceof List<?>) {
                    List<Object> _temp = (List<Object>) value;
                    criteria.and(key).in(_temp);
                } else {
                    criteria.and(key).is(value);
                }
            });
        }
        Query query = new Query(criteria);
        Update update = new Update();
        standardData.forEach((key, value) -> {
            if (!"id".equals(key)) {
                update.set(key, value);
            }
        });
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, collectionName);
        return updateResult.getUpsertedId();
    }

    /**
     * 得到 resources 目录下文件的 base64字符串
     *
     * @param filePath
     * @return
     */
    public String getResourceFileBase64(String filePath) {
        String base64 = "";
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + filePath;
        try {
            File file = new File(path);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] fileBytes = new byte[(int) file.length()];
            fileInputStream.read(fileBytes);
            fileInputStream.close();

            base64 = Base64.getEncoder().encodeToString(fileBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64;
    }

    /**
     * 文件转为 base64
     *
     * @param fileUrl 网络地址
     * @return
     */
    public String getUrlFileBase64(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return "";
        }
        String base64 = "";
        try {
            HttpClient httpClient = new HttpClient();
            byte[] fileBytes = httpClient.get(fileUrl);
//            InputStream input = new ByteArrayInputStream(fileBytes);
            base64 = Base64.getEncoder().encodeToString(fileBytes);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("getUrlFileBase64 {}", e.getMessage());
        }
        return base64;
    }

}
