package com.brilliance.isc.dsp.controller;

import cn.hutool.core.lang.Assert;
import com.brilliance.isc.dsp.config.DocBean;
import com.brilliance.isc.dsp.model.*;
import com.brilliance.isc.dsp.service.FrameService;
import com.brilliance.isc.dsp.utils.Result;
import com.brilliance.isc.common.context.AppEnv;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class ParseDspFileController {
    private static final Logger logger = LoggerFactory.getLogger(ParseDspFileController.class);

    private static final String KEYONE = "FrameField";
    private static final String KEYTWO = "FieldValue";
    private static final String KEYTHREE = "FramePanel";
    private static final String KEYFOUR = "GridValue";
    private static final String KEYFIVE = "GridLists";
    private static final String KEYSIX = "Label";
    private static final String KEYSEVEN = "Grid";



    @Autowired
    private DocBean docBean;
    @Autowired
    private FrameService frameService;
    @Autowired
    private AppEnv appEnv;

    @PostMapping("/dspfile")
    public <T> Result dspParse(@RequestBody Map<String, Object> map) throws Exception {
//        public <T> Result dspParse(@RequestParam(value = "file") String fileName) throws Exception {
        //获取上传文件名称
        //String fileName = file.getOriginalFilename();
        //获取上传文件类型
        //String contentType = file.getContentType();
//        String filePath = docBean.getFilePath() + fileName;
        String fileName = (String) map.get("file") + ".DSP";
//        fileName = fileName + ".DSP";
        String filePath = appEnv.getDataPath("display", fileName);
        String fileType = fileName.substring(fileName.indexOf(".") + 1);
        if (!"DSP".equals(fileType)) {
            logger.error("文件格式错误!");
            return Result.error().message("文件格式错误!");
        }
        //获取上传文件输入流，便于文件内容读写操作
        FileInputStream inputStream = new FileInputStream(filePath);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GB2312");
        BufferedReader reader = new BufferedReader(inputStreamReader);
        // 解析文件内容并返回
        List<Panel> panelList = new ArrayList<>();
        Panel panel = new Panel();
        List<Table> tableList = null;
        FrameField frameField = null;
        List<T> list = null;
        String prop = null;
        List<String> tableValues =null;

        Table table1 = null;

        List<String> props = null;
        List<String> widths = null;
        Grid grid = null ;

        List<GridValue> gridValues = null ;
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                // 读取到的结果
                HashMap<String, Object> result = frameService.printEibsElement(line);
                if (result != null) {
                    // 多个panel组装
                    if (result.containsKey(KEYTHREE)) {
                        panel = (Panel) result.get(KEYTHREE);
                        panelList.add(panel);
                        list = new ArrayList<>();
                    }
                    // 多个field组装
                    Assert.notNull(list);
                    if (result.containsKey(KEYONE)) {
                        frameField = (FrameField) result.get(KEYONE);
                        list.add((T) frameField);
                    }
                    // 多个value组装到上一行的field上
                    if (result.containsKey(KEYTWO)) {
                        FrameField frameValue = (FrameField) result.get(KEYTWO);
                        FrameField ff = (FrameField) list.get(list.size() - 1);
                        ff.setValue(ff.getValue() != null ? ff.getValue()  + frameValue.getValue() : frameValue.getValue());
                        list.remove(list.get(list.size() - 1));
                        ff.setValue(ff.getValue().replaceAll("\u001F", ""));
                        list.add((T) ff);
                        panel.setList(list);
                    }


                    if (result.containsKey(KEYSIX)) {
                        Label label = (Label) result.get(KEYSIX);
                        label.setViewType("Label");
                        list.add((T) label);
                        panel.setList(list);
                    }

//                    if (result.containsKey(KEYSEVEN)) {
//                        tableList = new ArrayList<>();
//                        table1 = new Table();
//                        props = new ArrayList<>();
//                        widths = new ArrayList<>();
//                        tableValues = new ArrayList<>();
//                        grid = new Grid();
//                    }
//
//                        if (result.containsKey(KEYFIVE)) {
//                        GridLists gridLists = (GridLists) result.get(KEYFIVE);
//                            widths.add(gridLists.getWidth());
//                            frameField.setWidths(widths);
//                    }
//
//                    if (result.containsKey(KEYFOUR)) {
//                        GridValue gridValue = (GridValue) result.get(KEYFOUR);
//                        if ("0".equals(gridValue.getRow())) {
//                            prop = gridValue.getValue();
//                            props.add(prop);
//                            frameField.setProps(props);
//                        } else  {
//                          //  if (Integer.parseInt(gridValue.getRow()) < Integer.parseInt(grid.getRows()) - 1 ){
//                            tableValues.add(gridValue.getValue());
//                         //   } else {
//                           //     tableValues.add(gridValue.getValue() + "&&");
//                          //  }
//                            frameField.setTableValues(tableValues);
//                        }
//                        FrameField ff = (FrameField) list.get(list.size() - 1);
//                        list.remove(list.get(list.size() - 1));
//                        list.add((T) ff);
//                        panel.setList(list);
//                    }



//                    if (result.containsKey(KEYSEVEN)) {
//                        tableList = new ArrayList<>();
//                        table1 = new Table();
//                        props = new ArrayList<>();
//                        widths = new ArrayList<>();
//                        tableValues = new ArrayList<>();
//
//
//                    }
//
//                    if (result.containsKey(KEYFIVE)) {
//                        GridLists gridLists = (GridLists) result.get(KEYFIVE);
//                        table1 = new Table();
//                        table1.setWidth(gridLists.getWidth());
//                        tableList.add(table1);
//                    }
//
//                    if (result.containsKey(KEYFOUR)) {
//                        GridValue gridValue = (GridValue) result.get(KEYFOUR);
//                        int i  = Integer.parseInt(gridValue.getRow());
//                        int j = Integer.parseInt(gridValue.getColumn());
//                        if (i == 0) {
//                            Table table2 = tableList.get(i);
//                            table2.setProp(gridValue.getValue());
//                            tableList.remove(j);
//                            tableList.add(j,table2);
//                        } else {
//                            Table table2 = tableList.get(i);
//                            //table2.setProp(gridValue.getValue());
//                            tableValues.add(gridValue.getValue());
//                            table2.setValues(tableValues);
//                        }
//                        frameField.setTableList(tableList);
//                    }



                    if (result.containsKey(KEYSEVEN)) {
                        Grid grid1 = (Grid) result.get(KEYSEVEN);
                        widths = new ArrayList<>();
                        gridValues = new ArrayList<>();
                    }

                    if (result.containsKey(KEYFIVE)) {
                        GridLists gridLists = (GridLists) result.get(KEYFIVE);
                        Assert.notNull(widths);
                        widths.add(gridLists.getWidth());
                    }

                    if (result.containsKey(KEYFOUR)) {
                        GridValue gridValue = (GridValue) result.get(KEYFOUR);
                        Assert.notNull(widths);
                        gridValue.setWidth(widths.get(Integer.parseInt(gridValue.getColumn())));
                        Assert.notNull(gridValues);
                        gridValues.add(gridValue);
                        Assert.notNull(list);
                        FrameField ff = (FrameField) list.get(list.size() - 1);
                        ff.setGridValues(gridValues);
                        list.remove(list.get(list.size() - 1));
                        list.add((T) ff);
                        panel.setList(list);
                    }
                }
            }

        } catch (Exception e) {
            logger.error("ParseDspFileController.dspParse 处理DSP文件解析失败!");
            return Result.error().message("DSP文件解析失败!");
        }
        // 关闭流对象
        if (inputStream != null) {
            inputStream.close();
        }
        if (inputStreamReader != null) {
            inputStreamReader.close();
        }
        if (reader != null) {
            reader.close();
        }
        Object o = panelList;
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("panelLists", o);
        return Result.ok().data(resultMap);
    }
}
