package com.yeechart.dotMatrix.module.DotMatrix.controller;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.yeechart.dotMatrix.canvas.DotMatrixImageUtil;
import com.yeechart.dotMatrix.module.DotMatrix.model.bean.GetNotMatrixByTypeCodeRequest;
import com.yeechart.dotMatrix.module.DotMatrix.model.bean.ResultBean;
import com.yeechart.dotMatrix.module.DotMatrix.service.DotMatrixService;
import com.yeechart.dotMatrix.signage.SignageFileUtil;
import com.yeechart.dotMatrix.signage.bean.Ter020201InfoVo;
import com.yeechart.dotMatrix.signage.bean.Ter020201Vo;
import com.yeechart.dotMatrix.signage.bean.mizilzo.BitmapDataVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/DotMatrix")
public class DotMatrixController {
    protected Logger logger = LoggerFactory.getLogger(DotMatrixController.class);

    @Autowired
    private DotMatrixService dotMatrixService;

    @Autowired
    private SignageFileUtil signageFileUtil;

    /**
     * 获取点阵图
     *
     * @param terLampInfoVO
     * @return
     */
    @PostMapping("getDotMatrix")
    public ResultBean getDotMatrix(@RequestBody Ter020201Vo terLampInfoVO) {

        logger.info("################### 获取点整图 #########   更新的类别 " + JSONObject.toJSONString(terLampInfoVO));
        List<BitmapDataVo> bitmapDataVoList = dotMatrixService.getSignageDotMatrix(terLampInfoVO);

        return bitmapDataVoList == null ? ResultBean.defeated("获取点整图失败") : ResultBean.succeed(bitmapDataVoList);

    }

    @PostMapping("getDotMatrixByTypeCode")
    public ResultBean getDotMatrixByTypeCode(@RequestBody GetNotMatrixByTypeCodeRequest req) {
        if (StringUtils.isEmpty(req.getDeId())) {
            return ResultBean.defeated("非法设备ID");
        }
        if (StringUtils.isEmpty(req.getTypeCode())) {
            return ResultBean.defeated("非法设备typeCode");
        }
//        String[] typeCodesArr = req.getTypeCode().split(",");
//        List<BitmapDataVo> bitmapDataVoList = new ArrayList<>();
//        for (String typeCode : typeCodesArr) {
//            if (req.getIsDefault() != null && req.getIsDefault()) {
//                if (!typeCode.startsWith("D")) {
//                    return ResultBean.defeated("预览初始图时,点阵图类型编号不正确,必须为D开头");
//                }
//            }
//            BitmapDataVo bitmapDataVo = signageFileUtil.getLastBitmapDataVo(req.getDeId(), typeCode, req.getIsDefault());
//            bitmapDataVoList.add(bitmapDataVo);
//        }
//        return ResultBean.succeed(bitmapDataVoList);
        return ResultBean.defeated("未实现");
    }

    /**
     * 获取自检图
     *
     * @return
     */
    @GetMapping("getSelfCheckDiagram")
    public ResultBean getSelfCheckDiagram() {

        List<BitmapDataVo> bitmapDataVoList = dotMatrixService.getBatchBitmapQualityInspection();

        return bitmapDataVoList == null ? ResultBean.defeated("获取自检图失败") : ResultBean.succeed(bitmapDataVoList);

    }


    /**
     * 删除点阵图
     *
     * @return
     */
    @GetMapping("delDotMatrix")
    public ResultBean delDotMatrix(String deID) {
        logger.info("delete dotmatrix for device: {}", deID);
         dotMatrixService.delDotMatrix(deID);

        return  ResultBean.succeed();

    }


