package com.persagy.dmp.rwd.qrcode.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.persagy.dmp.common.constant.CommonConstant;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.common.model.response.CommonResult;
import com.persagy.dmp.digital.client.DigitalObjectFacade;
import com.persagy.dmp.file.client.FileClientFacade;
import com.persagy.dmp.file.model.FileInfo;
import com.persagy.dmp.file.model.FileInfoCreator;
import com.persagy.dmp.file.model.FileRequestData;
import com.persagy.dmp.file.model.UploadMes;
import com.persagy.dmp.file.utils.FileStorageHelper;
import com.persagy.dmp.rwd.qrcode.service.QrCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.IdGenerator;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 二维码管理 Service
 * @author:linhuili
 * @date:2021/11/8
 */
@Service
@Slf4j
public class QrCodeServiceImpl implements QrCodeService {

    /**
     * 生成默认二维码
     * @param objectDigitals
     */
    @Override
    public void createDefaultQrCode(List<ObjectNode> objectDigitals) {
        if(CollUtil.isEmpty(objectDigitals)){
            return;
        }
        //获取基础参数
        String projectId = AppContext.getContext().getProjectId();
        String groupCode = AppContext.getContext().getGroupCode();
        for (ObjectNode objectDigital : objectDigitals) {
            //生成二维码图片，并上传到文件服务器
            String fileId = uploadQrCode(groupCode,projectId,objectDigital);
            if(StringUtils.isEmpty(fileId)){
                log.info("生成二维码失败:{}"+objectDigital.get("id"));
                continue;
            }
            //设置对象二维码信息
            setObjectQrCode(objectDigital,fileId);
        }
        //更新对象二维码信息
        DigitalObjectFacade.update(groupCode,projectId,null,null,objectDigitals);
    }

    /**
     * 设置二维码图片
     * @param objectDigital
     */
    public void setObjectQrCode(ObjectNode objectDigital, String fileId){
        //设置二维码信息
        ObjectNode qrCodePic = JsonNodeFactory.instance.objectNode();
        qrCodePic.put("key", fileId);
        qrCodePic.put("name",objectDigital.get("id"));
        qrCodePic.put("type","image");
        objectDigital.put(CommonConstant.QR_CODE_PIC_INFO,qrCodePic);
    }

    /**
     * 生成二维码信息并上传到文件服务器
     * @param objectDigital
     */
    public String uploadQrCode(String groupCode,String projectId,ObjectNode objectDigital){
       try {
           //获取基础参数
           String content =objectDigital.get("id").textValue();
           //生成二维码
           QrConfig qrConfig = new QrConfig(300, 300);
           byte[] bytes = QrCodeUtil.generatePng(content, qrConfig);
           ByteArrayInputStream byteArrayInputStream = IoUtil.toStream(bytes);
           FileInfo fileInfo = FileInfoCreator.of(groupCode, projectId, CommonConstant.FILE_BUCKET_NAME, content + ".png");
           fileInfo.setId(IdUtil.simpleUUID());
           //上传到文件服务器
           String fileId = FileStorageHelper.uploadFile(fileInfo, byteArrayInputStream);
           log.info("对象二维码信息上传到文件服务器，文件id：{}"+fileId);
           return fileId;
       }catch (Exception e){
           log.info("对象二维码信息上传到文件服务器失败{}"+e.getMessage());
       }
       return null;
    }

    /**
     * 生成对象二维码信息
     * @param digital
     */
    public void createObjectQrCode(String groupCode,String projectId,ObjectNode digital){
        //生成二维码图片并上传到文件服务器
        String fileId = uploadQrCode(groupCode,projectId,digital);
        if(StringUtils.isEmpty(fileId)){
            log.info("生成二维码失败:{}"+fileId);
            return;
        }
        //设置对象二维码信息
       setObjectQrCode(digital,fileId);
        //更新对象二维码信息
        List<ObjectNode> list = new ArrayList<>();
        list.add(digital);
        DigitalObjectFacade.update(groupCode,projectId,null,null,list);
    }

    /**
     * 移除对象二维码信息点
     * @param digital
     */
    public void removeObjectQrCode(String groupCode,String projectId,ObjectNode digital){
        ObjectNode infos = JsonNodeFactory.instance.objectNode();
        //删除二维码信息点
        ArrayNode removeInfos = JsonNodeFactory.instance.arrayNode();
        removeInfos.add(CommonConstant.QR_CODE_PIC_INFO);
        infos.put(CommonConstant.REMOVE_FIELD, removeInfos);

        List<ObjectNode> list = new ArrayList<>();
        list.add(digital);
        DigitalObjectFacade.update(groupCode,projectId,null,null,list);
    }
}
