package com.yeechart.dotMatrix.signage;

import com.yeechart.dotMatrix.canvas.*;
import com.yeechart.dotMatrix.oss.LatticeOSSUpload;
import com.yeechart.dotMatrix.signage.bean.mizilzo.BitmapDataVo;
import com.yeechart.dotMatrix.util.OtherUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import static com.yeechart.dotMatrix.signage.SignageDrawUtil.*;
import static com.yeechart.dotMatrix.signage.TypeCodeUtil.*;

/**
 * 生成硬件质检图
 */

@Component
public class SignageQualityUtil {

    @javax.annotation.Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private LatticeOSSUpload latticeOSSUpload;

    @Autowired
    private SignageFileUtil signageFileUtil;

     @Autowired
    private DotMatrixDrawtextUtil dotMatrixDrawtextUtil;

    /************************************** 生成质检图  **************************************/

    /**
     * 绘制整图/背景图
     *
     * @param isBg 是否为背景图(false 则生产有结果的整图， true 则生产不带结果的背景图)
     * @return
     */
    private  int[][] canvasBitmapQualityInspection(boolean isBg) {

        int[][] canvasBitmapArrays = new int[height][width];

        int startRowA = height / 40;

        String text = "蚁巢工厂测试";

        int[][] fontBinaryArray = dotMatrixDrawtextUtil.drawingText(text, textFontSize, noChineseFontSize2);

        int startColumnA = width / 2 - fontBinaryArray[0].length / 2;

        DotMatrixCanvasUtil.mergeDotMatrices(canvasBitmapArrays, fontBinaryArray, startRowA, startColumnA, new int[]{1, 1, 1, 1});

        //绘制间隔实线
        DotMatrixDrawShapeUtil.drawLine(canvasBitmapArrays, 1, 0, 0, height / 20 + height / 40 + noChineseFontSize * 4, rightMargins, width - rightMargins);


        String[] data = new String[]{
                "运行", "待料", "停机", "保养", "故障", "维修",
                "NFC", "WIFI",
                "充电", "语音键",
                "音量加键", "音量减键"
        };

        for (int i = 0; i < data.length; i++) {
            canvasBitmapQualityInspectionItem(canvasBitmapArrays, i, data[i],
                    isBg ? null : false);
        }
        if (!isBg) {
            canvasBitmapQualityInspectionBigResult(canvasBitmapArrays, false);
        }


        return canvasBitmapArrays;
    }


    /**
     * 绘制质检项目
     *
     * @param canvasBitmapArrays 画布
     * @param number             质检的项目序号
     * @param text               质检的名称
     * @param pass               是否通过(为空时 则不绘制质检结果，true 为通过, false 为不通过)
     */
    private  void canvasBitmapQualityInspectionItem(int[][] canvasBitmapArrays, int number, String text, Boolean pass) {

        int startRowA = height / 20 + noChineseFontSize * 7 + Math.max(textFontSize2Height, noChineseFontSizeHeight);
        int startColumnA = rightMargins;
        int interval = height / 20;


        int rows = number / 2;//行数
        int columns = number % 2;//列数

        startRowA = startRowA + (Math.max(textFontSize2Height, noChineseFontSizeHeight) + interval) * rows;

        if (columns != 0) {
            startColumnA = canvasBitmapArrays[0].length / 2 + startColumnA;
        }


        text = text + ":";
        dotMatrixDrawtextUtil.drawingText(
                canvasBitmapArrays,
                text,
                startRowA,
                startColumnA,
                textFontSize2,
                noChineseFontSize);

        //绘制结果
        if (pass != null) {
            interval = canvasBitmapArrays[0].length / 2 - rightMargins * 2 - textFontSize2 * 2;
            text = pass ? "通过" : "异常";

            dotMatrixDrawtextUtil.drawingText(
                    canvasBitmapArrays,
                    text,
                    startRowA,
                    startColumnA + interval,
                    textFontSize2,
                    noChineseFontSize);
        }

    }

    /**
     * 绘制 单项结果文本
     *
     * @param pass
     * @return
     */
    private  int[][] canvasBitmapQualityInspectionResult(boolean pass) {
        String text = pass ? "通过" : "异常";
        return dotMatrixDrawtextUtil.drawingText(text, textFontSize2, noChineseFontSize);
    }


