package org.jeecg.module.custom.ocr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.module.custom.ocr.api.entity.FormRecord;
import org.jeecg.module.custom.ocr.api.entity.LivePhoto;
import org.jeecg.module.custom.ocr.api.thread.TaskQueue;
import org.jeecg.module.custom.ocr.base.BaseServiceImpl;
import org.jeecg.module.custom.ocr.config.ApiConfig;
import org.jeecg.module.custom.ocr.dataDao.OcrPictureMybatisDao;
import org.jeecg.module.custom.ocr.dataobject.OcrPicture;
import org.jeecg.module.custom.ocr.dataobject.OcrPictureInfo;
import org.jeecg.module.custom.ocr.dataobject.Task;
import org.jeecg.module.custom.ocr.service.OcrPictureInfoService;
import org.jeecg.module.custom.ocr.service.OcrPictureService;
import org.jeecg.module.custom.ocr.service.OcrTaskchildPictureService;
import org.jeecg.module.custom.ocr.utils.DataDictionaryUtil;
import org.jeecg.module.custom.ocr.utils.ImageClassUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务层实现
 */
@Service("ocrPictureService")
@Slf4j
public class OcrPictureServiceImpl extends BaseServiceImpl<OcrPictureMybatisDao, OcrPicture> implements OcrPictureService {

    @Resource
    private OcrTaskchildPictureService ocrTaskchildPictureService;

    /**
     * 注入api 配置信息
     */
    @Autowired
    private ApiConfig apiConfig;

    /**
     * 字典数据添加工具类
     */
    @Autowired
    DataDictionaryUtil dataDictionaryUtil;

    @Value("${image.classifyPath}")
    private String classifyPath;

    @Value("${image.classifyBaseUrl}")
    private String classifyBaseUrl;

    @Resource
    private OcrPictureInfoService ocrPictureInfoService;

    public List<OcrPicture> listPage(Wrapper<OcrPicture> queryWrapper) {

        long count = this.count(queryWrapper);
        Page<OcrPicture> ocrPicturePage = new Page<>(1, count);
        ocrPicturePage.setMaxLimit(count);
        IPage<OcrPicture> iPage = this.page(ocrPicturePage, queryWrapper);

        return iPage.getRecords();
    }

    @Override
    public int savePictures(List<OcrPicture> ocrPictureList) {
        //1.字典数据 解析入库
//        boolean b = dataDictionaryUtil.pictureDataDictionarySaveArray(ocrPictureList);

        //2.调整图片地址，补齐域名
//        for (OcrPicture picture : ocrPictureList) {
//            picture.setCreateTime(System.currentTimeMillis()); //获取创建时间戳
//        }

        try {
            boolean saveBatch = false;
//            synchronized (lock) {
//                // 同步的代码块
//                saveBatch = this.saveOrUpdateBatch(ocrPictureList);
//                //通过与不通过的任务需要直接创建任务。
//                for (OcrPicture picture : ocrPictureList) {
//                    if ("8".equals(picture.getTaskstatus()) || "9".equals(picture.getTaskstatus()) || "10".equals(picture.getTaskstatus())) {
//                        boolean taskSaveResult = ocrTaskchildPictureService.createTaskOldPicture(picture);
//                        if (!taskSaveResult) {
//                            log.error("旧数据创建任务失败,任务id:{}", picture.getTaskId());
//                        }
//                    }
//                }
//
//            }

            //3.添加图片信息
            if (saveBatch) {
//            this.savePicturesInfo(ocrPictureList);
                this.convertImage(ocrPictureList);
                return ocrPictureList.size();
            }
            log.error("存储图片失败:{}", JSONObject.toJSON(ocrPictureList));
        } catch (Exception e) {
            log.error("存储图片异常:{}", e.getMessage());
        }

        return 0;
    }

    @Override
    public Map<String, String> getOcrPictureClassifyAndHash(String img) {
        JSONObject jsonObjectSimi = ImageClassUtil.getClassify(img, "1", classifyPath, classifyBaseUrl);
        //返回内容为零，表示成功，否则表示失败
        if (null != jsonObjectSimi && jsonObjectSimi.getString("code").equals("0") && jsonObjectSimi.get("data") != null && jsonObjectSimi.getJSONArray("data").size() > 0) {
            JSONObject data = jsonObjectSimi.getJSONArray("data").getJSONObject(0);
            Map<String, String> map = new HashMap();
            map.put("classId", data.getString("classId"));
            map.put("hash", data.getString("hash"));
            return map;
        } else {
            return null;
        }
    }