    /**
     * 预览点阵图
     *
     * @param typeCode  需要预览的点阵图类型编号
     * @param DEID      设备编号（默认图图时可不传）
     * @param isDefault 是否是初始图（不传时，默认为业务图）
     * @return
     */
    @GetMapping("previewBitmap")
    public ResponseEntity<byte[]> previewBitmap(String typeCode, String DEID, Boolean isDefault, HttpServletRequest request) {

        if (isDefault == null || !isDefault) {
            if (StringUtils.isEmpty(DEID)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .header("Content-Type", "text/plain; charset=UTF-8")
                        .body("预览业务图时,设备ID不正确".getBytes());
            }

            if (StringUtils.isEmpty(typeCode)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .header("Content-Type", "text/plain; charset=UTF-8")
                        .body("预览业务图时,点阵图类型编号不正确".getBytes());
            }
        } else {
            if (StringUtils.isEmpty(typeCode)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .header("Content-Type", "text/plain; charset=UTF-8")
                        .body("预览初始图时,点阵图类型编号不正确".getBytes());
            }
            if (!typeCode.startsWith("D")) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .header("Content-Type", "text/plain; charset=UTF-8")
                        .body("预览初始图时,点阵图类型编号不正确,必须为D开头".getBytes());
            }
            DEID = "default";
        }

        // 设置响应头，指定内容类型为image/png
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);


        BufferedImage bufferedImage;

        BitmapDataVo bitmapDataVo;
        if(DEID.contains("test")){
            Ter020201Vo ter020201Vo = new Ter020201Vo();
            if("test".equals(DEID)){
                ter020201Vo.setTer020201InfoVo(Ter020201InfoVo.test3("测试使用"));
            }else{
                ter020201Vo.setTer020201InfoVo(Ter020201InfoVo.defaultInit("测试默认"));
            }

            Set<String> typeCodeList = new HashSet<>();
            typeCodeList.add(typeCode);
            ter020201Vo.setType(new Integer[]{0});


            List<BitmapDataVo> bitmapDataVoList  = dotMatrixService.getSignageDotMatrix(ter020201Vo);
            Map<String,BitmapDataVo> bitmapDataVoMap = bitmapDataVoList.stream().collect(Collectors.toMap(BitmapDataVo::getTypeCode, Function.identity()));
            bitmapDataVo =bitmapDataVoMap.get(typeCode);

        }else{
            bitmapDataVo =  signageFileUtil.getLastBitmapDataVo(DEID, typeCode, "未知", isDefault);
        }

        if (bitmapDataVo == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .header("Content-Type", "text/plain; charset=UTF-8")
                    .body("预览初始图时,设备相关图不存在，可能设备已被删除".getBytes());
        }


        byte[] twoBytes = bitmapDataVo.getTwoData();

        int width = 480;
        int height = 648;


        typeCode = typeCode.replace("D", "");
        if (typeCode.startsWith("0000") || typeCode.startsWith("0100")) {

            if (typeCode.length() > 8) {
                String typeCode2 = typeCode.substring(6);
                String chartStr = typeCode2.substring(0, 2);
                String stateStr = typeCode2.substring(2);

                if (!"FF".equals(chartStr)) {
                    //图表类
                    height = height - width / 10 * 2 - width / 40 * 2;

                    width = width - width / 10 * 2 - width / 40 * 2;

                }
            }

            twoBytes = DotMatrixImageUtil.canvasBitmapArraysToTwo(
                    DotMatrixImageUtil.screenFlip(DotMatrixImageUtil.twoToCanvasBitmapArrays(twoBytes, height, width)
                    )
            );

            //点阵图转换为图片
            bufferedImage = DotMatrixImageUtil.pixelArrayToConvertImage(twoBytes, height, width);
        } else {
            twoBytes = DotMatrixImageUtil.canvasBitmapArraysToTwo(
                    DotMatrixImageUtil.screenHorizontalToVertical(DotMatrixImageUtil.twoToCanvasBitmapArrays(twoBytes, height, width)
                    )
            );

            //点阵图转换为图片
            bufferedImage = DotMatrixImageUtil.pixelArrayToConvertImage(twoBytes, width, height);
        }


        // 将图片转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "png", baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        byte[] imageBytes = baos.toByteArray();

        // 返回图片数据
        return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);


    }


}
