package com.qmth.qrzk.web.controller;


import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.border.Border;
import com.itextpdf.layout.border.SolidBorder;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import com.qmth.qrzk.dao.repositories.ConfidentialRepo;
import com.qmth.qrzk.pdf.ItextDocumentModel;
import com.qmth.qrzk.pdf.ItextPdfHelper;
import com.qmth.qrzk.repository.service.query.ConfidentialParams;
import com.qmth.qrzk.repository.user.model.Confidential;
import com.qmth.qrzk.repository.utils.FileTool;
import com.qmth.qrzk.service.ConfidentialService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("confidential")
public class ConfidentialController extends BaseAjaxController {

    @Autowired
    private ConfidentialRepo confidentialRepo;


    @Autowired
    private ConfidentialService confidentialService;

    @RequestMapping("/page")
    @ResponseBody
    public Map<String, Object> page(@RequestBody final ConfidentialParams cp) {

        Specification<Confidential> specification = new Specification<Confidential>() {

            @Override
            public Predicate toPredicate(Root<Confidential> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder builder) {
                List<Predicate> predicates = new ArrayList();
                if (cp.getBatchId() != null) {
                    predicates.add(builder.equal(root.get("paperBatch").get("id"), cp.getBatchId()));
                }
                if (cp.getKeyword() != null && !cp.getKeyword().equals("")) {
                    predicates.add(builder.or(builder.like(root.get("province").<String>get("name"), "%" + cp.getKeyword() + "%"), builder.like(root.get("province").<String>get("address"), "%" + cp.getKeyword() + "%")));
                }
                return builder.and(predicates.toArray(new Predicate[0]));
            }
        };
  //      Sort sort =new Sort(Sort.Direction.ASC, "province.code");
        //多字段排序
        List<Order> listSort = new ArrayList<Order>();
        Order order1 = new Order(Direction.DESC,"paperBatch.id");
        Order order2 = new Order(Direction.ASC,"province.code");
        listSort.add(order1);
        listSort.add(order2);
        Sort sort =new Sort(listSort);
        
        PageRequest page = new PageRequest(cp.getPage() - 1, cp.getRows(),sort);
        Page<Confidential> pageInfo = confidentialRepo.findAll(specification, page);

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("rows", pageInfo.getContent());
        result.put("total", pageInfo.getTotalElements());
        return result;
    }

    @RequestMapping("/update")
    public void update(HttpServletResponse response, @RequestBody Confidential confidential) {
        confidentialService.updateById(confidential.getBagNum(), confidential.getId());
        JSONObject object = new JSONObject();
        object.put("result", "success");
        this.outJsonString(response, object.toString());

    }