    /**
     * 新增图片信息表
     *
     * @param ocrPicture
     */
    @Override
    public void savePicturesInfo(OcrPicture ocrPicture) {
        boolean isConnection = true;
        String url = ocrPicture.getImageUrl();
        if (!StringUtils.isEmpty(ocrPicture.getLocalImageUrl())) {
            url = ocrPicture.getLocalImageUrl();
            isConnection = false;
        }
        OcrPictureInfo imageInfo = getImageInfo(url, isConnection);
        imageInfo.setPictureId(ocrPicture.getId());
        imageInfo.setImgName(String.valueOf(ocrPicture.getImageNo()));
        ocrPictureInfoService.save(imageInfo);
    }

    @Override
    public OcrPicture getByTaskId(Long taskId) {
        if (taskId == null) {
            return null;
        }
        // 使用MyBatis-Plus的lambda查询
        return this.lambdaQuery().eq(OcrPicture::getTaskId, taskId).one();
    }

    @Override
    public void savePicturesInfo(Task task, String fileName, String imageUrl, String type) {
        boolean isConnection = true;

        OcrPictureInfo imageInfo = getImageInfo(imageUrl, isConnection);
        imageInfo.setPictureId(task.getId());
        imageInfo.setImgName(fileName);
        imageInfo.setImageUrl(imageUrl);
        imageInfo.setLocalImageUrl(task.getLocalImageUrl());
        imageInfo.setImgHash(task.getImgHash());
        imageInfo.setTaskId(task.getId());
        imageInfo.setTaskNo(task.getTaskNo());
        imageInfo.setType(type);
        ocrPictureInfoService.save(imageInfo);
    }

    /**
     * 获取图片信息
     *
     * @param imageUrl     图片地址 两种 网络或者本地图片
     * @param isConnection 是否是url 开启网络请求
     * @return
     */
    private OcrPictureInfo getImageInfo(String imageUrl, boolean isConnection) {

        try {
            BufferedImage image = null;
            Integer imageSize = 0;
            if (isConnection) {
                // 创建URL对象
                URL url = new URL(imageUrl);
                // 打开连接
                URLConnection urlConnection = url.openConnection();
                // 获取图片大小
                imageSize = urlConnection.getContentLength();
                // 使用ImageIO读取图片
                image = ImageIO.read(url);
            } else {
                File file = new File(imageUrl);
                image = ImageIO.read(file);
                imageSize = (int) file.length();
            }

            if (image != null) {
                OcrPictureInfo info = new OcrPictureInfo();
                // 获取图片宽度和高度
                int width = image.getWidth();
                int height = image.getHeight();

                // 获取色彩空间类型
                ColorSpace colorSpace = image.getColorModel().getColorSpace();
                String colorSpaceType;
                switch (colorSpace.getType()) {
                    case ColorSpace.TYPE_RGB:
                        colorSpaceType = "RGB";
                        break;
                    case ColorSpace.TYPE_GRAY:
                        colorSpaceType = "Grayscale";
                        break;
                    case ColorSpace.TYPE_CMYK:
                        colorSpaceType = "CMYK";
                        break;
                    default:
                        colorSpaceType = "Other";
                        break;
                }
                String formatName = ImageIO.getImageReadersByMIMEType("image/jpeg").next().getFormatName();
                info.setCreateTime(System.currentTimeMillis());
                info.setUploadTime(System.currentTimeMillis());
                info.setTagTime(System.currentTimeMillis());
                info.setImgSpace(colorSpaceType);
                info.setImgSize(imageSize.toString());
                info.setImgMeasure(width + "x" + height);
                info.setImgFormat(formatName);
                info.setSource("无量云2.0");
                return info;
            } else {
                log.info("Cannot read image from URL.");
                return null;
            }
        } catch (Exception e) {
            log.error("Error: " + e.getMessage());
        }
        return null;
    }

    private void convertImage(List<OcrPicture> list) {
        for (OcrPicture ocrPicture : list) {
            FormRecord entity = new FormRecord();
            LivePhoto livePhoto = new LivePhoto();
            livePhoto.setMd5(String.valueOf(ocrPicture.getId()));
            livePhoto.setFileUrl(ocrPicture.getImageUrl());

            String imgurl = ocrPicture.getImageUrl();
            livePhoto.setLocalImgUrl(apiConfig.getLocalImagePath() + imgurl.substring(imgurl.lastIndexOf("/")));

            boolean addedToQueue = false;
            while (!addedToQueue) {
                try {
                    addedToQueue = TaskQueue.pictureImgToLocalPushData(entity);
                    if (addedToQueue) {
                        break;
                    }
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    log.error("放入图片下载队列,等待休眠异常:{}", e.getMessage());
                }
            }
        }
    }
}
