public with sharing class QuotesPDFController {
    //报价ID
    public String id {get; set;}
    //报价
    public Quotes__c quo {get; set;}
    //报价行项目
    public List<Quotes_item__c> qiList {get; set;}
    public List<lineDataInfo> lineList{get;set;}
    public List<lineDataInfo> lineList2{get;set;}
    //生成的PDF页数
    public Integer pageNum{get;set;}
    //不含税合计 合计
    public Decimal amount{get;set;}
    //税额 合计
    public Decimal taxAmt{get;set;}
    //总金额 合计
    public Decimal grossAmt{get;set;}
    public String conName{get;set;}
    
    // 20220222 PI改造 by Bright---start
    public string staticResource { get; private set; }
    public string contactStaticResource { get; private set; }
    // 20220222 PI改造 by Bright---end

    // 第一页不会侵入页脚信息的最大行数
    private Decimal firstCount = 50;
    // 第一页数据侵入页脚信息，第一页的最大行数
    private Decimal firstMaxCount = 60;
    // 从第二页开始不侵入页脚信息，单页最大行数
    private Decimal dataCount = 119;
    // 从第二页开始侵入页脚信息，单页最大行数
    private Decimal dataCountMax = 129;
    // 当前页面信息的行数
    private Integer count{get;set;}
    // 一行显示的字符数
    private Decimal ITEM_NAME_NUMBER_strNum = 10;
    // 一行显示的字符数
    private Decimal PART_NUMBERNew_strNum = 15;
    // 一行显示的字符数
    private Decimal DESCRIPTION_strNum = 40;
    //接收地址有回车，一行最大可以有汉字长度
    private Decimal RECEIVEDESCRIPTION_strNum = 21;

    public QuotesPDFController() {
        //获取报价ID
        id = System.currentPageReference().getParameters().get('id');
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Quotes__c'));// 20220222 PI改造 by Bright
		contactStaticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));// 20220222 PI改造 by Bright
    }

    /**
     * [init description]初始化方法
     */
    public void init(){
        pageNum = 0;
        //数据信息到42行 就会把页脚信息顶到下一页
        //firstCount = 40;
        //id不为空，查找对应报价和报价行项目
        if(id != null && id != ''){
            //查询报价 CONTACT_EMAIL__c(联系邮箱)，CONTACT_PHONE__c(联系电话)，BILL_TO__c(付款人)
            //SUBTOTAL__c
            //DISCOUNT__c
            //TAX__c
            //TOTAL__c
            quo = [SELECT id,ESTIMATE__c,DATE__c,EXPIRES__c,CURRENCY__c,TERMS__c,INCOTERM__c,PO__c,LEAD_TIME__c,CONTACT_EMAIL__c,CONTACT_PHONE__c,CONTACT_NAME__c,CONTACT_NAME__r.AWS_Data_Id__c ,BILL_TO__c,SHIP_TO__c,CUSTOMER_MESSAGE__c,SWOName__c,QuotesType__c,COMPANYName__c,SUBTOTAL__c,DISCOUNT__c,TAX__c,TOTAL__c,AWS_Data_Id__c  FROM Quotes__c WHERE Id = :id];
            List<Contact> conList = [select Id,Name from Contact where Id =: quo.CONTACT_NAME__c];
            if(conList!=null && conList.size()!=0){
                conName = conList[0].Name;
            }
            //查询报价行项目
            qiList = [SELECT id,PART_NUMBERNew__c,ITEM_NAME_NUMBER__c,QUANTITY__c,UPC_CODE__c,DESCRIPTION__c,RATE__c,AMOUNT__c,TAX_RATE__c,TAX_AMT__c,GROSS_AMT__c,DESCROPTION_NAME__c,ProductOTcode__c FROM Quotes_item__c where QUOTE__c = :id];
            /*for(Integer t = 0 ; t<13 ; t++){
                Quotes_item__c item = new Quotes_item__c();
                item.DESCRIPTION__c = 'wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww';
                qiList.add(item);
            }*/
            if(qiList!=null && qiList.size()!=0){
                lineList = new List<lineDataInfo>();
                lineList2 = new List<lineDataInfo>();
                Map<String,Decimal> oneDataRowNum = new Map<String,Decimal>();
                // 计算所有数据有回车换行情况，一条数据占用多行的行数。
                Decimal dataNum = 0;
                //不含税合计 合计
                amount = 0.00;
                //税额 合计
                taxAmt = 0;
                //总金额 合计
                grossAmt = 0;
                for(Integer i = 0; i<qiList.size() ; i++){

                    String str = qiList[i].ProductOTcode__c;
                    //a，b，c 一条数据中一个字段占用页面行数，页面中有三个字段较长，需要计算每条数据占页面的行数，确定数据是否会侵入页脚信息中
                    Decimal a = 0;
                    Decimal b = 0;
                    Decimal c = 0;
                    System.debug(qiList[i].DESCROPTION_NAME__c);
                    if (qiList[i].DESCROPTION_NAME__c == 'Payment Info' && qiList[i].DESCRIPTION__c != null) {
                        // 计算出来的占用页面行数加一  每条数据后面要加一行空白行
                        a = getLine(RECEIVEDESCRIPTION_strNum,qiList[i].DESCRIPTION__c)+1;
                    }else if(qiList[i].DESCROPTION_NAME__c == 'DESCRIPTION' && qiList[i].DESCRIPTION__c!=null){
                        // 计算出来的占用页面行数加一  每条数据后面要加一行空白行
                        str = qiList[i].DESCRIPTION__c;
                        a = ((str.length()!=0) ? math.ceil(str.length()/RECEIVEDESCRIPTION_strNum) : 1)+1;
                    }else{
                        // 计算出来的占用页面行数加一  每条数据后面要加一行空白行
                        a = (str!=null && str.length()!=0 ? math.ceil(str.length()/ITEM_NAME_NUMBER_strNum) : 1)+1;
                        // 计算出来的占用页面行数加一  每条数据后面要加一行空白行
                        str = qiList[i].PART_NUMBERNew__c;
                        b = (str!=null && str.length()!=0 ? math.ceil(str.length()/PART_NUMBERNew_strNum) : 1)+1;
                        // 计算出来的占用页面行数加一  每条数据后面要加一行空白行
                        str = qiList[i].DESCRIPTION__c;
                        c = (str!=null && str.length()!=0 ? math.ceil(str.length()/DESCRIPTION_strNum) : 1)+1;
                    }
                    //比较一条数据中单个字段所占页面行数，取最大值
                    if(a>=b && a>=c){
                        dataNum += a;
                        oneDataRowNum.put(qiList[i].Id, a);
                    }else if(b>=a && b>=c){
                        dataNum += b;
                        oneDataRowNum.put(qiList[i].Id, b);
                    }else if(c>=a && c>=b){
                        dataNum += c;
                        oneDataRowNum.put(qiList[i].Id, c);
                    }
                    if(qiList[i].DESCROPTION_NAME__c != 'DESCRIPTION' && qiList[i].DESCROPTION_NAME__c != 'Payment Info'){
                        amount = amount + (qiList[i].AMOUNT__c != null ? qiList[i].AMOUNT__c : 0.00);
                        taxAmt = taxAmt + (qiList[i].TAX_AMT__c != null ? qiList[i].TAX_AMT__c : 0.00);
                        qiList[i].GROSS_AMT__c = (qiList[i].AMOUNT__c != null ? qiList[i].AMOUNT__c : 0.00) + (qiList[i].TAX_AMT__c != null ? qiList[i].TAX_AMT__c : 0.00);
                        grossAmt = grossAmt + (qiList[i].GROSS_AMT__c != null ? qiList[i].GROSS_AMT__c : 0.00);
                    }
                }
                //加上最后一行合计
                dataNum = dataNum+3;
                // 存放放在PDF页面最后的付款信息 Payment Info
                List<Quotes_item__c> buyInfo = new List<Quotes_item__c>();
                // 存放放在最后的备注 DESCRIPTION 信息
                List<Quotes_item__c> descriptionList = new List<Quotes_item__c>();
                //构建最后一行合计行
                Quotes_item__c lastTotal = new Quotes_item__c();
                lastTotal.DESCRIPTION__c = 'Subtotal for SWO Number: '+(quo.SWOName__c!=null?quo.SWOName__c:'');
                lastTotal.AMOUNT__c = amount;
                lastTotal.TAX_AMT__c = taxAmt;
                lastTotal.GROSS_AMT__c = grossAmt;
                System.debug('firstCount'+firstCount);
                System.debug('firstMaxCount'+firstMaxCount);
                System.debug('dataNum'+dataNum);
                if(firstCount>=dataNum){
                    // 数据没有侵入页脚信息
                    for(Quotes_item__c it : qiList){
                        if(it.DESCROPTION_NAME__c == 'Payment Info'){
                            buyInfo.add(it);
                            continue;
                        }else if(it.DESCROPTION_NAME__c == 'DESCRIPTION'){
                            descriptionList.add(it);
                            continue;
                        }else{
                            lineList.add(new lineDataInfo(it));
                            lineList.add(new lineDataInfo());
                        }
                    }
                    //最后添加合计行收款信息
                    addHead(lineList,buyInfo,lastTotal,descriptionList);

                    Decimal a = firstCount-dataNum;
                    for(Integer i = 0 ; i<a-1 ; i++){
                        lineList.add(new lineDataInfo());
                    }
                }else if(firstCount<dataNum && dataNum<firstMaxCount){
                    // 数据侵入页脚信息，还没有到下一页
                    for(Quotes_item__c it : qiList){
                        if(it.DESCROPTION_NAME__c == 'Payment Info'){
                            buyInfo.add(it);
                            continue;
                        }else if(it.DESCROPTION_NAME__c == 'DESCRIPTION'){
                            descriptionList.add(it);
                            continue;
                        }else{
                            lineList.add(new lineDataInfo(it));
                            lineList.add(new lineDataInfo());
                        }
                    }
                    //最后添加合计行收款信息
                     addHead(lineList,buyInfo,lastTotal,descriptionList);
                    // a 需要补空白行把第一页撑满
                    Decimal a = firstMaxCount-dataNum;
                    for(Integer i = 0 ; i<a-1 ; i++){
                        lineList.add(new lineDataInfo());
                    }
                }else if(firstMaxCount<dataNum){
                    pageNum = 2;
                    //数据侵入到第二页
                    //onePageNow 当前第一页累计填充行数
                    Decimal onePageNow = 0;
                    //dataIndex 第一页当前填充数据的数据下标，第二页从此下标开始填充数据
                    Integer dataIndex = 0;
                    for(Quotes_item__c item : qiList){
                        dataIndex ++;
                        //这条数据是收款信息，最后添加
                        if(item.DESCROPTION_NAME__c == 'Payment Info'){
                            buyInfo.add(item);
                            continue;
                        }
                        if(item.DESCROPTION_NAME__c == 'DESCRIPTION'){
                            descriptionList.add(item);
                            continue;
                        }
                        //第一页填充这条数据后占用行数，需要加上最后一行的合计行
                        onePageNow += (oneDataRowNum.get(item.Id)+1);

                        if(onePageNow > firstMaxCount){
                            //a 第一页需要补满添加的空白行条数
                            Decimal a = firstMaxCount - (onePageNow - oneDataRowNum.get(item.Id));
                            for(Integer i=0 ; i<a ; i++){
                                lineList.add(new lineDataInfo());
                            }
                            break;
                        }
                        if(item.DESCROPTION_NAME__c == 'DESCRIPTION'){
                            /*setItem(lineList,item.DESCRIPTION__c);
                            lineList.add(new lineDataInfo());*/
                        }else{
                            lineList.add(new lineDataInfo(item));
                            lineList.add(new lineDataInfo());
                        }
                    }
                    for(Integer i = dataIndex ; i<qiList.size() ; i++){
                        if(qiList[i].DESCROPTION_NAME__c == 'Payment Info'){
                            buyInfo.add(qiList[i]);
                            continue;
                        }else if(qiList[i].DESCROPTION_NAME__c == 'DESCRIPTION'){
                            descriptionList.add(qiList[i]);
                            continue;
                        }else{
                            lineList2.add(new lineDataInfo(qiList[i]));
                            lineList2.add(new lineDataInfo());
                        }
                    }
                    addHead(lineList,buyInfo,lastTotal,descriptionList);
                }
            }
        }else{
            //报价为空添加空的报价和报价行项目
            quo = new Quotes__c();
            qiList = new List<Quotes_item__c>();
        }
    }
    /**
     * [save description]保存方法
     */
    public void save(){

    }
    // 加入最后的合计信息和收款信息
    public void addHead(List<lineDataInfo> lineData,List<Quotes_item__c> buyInfo,Quotes_item__c lastLine,List<Quotes_item__c> descriptionList){
        if(lineData!=null && lineData.size()!=0){
           /* if(lastLine!=null){
                lineData.add(new lineDataInfo(lastLine));
                lineData.add(new lineDataInfo());
            }*/
            if(buyInfo!=null&&buyInfo.size()!=0){
                for(Quotes_item__c item : buyInfo){
                    setItem(lineData,item.DESCRIPTION__c);
                    lineData.add(new lineDataInfo());
                }
            }
            if(descriptionList != null && descriptionList.size()!=0){
                for(Quotes_item__c item : descriptionList){
                    lineData.add(new lineDataInfo(item.DESCRIPTION__c));
                    lineData.add(new lineDataInfo());
                }
            }
        }
    }

    //传入一个数字 和一个字符串，计算每一行有该数字个字符，字符串分几行
    public Decimal getLine(Decimal num,String str){
        System.debug('getLine:'+str);
        if(String.isNotBlank(str)){
            if(str.indexOf('；')!=-1){
                str = str.replaceAll('；',';');
            }
            Decimal lineNum = 0;
            Integer a = str.indexOf(';');
            if(a!=-1){
                String[] str_list = str.split(';');
                for(String str_son:str_list){
                    lineNum += math.ceil(str_son.length()/num);
                }
            }else{
                lineNum += math.ceil(str.length()/num);
            }
            return lineNum;
        }
        return 1;
    }

    public void setItem(List<lineDataInfo> dataList,String str){
        
        if(String.isNotBlank(str)){
            System.debug('str:'+str);
            if(str.indexOf('；')!=-1){
                str = str.replaceAll('；',';');
            }
            String[] strList = str.split(';');
            System.debug('strList:'+strList);
            if(strList!=null && strList.size()!=0){
               for(String s:strList){
                    System.debug('s:'+s);
                    dataList.add(new lineDataInfo(s));
                } 
            }
        }
    }

    public class lineDataInfo{
        public String description{get;set;}
        public String productName{get;set;}
        public Quotes_item__c qi{get;set;}

        public lineDataInfo(){
            description = '空白行';
            qi = new Quotes_item__c();
        }
        public lineDataInfo(Quotes_item__c in_qi){
            qi = in_qi;
            if (String.isNotBlank(in_qi.ProductOTcode__c)) {
                /*productName = in_qi.ProductOTcode__c.startsWith('00000000000')?in_qi.ProductOTcode__c.substring(12,in_qi.ProductOTcode__c.length):in_qi.ProductOTcode__c;*/
                if(in_qi.ProductOTcode__c.startsWith('00000000000')){
                    productName = String.valueOf(in_qi.ProductOTcode__c).substring(11,String.valueOf(in_qi.ProductOTcode__c).length());
                }else{
                    productName = in_qi.ProductOTcode__c;
                }
            }else{
                productName = 'Service Quote Subtotal';
            }
            description = in_qi.DESCRIPTION__c;
        }
        public lineDataInfo(String in_des){
            description = in_des;
            qi = new Quotes_item__c();
        }
    }
}