    @RequestMapping(value = "/confidentialPdf", method = RequestMethod.GET)
    public void pdf(HttpServletRequest request, HttpServletResponse response, Integer batchId) {

        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        String fileName = webApplicationContext.getServletContext().getRealPath("/") + "temporary"
                + File.separator + UUID.randomUUID() + ".tmp";
        Document doc = null;
        try {
            ItextDocumentModel model = new ItextDocumentModel();
            File f = new File(fileName);
            f.getParentFile().mkdirs();
            f.createNewFile();
            doc = model.prepareDocument(f);

            PdfFont pdfFont = ItextPdfHelper.getPdfFontSTSong();
            doc.setFont(pdfFont);
            List<Confidential> list = confidentialRepo.findByBatchId(batchId);

            int index = 1;
            int page = 1;
            Table table = new Table(new float[]{0.8f, 2.5f, 1, 0.8f, 0.8f, 0.8f, 2.5f, 1, 0.8f}).setWidthPercent(100);
            head( doc);
            addHeader(table);
            int total=0;
            for (Confidential c : list) {

                for (Integer i = 0; i < c.getBagNum(); i++) {
                    if(total+i!=0&&(total+i)%15==0){
                        doc.add(table);
                        doc.add(new AreaBreak());
                        table = new Table(new float[]{0.8f, 2.5f, 1, 0.8f, 0.8f, 0.8f, 2.5f, 1, 0.8f}).setWidthPercent(100);
                        head( doc);
                        addHeader(table);
                    }
                    table.addCell(new Cell(1, 1).add(String.valueOf(index)).setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
//                    table.addCell(new Cell(1, 1).add(c.getProvince().getName()+c.getProvince().getAddress()).setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
//                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
                    table.addCell(new Cell(1, 1).add(c.getProvince().getUnit()).setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
                    table.addCell(new Cell(1, 1).add("").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
                    table.addCell(new Cell(1, 1).add("√").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
                    table.addCell(new Cell(1, 1).add("").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
                    table.addCell(new Cell(1, 1).add("").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
                    table.addCell(new Cell(1, 1).add("湖北省教育考试院").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
                    table.addCell(new Cell(1, 1).add("").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
                    table.addCell(new Cell(1, 1).add("").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
                    index++;
                }
                total+=c.getBagNum();
            }
            doc.add(table);
            foot(doc,total);
            ItextPdfHelper.closePdf(doc);
            FileTool.downLoad(response, fileName);
            f.delete();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }


    }

    private static void addHeader(Table table) {
        table.addCell(new Cell(2, 1).add("格数").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell(2, 1).add("收件单位名称及驻地").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell(2, 1).add("号码").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell(1, 3).add("件数").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell(2, 1).add("发件单位").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell(2, 1).add("机要通信编号").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell(2, 1).add("备注").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell(1, 1).add("绝").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell(1, 1).add("机").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell(1, 1).add("密").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
    }

    private void head(Document doc) {
        Paragraph p = new Paragraph("机要件交接单").setFontSize(20).setBold().setTextAlignment(TextAlignment.CENTER).setMarginTop(5);
        doc.add(p);
        p = new Paragraph("寄件单位：湖北省教育考试院").setFontSize(12).setBold().setTextAlignment(TextAlignment.LEFT).setMarginTop(10);
        doc.add(p);
        Table table = new Table(new float[]{1, 1});
        table.setWidthPercent(100).setBorder(Border.NO_BORDER);
        p = new Paragraph("发出日期：     年  月  日").setFontSize(12).setBold().setTextAlignment(TextAlignment.LEFT).setMarginTop(10);
        table.addCell(new Cell().add(p).setBorder(Border.NO_BORDER));
        p = new Paragraph("第    号    第" + doc.getPdfDocument().getNumberOfPages() + "页").setFontSize(12).setBold().setTextAlignment(TextAlignment.RIGHT).setMarginTop(10);
        table.addCell(new Cell().add(p).setBorder(Border.NO_BORDER));
        doc.add(table);
    }

    private void foot(Document doc, int total) {
        Table table = new Table(new float[]{1, 2, 1, 1, 1, 1, 2, 1, 1}).setWidthPercent(100);
        Table t = new Table(new float[]{1});
        t.setWidthPercent(100).setBorder(Border.NO_BORDER);
        t.addCell(new Cell().add("本页合计"+total+"件").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.LEFT).setBorder(Border.NO_BORDER).setBorderBottom(new SolidBorder(1)));
        t.addCell(new Cell().add("本号单共计"+doc.getPdfDocument().getNumberOfPages()+"页"+total+"件").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.LEFT).setBorder(Border.NO_BORDER).setBorderBottom(new SolidBorder(1)));
        t.addCell(new Cell().add("机要业务资费¥").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.LEFT).setBorder(Border.NO_BORDER));
        table.addCell(new Cell(1, 5).add(t).setPadding(0).setMargin(0));
        t = new Table(new float[]{1});
        t.setWidthPercent(100).setBorder(Border.NO_BORDER);
        t.addCell(new Cell().add("接收人").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.LEFT).setBorder(Border.NO_BORDER));
        t.addCell(new Cell().add("（章）").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.LEFT).setBorder(Border.NO_BORDER));
        t.addCell(new Cell().add("接收日期").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
                .setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER).setBorder(Border.NO_BORDER));
        table.addCell(new Cell(1, 4).add(t).setMargin(0));

//        doc.add(table.setMarginTop(20));
        doc.add(table);
        t = new Table(new float[]{1, 1});
        t.setWidthPercent(100).setBorder(Border.NO_BORDER);
        Paragraph p = new Paragraph("登记人：").setFontSize(12).setBold().setTextAlignment(TextAlignment.LEFT).setMarginTop(10);
        t.addCell(new Cell().add(p).setBorder(Border.NO_BORDER));
        p = new Paragraph("送件人：").setFontSize(12).setBold().setTextAlignment(TextAlignment.LEFT).setMarginTop(10);
        t.addCell(new Cell().add(p).setBorder(Border.NO_BORDER));
        doc.add(t);
    }
}
