package com.ejweb.modules.report.web;

import com.ejweb.conf.GConstants;
import com.ejweb.core.utils.StringUtils;
import com.ejweb.modules.report.entity.CtBbtcBusType;
import com.ejweb.modules.report.entity.ReportAttachmentEntity;
import com.ejweb.modules.report.entity.ReportEntity;
import com.ejweb.modules.report.service.CtBbtcBusTypeService;
import com.ejweb.modules.report.service.ReportService;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.List;

/**
 * 举报转为Word文档Controller
 *
 * @author lixy
 * @version 2017-10-19
 */
@Controller
@RequestMapping(value = "${adminPath}/report")
public class ReportToWordController {
    @Autowired
    private ReportService reportService;

    @Autowired
    protected CtBbtcBusTypeService CtBbtcBusTypeService;

    @ModelAttribute
    public ReportEntity get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return reportService.get(id);
        } else {
            return new ReportEntity();
        }
    }

    @RequestMapping(value = "toWord")
    public void toWord(ReportEntity reportEntity, String flag, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws IOException, XmlException {
        //Blank Document
        XWPFDocument document = new XWPFDocument();
        //Write the Document in file system
        // String reportProjectTitle = reportEntity.getReportProject();
//        if (reportProjectTitle.contains("/")){
//            reportProjectTitle = reportProjectTitle.replace("/","|");
//        }
//        if (reportProjectTitle.contains("\\")){
//            reportProjectTitle = reportProjectTitle.replace("\\","|");
//        }
        FileOutputStream out = new FileOutputStream(GConstants.FILE_UPLOAD_DIR + "pdf/" + reportEntity.getId() + ".docx");
//        FileOutputStream out = new FileOutputStream("D:/1.docx");
//        FileOutputStream out = new FileOutputStream("C:/1.docx");
        //添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
        //设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun titleParagraphRun = titleParagraph.createRun();
        titleParagraphRun.setText("举报记录");
        titleParagraphRun.setColor("000000");
        titleParagraphRun.setFontSize(20);

        //段落 第一段 举报内容
        XWPFParagraph paragraphBasic = document.createParagraph();
        XWPFRun runBasic = paragraphBasic.createRun();
        runBasic.setText("举报内容");
        runBasic.setColor("696969");
        runBasic.setFontSize(16);

        //换行
        XWPFParagraph newLine1 = document.createParagraph();
        XWPFRun paragraphRun1 = newLine1.createRun();
        paragraphRun1.setText("\r");

        //基本信息表格
        XWPFTable basicInfoTable = document.createTable();
        //去表格边框
        basicInfoTable.getCTTbl().getTblPr().unsetTblBorders();
        //列宽自动分割
        CTTblWidth infoTableWidth = basicInfoTable.getCTTbl().addNewTblPr().addNewTblW();
        infoTableWidth.setType(STTblWidth.AUTO);
        infoTableWidth.setW(BigInteger.valueOf(9072));

        //表格第一行
        XWPFTableRow reportProject = basicInfoTable.getRow(0);
        reportProject.getCell(0).setText("被举报项目/部门：");
        reportProject.addNewTableCell().setText(reportEntity.getReportProject() == null ? "" : reportEntity.getReportProject());

        XWPFTableRow supplementTitle = basicInfoTable.createRow();
        supplementTitle.getCell(0).setText("标题：");
        supplementTitle.getCell(1).setText(reportEntity.getSupplementTitle() == null ? "" : reportEntity.getSupplementTitle());

        //表格第二行
        XWPFTableRow supplementInformant = basicInfoTable.createRow();
        supplementInformant.getCell(0).setText("被举报人：");
        supplementInformant.getCell(1).setText(reportEntity.getSupplementInformant() == null ? "" : reportEntity.getSupplementInformant());
        //表格第三行
        XWPFTableRow reportCity = basicInfoTable.createRow();
        reportCity.getCell(0).setText("所在城市：");
        reportCity.getCell(1).setText(reportEntity.getReportCity() == null ? "" : reportEntity.getReportCity());
        //表格第四行
        XWPFTableRow reportTime = basicInfoTable.createRow();
        reportTime.getCell(0).setText("举报时间：");
        reportTime.getCell(1).setText(reportEntity.getReportTime() == null ? "" : reportEntity.getReportTime());

        XWPFTableRow reportIp = basicInfoTable.createRow();
        reportIp.getCell(0).setText("IP来源：");
        reportIp.getCell(1).setText(reportEntity.getReportIp() == null ? "" : reportEntity.getReportIp());
        XWPFTableRow ipCity = basicInfoTable.createRow();
        ipCity.getCell(0).setText("IP所属城市：");
        ipCity.getCell(1).setText(reportEntity.getIpCity() == null ? "" : reportEntity.getIpCity());
        String is_send_email = reportEntity.getIsSendEmail();
        if (StringUtils.isNotBlank(is_send_email)) {
            if (is_send_email.equals("1")) {
                is_send_email = "是";
            }
        } else {
            is_send_email = "否";
        }
        XWPFTableRow isSendEmail = basicInfoTable.createRow();
        isSendEmail.getCell(0).setText("是否已发送邮件：");
        isSendEmail.getCell(1).setText(is_send_email);

        //表格第五行
        XWPFTableRow reportContent = basicInfoTable.createRow();
        reportContent.getCell(0).setText("内容：");
        reportContent.getCell(1).setText(reportEntity.getReportContent() == null ? "" : reportEntity.getReportContent());

        //表格 附件
        //获取附件列表
        ReportAttachmentEntity reportAttachmentBean = new ReportAttachmentEntity();
        reportAttachmentBean.setReportId(reportEntity.getId());
        reportAttachmentBean.setAttachmentType("0");
        List<ReportAttachmentEntity> list = reportService.getAttachmentInfo(reportAttachmentBean);

        if (list != null && list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                XWPFTableRow reportAttachment = basicInfoTable.createRow();
                reportAttachment.getCell(0).setText("附件：");
                reportAttachment.getCell(1).setText(list.get(i).getAttachmentPath());
            }
        }
        if (list.size() > 1) {
            mergeCellsVertically(basicInfoTable, 0, 9, 9 + list.size() - 1);
        }
        this.setCellWidth(basicInfoTable);


        //两个表格之间加个换行
        XWPFParagraph newLine2 = document.createParagraph();
        XWPFRun paragraphRun2 = newLine2.createRun();
        paragraphRun2.setText("\r");

        //段落 第二段 举报人信息
        XWPFParagraph paragraphPeople = document.createParagraph();
        XWPFRun runPeople = paragraphPeople.createRun();
        runPeople.setText("举报人信息");
        runPeople.setColor("696969");
        runPeople.setFontSize(16);

        //换行
        XWPFParagraph newLine3 = document.createParagraph();
        XWPFRun paragraphRun3 = newLine3.createRun();
        paragraphRun3.setText("\r");

        //举报人信息表格
        XWPFTable peopleInfoTable = document.createTable();
        //去表格边框
        peopleInfoTable.getCTTbl().getTblPr().unsetTblBorders();
        //列宽自动分割
        CTTblWidth peopleInfoTableWidth = peopleInfoTable.getCTTbl().addNewTblPr().addNewTblW();
        peopleInfoTableWidth.setType(STTblWidth.AUTO);
        peopleInfoTableWidth.setW(BigInteger.valueOf(9072));

        //表格第一行
        XWPFTableRow reportPersonName = peopleInfoTable.getRow(0);
        reportPersonName.getCell(0).setText("姓名：");
        reportPersonName.addNewTableCell().setText(reportEntity.getReportPersonName() == null ? "" : reportEntity.getReportPersonName());
        //表格第二行
        XWPFTableRow reportPersonTel = peopleInfoTable.createRow();
        reportPersonTel.getCell(0).setText("手机号：");
        reportPersonTel.getCell(1).setText(reportEntity.getReportPersonTel() == null ? "" : reportEntity.getReportPersonTel());
        //表格第三行
        XWPFTableRow reportPersonEmail = peopleInfoTable.createRow();
        reportPersonEmail.getCell(0).setText("Email：");
        reportPersonEmail.getCell(1).setText(reportEntity.getReportPersonEmail() == null ? "" : reportEntity.getReportPersonEmail());
        //表格第四行
        XWPFTableRow reportSource = peopleInfoTable.createRow();
        reportSource.getCell(0).setText("举报途径：");
        String report_source = reportEntity.getReportSource();
        if (StringUtils.isNotBlank(report_source)) {
            if (report_source.equals("web")) {
                report_source = "官网";
            } else if (report_source.equals("oa")) {
                report_source = "融创OA系统";
            } else if (report_source.equals("supplier")) {
                report_source = "供应商系统";
            } else if (report_source.equals("wechat")) {
                report_source = "微信公众号";
            } else if (report_source.equals("sunacE")) {
                report_source = "融E";
            } else if (report_source.equals("offline")) {
                report_source = "线下扫码";
            } else if (report_source.equals("tel")) {
                report_source = "电话";
            } else if (report_source.equals("email")) {
                report_source = "邮件";
            } else if (report_source.equals("visit")) {
                report_source = "来访";
            }
        } else {
            report_source = "";
        }
        reportSource.getCell(1).setText(report_source);
        this.setCellWidth(peopleInfoTable);

        //两个表格之间加个换行
        XWPFParagraph newLine6 = document.createParagraph();
        XWPFRun paragraphRun6 = newLine6.createRun();
        paragraphRun6.setText("\r");

        if (!reportEntity.getReportStatus().equals("0")) {
            //段落 第三段 举报信息补充
            XWPFParagraph paragraphSupplement = document.createParagraph();
            XWPFRun runSupplement = paragraphSupplement.createRun();
            runSupplement.setText("举报信息补充");
            runSupplement.setColor("696969");
            runSupplement.setFontSize(16);

            //换行
            XWPFParagraph newLine4 = document.createParagraph();
            XWPFRun paragraphRun4 = newLine4.createRun();
            paragraphRun4.setText("\r");

            //举报信息补充表格
            XWPFTable supplementInfoTable = document.createTable();
            //去表格边框
            supplementInfoTable.getCTTbl().getTblPr().unsetTblBorders();
            //列宽自动分割
            CTTblWidth supplementInfoTableWidth = supplementInfoTable.getCTTbl().addNewTblPr().addNewTblW();
            supplementInfoTableWidth.setType(STTblWidth.AUTO);
            supplementInfoTableWidth.setW(BigInteger.valueOf(9072));

            //表格第一行

            //表格第四行
            XWPFTableRow supplementType = supplementInfoTable.createRow();
            supplementType.getCell(0).setText("业务类型：");
            String supplement_type = reportEntity.getSupplementType();


            if (StringUtils.isNotBlank(supplement_type)) {
                String[] types = supplement_type.split(",");
               String typeStr = "";
               /*  for (String value : types) {

                    if (value.equals("1")) {
                        value = "营销";
                    } else if (value.equals("2")) {
                        value = "工程";
                    } else if (value.equals("3")) {
                        value = "成本";
                    } else if (value.equals("4")) {
                        value = "招采";
                    } else if (value.equals("5")) {
                        value = "财务";
                    } else if (value.equals("6")) {
                        value = "法务";
                    } else if (value.equals("7")) {
                        value = "行政";
                    } else if (value.equals("8")) {
                        value = "人力";
                    } else if (value.equals("9")) {
                        value = "开发";
                    } else if (value.equals("10")) {
                        value = "研发";
                    } else if (value.equals("11")) {
                        value = "投资";
                    } else if (value.equals("12")) {
                        value = "其他";
                    } else if (value.equals("13")) {
                        value = "物业管理";
                    } else if (value.equals("14")) {
                        value = "文旅管理";
                    } else if (value.equals("15")) {
                        value = "商业";
                    }
                    typeStr = typeStr + value + ",";
                    supplement_type = typeStr.substring(0, typeStr.length() - 1);
                }*/
                for (String str:types) {
                    CtBbtcBusType ctBbtcBusType = CtBbtcBusTypeService.get(str);
                    if(ctBbtcBusType!=null){
                        typeStr = typeStr + ctBbtcBusType.getName() + ",";
                    }else{
                        typeStr = typeStr + "--";
                    }

                }
                supplement_type = typeStr.substring(0, typeStr.length() - 1);
            } else {
                supplement_type = "";
            }
            supplementType.addNewTableCell().setText(supplement_type);
            //表格第五行
            XWPFTableRow supplementArea = supplementInfoTable.createRow();
            supplementArea.getCell(0).setText("被举报区域：");
            String supplement_area = reportEntity.getSupplementArea();

          /*  if (StringUtils.isNotBlank(supplement_area)) {
                if (supplement_area.equals("North China")) {
                    supplement_area = "华北区域公司";
                } else if (supplement_area.equals("BeiJing")) {
                    supplement_area = "北京区域公司";
                } else if (supplement_area.equals("ShangHai")) {
                    supplement_area = "上海区域公司";
                } else if (supplement_area.equals("SouthWest")) {
                    supplement_area = "西南区域公司";
                } else if (supplement_area.equals("SouthEast")) {
                    supplement_area = "东南区域公司";
                } else if (supplement_area.equals("Central China")) {
                    supplement_area = "华中区域公司";
                } else if (supplement_area.equals("GuangShen")) {
                    supplement_area = "广深区域公司";
                } else if (supplement_area.equals("Hainan")) {
                    supplement_area = "海南区域公司";
                } else if (supplement_area.equals("Group")) {
                    supplement_area = "集团本部";
                }
            } else {
                supplement_area = "";
            }*/

            supplementArea.addNewTableCell().setText(supplement_area);
            //表格第六行
            XWPFTableRow supplementContent = supplementInfoTable.createRow();
            supplementContent.getCell(0).setText("内容：");
            supplementContent.addNewTableCell().setText(reportEntity.getSupplementContent() == null ? "" : reportEntity.getSupplementContent());
            //表格 附件行
            //获取附件列表
            ReportAttachmentEntity supplementAttachmentBean = new ReportAttachmentEntity();
            supplementAttachmentBean.setReportId(reportEntity.getId());
            supplementAttachmentBean.setAttachmentType("1");
            List<ReportAttachmentEntity> list1 = reportService.getAttachmentInfo(supplementAttachmentBean);

            if (list1 != null && list1.size() != 0) {
                for (int i = 0; i < list1.size(); i++) {
                    XWPFTableRow reportAttachment = supplementInfoTable.createRow();
                    reportAttachment.getCell(0).setText("附件：");
                    reportAttachment.createCell().setText(list1.get(i).getAttachmentPath());
                }
            }
            if (list1.size() > 1) {
                mergeCellsVertically(supplementInfoTable, 0, 4, 4 + list1.size() - 1);
            }
            this.setCellWidth(supplementInfoTable);
            supplementInfoTable.setCellMargins(0, 100, 0, 100);

            //两个表格之间加个换行
            XWPFParagraph newLine5 = document.createParagraph();
            XWPFRun paragraphRun5 = newLine5.createRun();
            paragraphRun5.setText("\r");
        }

        if (reportEntity.getReportStatus().equals("2")) {
            //段落 第四段 处理结果
            XWPFParagraph paragraphResult = document.createParagraph();
            XWPFRun runResult = paragraphResult.createRun();
            runResult.setText("处理结果");
            runResult.setColor("696969");
            runResult.setFontSize(16);

            //换行
            XWPFParagraph newLine7 = document.createParagraph();
            XWPFRun paragraphRun7 = newLine7.createRun();
            paragraphRun7.setText("\r");

            //举报信息补充表格
            XWPFTable resultInfoTable = document.createTable();
            //去表格边框
            resultInfoTable.getCTTbl().getTblPr().unsetTblBorders();
            //列宽自动分割
            CTTblWidth resultInfoTableWidth = resultInfoTable.getCTTbl().addNewTblPr().addNewTblW();
            resultInfoTableWidth.setType(STTblWidth.AUTO);
            resultInfoTableWidth.setW(BigInteger.valueOf(9072));

            //表格第一行
            XWPFTableRow dealPersonName = resultInfoTable.getRow(0);
            dealPersonName.getCell(0).setText("处理人：");
            dealPersonName.addNewTableCell().setText(reportEntity.getDealPersonName() == null ? "" : reportEntity.getDealPersonName());
            //表格 附件行
            //获取附件列表
            ReportAttachmentEntity dealAttachmentBean = new ReportAttachmentEntity();
            dealAttachmentBean.setReportId(reportEntity.getId());
            dealAttachmentBean.setAttachmentType("2");
            List<ReportAttachmentEntity> list2 = reportService.getAttachmentInfo(dealAttachmentBean);

            if (list2 != null && list2.size() != 0) {
                for (int i = 0; i < list2.size(); i++) {
                    XWPFTableRow reportAttachment = resultInfoTable.createRow();
                    reportAttachment.getCell(0).setText("附件：");
                    reportAttachment.getCell(1).setText(list2.get(i).getAttachmentPath());
                }
            }
            if (list2.size() > 1) {
                mergeCellsVertically(resultInfoTable, 0, 1, 1 + list2.size() - 1);
            }
            this.setCellWidth(resultInfoTable);
            resultInfoTable.setCellMargins(0, 100, 0, 100);

            //表格第三行
            XWPFTableRow dealResult = resultInfoTable.createRow();
            dealResult.getCell(0).setText("处理结论：");
            String deal_result = reportEntity.getDealResult();
            if (StringUtils.isNotBlank(deal_result)) {
                if (deal_result.equals("1")) {
                    deal_result = "移交客诉";
                } else if (deal_result.equals("2")) {
                    deal_result = "举报无效";
                } else if (deal_result.equals("3")) {
                    deal_result = "举报受理";
                } else if (deal_result.equals("4")) {
                    deal_result = "举报属实";
                } else if (deal_result.equals("5")) {
                    deal_result = "举报不实";
                } else if (deal_result.equals("6")) {
                    deal_result = "移交其他部门";
                }else if (dealResult.equals("7")) {
                    deal_result = "转为线索";
                }
            } else {
                deal_result = "";
            }
            dealResult.getCell(1).setText(deal_result);
            this.setCellWidth(basicInfoTable);
        }

        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);

        document.write(out);
        out.close();

        PrintWriter printWriter = response.getWriter();
        response.setContentType("application/json;charset=utf-8");
        printWriter.write(GConstants.FILE_PREFIX_URL + "pdf/" + reportEntity.getId() + ".docx");
        printWriter.close();

    }

    /**
     * @Description: 跨行合并
     */
    public void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            if (rowIndex == fromRow) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * @Description: 设置单元格宽度
     */
    public void setCellWidth(XWPFTable table) {
        List<XWPFTableRow> rowList = table.getRows();
        for (XWPFTableRow row : rowList) {
            List<XWPFTableCell> cellList = row.getTableCells();
            int i = 0;
            for (XWPFTableCell cell : cellList) {
                CTTcPr cellPr = cell.getCTTc().addNewTcPr();
                cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);
                int width = 2268;
                if (i == 1) {
                    width = 6804;
                }
                //设置宽度
                cellPr.addNewTcW().setW(BigInteger.valueOf(width));
                i++;
            }
        }
    }

}