    /**
     * 绘制最终的结果
     *
     * @param canvasBitmapArrays
     * @param pass
     */
    private  int[][] canvasBitmapQualityInspectionBigResult(int[][] canvasBitmapArrays, boolean pass) {
        String text = pass ? "通过" : "异常";
        int[][] canvasBgArrays = new int[160]//height/8*2
                [width - rightMargins * 2];//
        //赋值初始化全为1
        for (int i = 0; i < canvasBgArrays.length; i++) {
            for (int j = 0; j < canvasBgArrays[0].length; j++) {
                canvasBgArrays[i][j] = 1;
            }
        }

        int[][] fontBinaryArray = dotMatrixDrawtextUtil.drawingText(text, textFontSizeCheck, noChineseFontSizeCheck);

        DotMatrixCanvasUtil.mergeDotMatricesConfuse(
                canvasBgArrays,
                fontBinaryArray,
                canvasBgArrays.length / 2 - fontBinaryArray.length / 2,
                canvasBgArrays[0].length / 2 - fontBinaryArray[0].length / 2,
                1
        );


        if (canvasBitmapArrays != null) {
            //合并画布
            DotMatrixCanvasUtil.mergeDotMatricesConfuse(
                    canvasBitmapArrays,
                    canvasBgArrays,
                    height - canvasBgArrays.length / 2 * 3,
                    rightMargins,
                    0
            );
        }

        return canvasBgArrays;

    }


    /**
     * 生成自检点阵图
     *
     * @param
     * @return
     */
    public  CompletableFuture<List<BitmapDataVo>> getBatchBitmapQualityInspection() {

        List<BitmapDataVo> bitmapDataVoList = new ArrayList<>();


        String dId = "SelfTest";//deviceStock.getDeviceId();

        String path = "device/020201/lattice/" + dId + "/";//路径;

        byte[] data = null;

        BitmapDataVo bitmapDataVo = null;
        //背景图
        int[][] bgCanvasBitmapArrays = canvasBitmapQualityInspection(true);

        // 由于 硬件屏幕原因 需要将 将右屏的画布旋转
        data = DotMatrixImageUtil.canvasBitmapArraysToTwo(
                DotMatrixImageUtil.screenHorizontalToVertical(
                        bgCanvasBitmapArrays
                )
        );
        bitmapDataVo = signageFileUtil.dealWithBitmapDataVo(data, dId, path, "T" + CODE_ON + CODE_RIGHT + CODE_SELF_TEST + "00", false);
        bitmapDataVoList.add(bitmapDataVo);


        int[][] yesResultCanvasBitmapArrays = canvasBitmapQualityInspectionBigResult(null, true);
        // 由于 硬件屏幕原因 需要将 将右屏的画布旋转
        data = DotMatrixImageUtil.canvasBitmapArraysToTwo(
                DotMatrixImageUtil.screenFlip(
                        DotMatrixImageUtil.screenHorizontalToVertical(
                                yesResultCanvasBitmapArrays
                        )
                )
        );
        bitmapDataVo = signageFileUtil.dealWithBitmapDataVo(data, dId, path, "T" + CODE_ON + CODE_RIGHT + CODE_SELF_TEST + "03", false);
        bitmapDataVoList.add(bitmapDataVo);


        int[][] noResultCanvasBitmapArrays = canvasBitmapQualityInspectionBigResult(null, false);
        // 由于 硬件屏幕原因 需要将 将右屏的画布旋转
        data = DotMatrixImageUtil.canvasBitmapArraysToTwo(
                DotMatrixImageUtil.screenFlip(
                        DotMatrixImageUtil.screenHorizontalToVertical(
                                noResultCanvasBitmapArrays
                        )
                )

        );
        bitmapDataVo = signageFileUtil.dealWithBitmapDataVo(data, dId, path, "T" + CODE_ON + CODE_RIGHT + CODE_SELF_TEST + "04", false);
        bitmapDataVoList.add(bitmapDataVo);


        CompletableFuture<Void> uploadFuture = latticeOSSUpload.uploadImages(dId, bitmapDataVoList);

        // 在上传操作完成后，才执行返回操作
        return uploadFuture.thenApplyAsync(v -> {
            // 这里可以添加更多操作，如果需要
            return bitmapDataVoList; // 最终返回 bitmapDataVoList
        }, threadPoolTaskExecutor);


    }


    /**
     * 基础字节库
     */
    private void GenerateCustomFonts() {

        String[] fonts = new String[]{
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                ".", "-", "_", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-",
        };

        StringBuilder sb = new StringBuilder();
        for (String font : fonts) {

            byte[] data = DotMatrixConversionUtil.twoTo16Lattice(
                    DotMatrixImageUtil.canvasBitmapArraysToTwo(
                            DotMatrixImageUtil.screenFlip(
                                    DotMatrixImageUtil.screenHorizontalToVertical(
                                            dotMatrixDrawtextUtil.drawingText(font, noChineseFontSize, noChineseFontSize)
                                    )
                            )

                    )
            );


            sb.append("\n");
            sb.append("字符为【");
            sb.append(font);
            sb.append("】的点阵图：");
            sb.append("\n");
            for (byte a : data) {
                String b = OtherUtil.Bytes2HexString(new byte[]{a});
                sb.append("0x");
                sb.append(OtherUtil.strToHighZeroPadding(b, 2));
                sb.append(",");
            }

        }

//        saveToFile("D:/WorkSpace/Web/image/Device/自定义字库","硬件","基础字库", sb.toString().getBytes());
    }

}
