package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSONObject;
import com.nantian.cloud.jljc.entity.doc.TestEntity;
import com.nantian.cloud.jljc.tools.*;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import com.nantian.sc.cloud.common.security.annotation.Inner;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/poi")
public class PoiEditWordController {

    @Autowired
    private MinioTemplate minioTemplate;


    @Inner(value = false)
    @RequestMapping(value = {"/getWord"}, produces = {"application/json;charset=UTF-8"})
    public void getEditWord(@RequestBody Map<String, Object> map, HttpServletResponse response) throws Exception {
        // 首页
        InputStream jljc = minioTemplate.getObject("jljc", "bilu.docx");
        // 续页
        InputStream inputStream = minioTemplate.getObject("jljc", "bilu2.docx");
        String watchDog = SurveyTakeDownUtil.commaConversion((String) map.get("watchdog"));
        String lawNumber = SurveyTakeDownUtil.commaConversion((String) map.get("lawNumber"));
        String itemList = (String) map.get("itemList");
        String breakLawItem = (String) map.get("breakLawItem");
        String str = "    我们是云南省节能监察中心节能监察人员" + watchDog + "，行政执法证编号为" + lawNumber + "，" +
                "已向你出示了执法证件，现依"+ itemList +"对你公司" + breakLawItem + "事项进行调查（询问）。请你配合我们，如实提供有关材料，回答询问，不得做虚假陈述或拒绝、阻挠调查。" +
                "你是否听清楚了？";
        //获取当前年月日时分秒
        Calendar calendar = Calendar.getInstance();
        map.put("total", "1");
        map.put("index", "1");
        map.put("year", calendar.get(Calendar.YEAR));
        map.put("month", calendar.get(Calendar.MONTH) + 1);
        map.put("day", calendar.get(Calendar.DAY_OF_MONTH));
        List<String> question = (List<String>) map.get("question");
        question.add(0,str);
        question.add(1,"答：听清楚了。");


        SurveyTakeDownUtil.conformityDocx(jljc,inputStream,map,response);
    }

    @Inner(value = false)
    @RequestMapping(value = {"/getNotifi"}, produces = {"application/json;charset=UTF-8"})
    public void getNotifacation(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inputStream = null;
        String title = (String) map.get("title");
        if (title.length() <= 13){
            inputStream = minioTemplate.getObject("jljc", "Notification.docx");
        }else {
            inputStream = minioTemplate.getObject("jljc", "Notification1.docx");
        }

        XWPFDocument document = new XWPFDocument(OPCPackage.open(inputStream));
        EditWordZZUtil.readWriteWord(document,map);

        String fileName = map.getOrDefault("companyName", "未知名称") + "现场告知书";
        OutputStream outputStream = null;
        try {
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".docx");
            outputStream = response.getOutputStream();
            document.write(outputStream);
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.flush();
            if (null != outputStream) outputStream.close();
            if (null != inputStream) inputStream.close();
        }
    }

    @Inner(value = false)
    @RequestMapping(value = {"/getInspect"}, produces = {"application/json;charset=UTF-8"})
    public R getInspect(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<String> materials = (List<String>) map.get("materials");
        List<String> list = new ArrayList<>();
        List<String> mas = new ArrayList<>();
        materials.forEach(m -> {
            List<String> charLength = null;
            try {
                charLength = CutStringUtil.getCharLength(m, 544);
            } catch (Exception e) {
                e.printStackTrace();
            }
            charLength.forEach(c -> {
                mas.add(c);
            });
        });
        map.put("total","1");
        map.put("index","1");
        map.put("materials",mas);
        InputStream homePage = minioTemplate.getObject("jljc", "Inspect1.docx");
        InputStream continuationSheet = minioTemplate.getObject("jljc", "Inspect2.docx");
        InputStream inputStream = minioTemplate.getObject("jljc", "Inspect3.docx");
        InspectUtil.inspectWord(homePage,continuationSheet,inputStream,map,response);
        return null;
    }

    @Inner(value = false)
    @PostMapping("/getTest")
    public R getTest(@RequestBody TestEntity testEntity, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("adjunct",testEntity.getAdjunct());
        map.put("text",testEntity.getText());
        map.put("companyName",testEntity.getCompanyName());
        map.put("title",testEntity.getTitle());
        map.put("processName",testEntity.getProcessName());
        map.put("total","1");
        map.put("index","1");
        map.put("tableName1",testEntity.getTableName1());
        map.put("tableName2",testEntity.getTableName2());
        map.put("amount",testEntity.getAmount());
        map.put("tablex",testEntity.getTable());
        if (null == testEntity.getTables() || testEntity.getTables().size() == 0){
            map.put("tables", "");
            map.put("tableName2", "");
            XWPFTableUtil.XWPFTable(map,response);
        }else {
            map.put("tables", testEntity.getTables());
            XWPFTablesUtil.XWPFTable(map, response);
        }
        return null;
    }
}

