global without sharing class QISToETQWebService {
    public static List<ImgObj> ImgObjs = new List<ImgObj>();
    webservice static String sendToETQ(String iflog_Id,BatchIF_Log__c rowDataSFDC, List<String> repairIds,String statu){
        List<QIS_Report__c> temp = [select id,name,GeneratedPDFField__c,problem_detail_photo__c,Photo_1__c,Photo_2__c,Photo_3__c,Photo_4__c,Photo_5__c,Photo_6__c,Photo_7__c,Photo_8__c,
        Photo_OSH_1__c,Photo_OSH_2__c,Photo_OSH_3__c,Photo_OSH_4__c
        //zzm 20231213 DB202310077820 start
        ,Photo_OSH_5__c,Photo_OSH_6__c,Photo_OSH_7__c,Photo_OSH_8__c
        //zzm 20231213 DB202310077820 end
        from QIS_Report__c where GeneratedPDFField__c = null and id in :repairIds ];
        List<Repair__c> tempRe = [select id,name,GeneratedPDFField__c,ProblemDescription__c,ASReportedCodeAC__c,AE_DetermineResult__c,PAE_Determine__c,PAE_DetermineAC__c from Repair__c where GeneratedPDFField__c = null
         and id in :repairIds ];
        if(temp != null && temp.size() > 0){
            // try {
                // 需要生成pdf的字段
                List<String> apiNames = new List<String>();
                apiNames.add('problem_detail_photo__c');
                apiNames.add('Photo_1__c');
                apiNames.add('Photo_2__c');
                apiNames.add('Photo_3__c');
                apiNames.add('Photo_4__c');
                apiNames.add('Photo_5__c');
                apiNames.add('Photo_6__c');
                apiNames.add('Photo_7__c');
                apiNames.add('Photo_8__c');
                apiNames.add('Photo_OSH_1__c');
                apiNames.add('Photo_OSH_2__c');
                apiNames.add('Photo_OSH_3__c');
                apiNames.add('Photo_OSH_4__c');
                //zzm 20231213 DB202310077820 start
                apiNames.add('Photo_OSH_5__c');
                apiNames.add('Photo_OSH_6__c');
                apiNames.add('Photo_OSH_7__c');
                apiNames.add('Photo_OSH_8__c');
                //zzm 20231213 DB202310077820 end
                List<QIS_Report__c> updateQis = new List<QIS_Report__c>();
                // //20231027 ymh添加注释  lighting修改附件上传 start
                // List<Attachment> attachments = new List<Attachment>();
                List<ContentDocumentLink> linkList = new List<ContentDocumentLink>();
                List<ContentVersion> versionList = new List<ContentVersion>();
                PageReference pdfPage ;
                Map<String,String> res = new Map<String, String>();
                for(QIS_Report__c qis : temp){
                    for (String apiName : apiNames) {
                        String generatedFields =  qis.GeneratedPDFField__c;
                        if (checkFieldisGeneratedPDF(apiName,qis)) {
                            continue;
                        }
                        if (qis.get(apiName) == null) {
                            continue;
                        }
                        setImgSrcs(qis, apiName);
                        pdfPage = new PageReference('/apex/repairandqistopdf?api=qis&id='+qis.Id+'&field='+apiName);
                        Blob pdfBody;
                        if(Test.isRunningTest()) { 
                            pdfBody = blob.valueOf('Unit.Test');
                        } else {
                            pdfBody = pdfPage.getContentAsPDF();
                        }
                        // Attachment attach = new Attachment();
                        // attach.Body = pdfBody;
                        
                        ContentVersion cv = new ContentVersion();
                        cv.VersionData = pdfBody;
                        if ('problem_detail_photo__c'.equals(apiName)) {
                            // attach.Name =  substringApiName(qis.name) + '_Problem_Discription.pdf';
                            cv.Title = substringApiName(qis.name) + '_Problem_Discription.pdf';
                            cv.PathOnClient = '/'+substringApiName(qis.name) + '_Problem_Discription.pdf';
                        }else {
                            // attach.Name = substringApiName(qis.name) + '_' + 'Problem_' + apiName.substring(0,apiName.length()-3) + '.pdf';
                            cv.Title = substringApiName(qis.name) + '_' + 'Problem_' + apiName.substring(0,apiName.length()-3) + '.pdf';
                            cv.PathOnClient = '/'+substringApiName(qis.name) + '_' + 'Problem_' + apiName.substring(0,apiName.length()-3) + '.pdf';
                        }
                        // attach.ParentId = qis.id;
                        // insert cv;
                        
                        versionList.add(cv);
                        res.put(cv.Title, qis.Id);
                        if (generatedFields == null) {
                            qis.GeneratedPDFField__c = apiName;
                        }else {
                            qis.GeneratedPDFField__c += ',' + apiName;
                        }
                    }
                    updateQis.add(qis);
                }
                if (versionList.size()>0) {
                    insert versionList;
                }
                List<Id> idList = new List<Id>();
                for (ContentVersion newVersion : versionList) {
                    idList.add(newVersion.Id);
                }
                versionList = [select ContentDocumentId,Title from ContentVersion where Id in: idList];
                for (ContentVersion cVersion : versionList) {
                    ContentDocumentLink cdl = new ContentDocumentLink();
                    cdl.ContentDocumentId = cVersion.ContentDocumentId;
                    // cdl.LinkedEntityId = qis.id;
                    cdl.LinkedEntityId = res.get(cVersion.Title);
                    cdl.ShareType = 'I';
                    cdl.visibility = 'AllUsers';
                    linkList.add(cdl);
                }
                if (linkList.size()>0) {
                    insert linkList;
                }
                // //20231027 ymh添加注释  lighting修改附件上传 end
                update updateQis;
                // RepairAndQISToPDFController.generateAttachment(temp);
                NFM401Controller.callout(null, null, repairIds, statu);
            // }
            // catch (Exception e) {
            //     return '更新QIS报错:'+ e.getMessage();
            // }
            // Database.executeBatch(new QISToPDFBatch(iflog_Id, rowDataSFDC,repairIds,statu),50); //生成PDF
        }else{

            BatchIF_Log__c iflog = new BatchIF_Log__c();
            iflog.Type__c = 'sendToETQ';
            iflog.ErrorLog__c = '';
            iflog.Log__c = 'NFM401WebService start--';

            Repair__c updateRe = new Repair__c();
            updateRe.Id = tempRe[0].id;
            updateRe.INTERFACE_RECORD_ID__c = null; 
            updateRe.ETQ_UPLOAD_STATUS__c = null; 
            updateRe.ETQ_UPLOAD_MESSAGE__c = null; 
            updateRe.OSH_ConfirmationDate__c = Date.today(); 
            updateRe.OSH_Affirmant__c = UserInfo.getUserId(); 
            updateRe.AWS_Interface_Time__c = Datetime.now();
            updateRe.AsyncData__c = true; 
            //update by rentx 2021-03-23 start 需要先更新修理的信息再掉401接口 不然的话可能会出现 调用成功但是部分修理更新失败的情况 将更新修理的步骤提前 则当修理更新失败时 就不会往下执行401的接口了 
            // try{
                update updateRe;
                // Database.executeBatch(new RepairToPDFBatch(iflog_Id, rowDataSFDC,repairIds,statu)); //生成PDF
                // RepairAndQISToPDFController.generateAttachment(reList);
                PageReference pdfPage ;
            
                List<Repair__c> updateRpr = new List<Repair__c>();
                // //20231027 ymh添加注释  lighting修改附件上传 start
                // List<Attachment> attachments = new List<Attachment>();
                List<ContentDocumentLink> linkList = new List<ContentDocumentLink>();
                for(Repair__c re : tempRe){
                    String generatedFields = re.GeneratedPDFField__c;
                    if (checkFieldisGeneratedPDF('ProblemDescription__c',re)) {
                        continue;                
                    }
                    if (re.get('ProblemDescription__c') == null) {
                        continue;
                    }
                    setImgSrcs(re, 'ProblemDescription__c');            
        
                    pdfPage = new PageReference('/apex/repairandqistopdf?api=repair&id='+re.Id);
                    Blob pdfBody;
                    if(Test.isRunningTest()) { 
                        pdfBody = blob.valueOf('Unit.Test');
                    } else {
                        pdfBody = pdfPage.getContentAsPDF();
                    }
                    // Attachment attach = new Attachment();
                    // attach.Body = pdfBody;
                    // attach.Name = re.name + '_' + 'Problem_Discription.pdf';
                    // attach.ParentId = re.id;
                    ContentVersion cv = new ContentVersion();
                    cv.VersionData = pdfBody;
                    cv.Title = re.name + '_' + 'Problem_Discription.pdf';
                    cv.PathOnClient = '/'+re.name + '_' + 'Problem_Discription.pdf';
                    insert cv;
                    Id docId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id].ContentDocumentId;  
                    ContentDocumentLink cdl = new ContentDocumentLink();
                    cdl.ContentDocumentId = docId;
                    cdl.LinkedEntityId = re.id;
                    cdl.ShareType = 'I';
                    cdl.visibility = 'AllUsers';

                    // attachments.add(attach);
                    linkList.add(cdl);
                    re.GeneratedPDFField__c = 'ProblemDescription__c';
                    updateRpr.add(re);
                }
                insert linkList;
                // //20231027 ymh添加注释  lighting修改附件上传 end
                update updateRpr;
                
                Database.executeBatch(new RepairSendToETQBatch(null, null,repairIds,statu),1);
                
                iflog.Log__c += '\n修理:'+updateRe+' 更新成功';
                iflog.Log__c = '\nNFM401WebService end--';
                insert iflog;
            // }catch(Exception ex){
            //     iflog.ErrorLog__c += '修理:'+updateRe+' 更新失败,因为::'+ex.getMessage();
            //     iflog.Log__c = '\nNFM401WebService end--';
            //     // System.debug('更新修理报错::36'+updateRe);
            //     insert iflog;
            //     return '更新修理报错:'+ ex.getMessage();
            // }
        }
        return '发送成功!';
    }

    // 主要用于生成qis中问题描述对应的pdf文件名称(比较特殊)
    public static String substringApiName(String name){
        for(Integer i = 0; i < 2; i++){
            name = name.substring(name.indexOf('-')+1);
        }
        return name;
    }

    public static Boolean checkFieldisGeneratedPDF(String apiName,SObject obj){
        String generatedFields = (String) obj.get('GeneratedPDFField__c');
        if (generatedFields != null) {
            List<String> ele = generatedFields.split(',');
            return ele.contains(apiName);
        }
        return false;
    }
    public class ImgObj{
        public String imgSrc {get; set;}
        public String height {get; set;}
    }
    // 设置页面展示的数据
    public static void setImgSrcs(SObject obj,String apiName){
        ImgObjs = new List<ImgObj>();
        String content = (String) obj.get(apiName);
        ImgObj ImgObj = new ImgObj();
        ImgObj.imgSrc = content;
        ImgObj.height = '900px';
        ImgObjs.add(ImgObj);
        System.debug('ImgObjs++'+ImgObjs);
        
    }

}