package com.ejweb.modules.report.web;

import com.ejweb.conf.GConstants;
import com.ejweb.core.utils.StringUtils;
import com.ejweb.modules.report.entity.CtBbtcBusCategory;
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.CtBbtcBusCategoryService;
import com.ejweb.modules.report.service.CtBbtcBusTypeService;
import com.ejweb.modules.report.service.ReportService;
import com.ejweb.modules.sys.entity.Dict;
import com.ejweb.modules.sys.entity.User;
import com.ejweb.modules.sys.service.DictService;
import com.ejweb.modules.sys.utils.UserUtils;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
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.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;

    @Autowired
    protected CtBbtcBusCategoryService ctBbtcBusCategoryService;

    @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)  {
        //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("\\","|");
//        }
        try {
        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 participant = basicInfoTable.createRow();
        participant.getCell(0).setText("参与人：");
        participant.getCell(1).setText(reportEntity.getParticipants() == null ? "" : reportEntity.getParticipants());
        //表格第四行 知情人
        XWPFTableRow insider = basicInfoTable.createRow();
        insider.getCell(0).setText("知情人：");
        insider.getCell(1).setText(reportEntity.getInsider() == null ? "" : reportEntity.getInsider());
        //表格第五行 发生时间
        XWPFTableRow reportDate = basicInfoTable.createRow();
        reportDate.getCell(0).setText("发生时间：");
        reportDate.getCell(1).setText(reportEntity.getReportDate() == null ? "" : reportEntity.getReportDate());
        //表格第六行 地点
        XWPFTableRow site = basicInfoTable.createRow();
        site.getCell(0).setText("地点：");
        site.getCell(1).setText(reportEntity.getSite() == null ? "" : reportEntity.getSite());
        //表格第七行 举报时间
        XWPFTableRow reportTime = basicInfoTable.createRow();
        reportTime.getCell(0).setText("举报时间：");
        reportTime.getCell(1).setText(reportEntity.getReportTime() == null ? "" : reportEntity.getReportTime());
        //表格第八行 所在城市
        XWPFTableRow reportCity = basicInfoTable.createRow();
        reportCity.getCell(0).setText("所在城市：");
        reportCity.getCell(1).setText(reportEntity.getReportCity() == null ? "" : reportEntity.getReportCity());
        //表格第九行 IP来源
        XWPFTableRow reportIp = basicInfoTable.createRow();
        reportIp.getCell(0).setText("IP来源：");
        reportIp.getCell(1).setText(reportEntity.getReportIp() == null ? "" : reportEntity.getReportIp());
        //表格第十行 IP所属城市
        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());
        //调查建议
        XWPFTableRow suggestion = basicInfoTable.createRow();
        suggestion.getCell(0).setText("调查建议：");
        suggestion.getCell(1).setText(reportEntity.getSuggestion() == null ? "" : reportEntity.getSuggestion());

        //表格 附件
        //获取附件列表
        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("姓名：");
        //表格第二行
        XWPFTableRow reportPersonTel = peopleInfoTable.createRow();
        reportPersonTel.getCell(0).setText("手机号：");
        //表格第三行
        XWPFTableRow reportPersonEmail = peopleInfoTable.createRow();
        reportPersonEmail.getCell(0).setText("Email：");
        //表格第四行
        XWPFTableRow qq = peopleInfoTable.createRow();
        qq.getCell(0).setText("QQ号：");
        //表格第五行
        XWPFTableRow weixin = peopleInfoTable.createRow();
        weixin.getCell(0).setText("微信号：");

        User user = UserUtils.getUser();
        String isAdmin = reportService.checkRole(user);
        /*如果移交后是本人  且不显示数据  则设置“”*/
        if(! isAdmin.equals("1") && ! isAdmin.equals("2")){
            if(user.getId().equals(reportEntity.getExchangeAfterUser()) && "2".equals(reportEntity.getIfClue())){
                reportPersonName.addNewTableCell().setText("");
                reportPersonTel.getCell(1).setText("");
                reportPersonEmail.getCell(1).setText("");
                qq.getCell(1).setText("");
                weixin.getCell(1).setText("");

            }else{
                reportPersonName.addNewTableCell().setText(reportEntity.getReportPersonName() == null ? "" : reportEntity.getReportPersonName());
                reportPersonTel.getCell(1).setText(reportEntity.getReportPersonTel() == null ? "" : reportEntity.getReportPersonTel());
                reportPersonEmail.getCell(1).setText(reportEntity.getReportPersonEmail() == null ? "" : reportEntity.getReportPersonEmail());
                qq.getCell(1).setText(reportEntity.getQq() == null ? "" : reportEntity.getQq());
                weixin.getCell(1).setText(reportEntity.getWeixin() == null ? "" : reportEntity.getWeixin());
            }
        }else{
            //系统  辅助 管理都能看见
            reportPersonName.addNewTableCell().setText(reportEntity.getReportPersonName() == null ? "" : reportEntity.getReportPersonName());
            reportPersonTel.getCell(1).setText(reportEntity.getReportPersonTel() == null ? "" : reportEntity.getReportPersonTel());
            reportPersonEmail.getCell(1).setText(reportEntity.getReportPersonEmail() == null ? "" : reportEntity.getReportPersonEmail());
            qq.getCell(1).setText(reportEntity.getQq() == null ? "" : reportEntity.getQq());
            weixin.getCell(1).setText(reportEntity.getWeixin() == null ? "" : reportEntity.getWeixin());
        }


        //表格第四行
        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 supplementGroup = supplementInfoTable.createRow();
            supplementGroup.getCell(0).setText("所属集团：");
            String supplementName = reportEntity.getSupplementGroup();
            supplementGroup.addNewTableCell().setText(supplementName == null ? "" : supplementName);
            //表格第二行
            XWPFTableRow supplementArea = supplementInfoTable.createRow();
            supplementArea.getCell(0).setText("被举报区域：");
            String supplement_area = reportEntity.getSupplementArea();
            supplementArea.addNewTableCell().setText(supplement_area == null ? "" : supplement_area);
            //表格第三行
            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 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 supplementCategory = supplementInfoTable.createRow();
            supplementCategory.getCell(0).setText("业务类别：");
            String category = reportEntity.getSupplementCategory();

            if (StringUtils.isNotBlank(category)) {
                String[] types = category.split(",");
                String typeStr = "";
                for (String str:types) {
                    CtBbtcBusCategory ctBbtcBusCategory = ctBbtcBusCategoryService.get(str);
                    if(ctBbtcBusCategory!=null){
                        typeStr = typeStr + ctBbtcBusCategory.getName() + ",";
                    }else{
                        typeStr = typeStr + "--";
                    }

                }
                category = typeStr.substring(0, typeStr.length() - 1);
            } else {
                category = "";
            }
            supplementCategory.addNewTableCell().setText(category == null ? "" : category);


            //表格第六行
            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();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @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++;
            }
        }
    }

}
