public without sharing class  eSignAgencyPageController { 
    //Get Account Records
    @AuraEnabled
    public static eSignWrapper geteSigns(String DNName){
        // 最多只显示200条明细数据
        //签收单明细
        List<eSignFormLineItem__c> eSignFormLineItems =
            [SELECT Id, OTCode__c, Name,
            Asset_Model_No__c ,
            productName__c,
            Count_Text__c,
            GoodStatus__c,
            agencyGoodStatus__c
            ,
            HPGoodStatus__c
            ,
            CaseNumber__c
            ,
            isBlockButton__c
           
            FROM eSignFormLineItem__c
            where eSignForm__r.DNNameNo0__c =: DNName
            order by CaseNumber__c asc
            ];
        // System.debug('签收单明细：'+eSignFormLineItems);
        //签收单
        eSignForm__c eSignForm  =
            [SELECT Id, Name, supplier__c,
             supplierNo__c, ContractNO__c, shippingUnit__c,
             shippingAddress__c, DNNameNo0__c, contactName__c,
             contactNumber__c, DeliveryDate__c, endUserName__c,
             totalNumber__c, transportMode__c, totalWeight__c,
             //CHAN-BWCBL8 精琢技术 wql 20201225 start
              agencyAcceptResult__c,agencyReject__c,denyReason__c,agencyAutoSignUpStatus__c,
             //CHAN-BWCBL8 精琢技术 wql 20201225 end
              //GoodDetails__c, weight__c,
             //最后更新的录入表和录入表的是否提交IsSubmit__c
             finalUpadteFrom__c,finalUpadteFrom__r.IsSubmit__c
                FROM eSignForm__c
                where DNNameNo0__c =: DNName];
        // System.debug('签收单：'+eSignForm);

        
        List<eSignFormEntry__c> eSignFormEntryList  =
            [SELECT Id, Name, supplier__c,
             supplierNo__c, ContractNO__c, shippingUnit__c,
             shippingAddress__c, DNNameNo0__c, contactName__c,
             contactNumber__c, DeliveryDate__c, endUserName__c,
             totalNumber__c, transportMode__c, totalWeight__c,
             agencyScanDayBack__c,agencySignUpDateBack__c,agencyConfirmDateBack__c,
             // GoodDetails__c, weight__c,
             IsSubmit__c,agencyAcceptResult__c
                FROM eSignFormEntry__c
                where DNNameNo0__c =: DNName
                order by createddate desc
                ];

        //返回该签收单是否有已打勾的录入表
        Boolean isSubmit;
        if(eSignFormEntryList.size() > 0){
            if(eSignFormEntryList[0].IsSubmit__c){
                isSubmit = true;
            }else{
                isSubmit = false;
            }
        }else{
                isSubmit = false;
        }
        

        eSignFormLineItems =loadeSignFormEntry(eSignFormLineItems, eSignForm.ID );

        List<Decimal> caseList = new List<Decimal>();
        //存放 id，签收单明细
        Map<String,eSignFormLineItem__c> eSignFormLineItemMap = new Map<String,eSignFormLineItem__c>();
        //定义一个变量 去判断箱号是否相同
        Decimal str ;
        for(eSignFormLineItem__c efli : eSignFormLineItems){
            
            if(str==null){
                str = efli.CaseNumber__c;
                caseList.add(efli.CaseNumber__c);
                eSignFormLineItemMap.put(efli.id,efli);
            }else{
                if(!caseList.contains(efli.CaseNumber__c)){
                    caseList.add(efli.CaseNumber__c);
                    eSignFormLineItemMap.put(efli.id,efli);
                }
            }
            

        }
        //外层遍历所有的
        for(eSignFormLineItem__c eflitem : eSignFormLineItems){
            //eSignFormLineItemMap是需要显示的
            if(eSignFormLineItemMap.containsKey(eflitem.id)){
                eflitem.isBlockButton__c = 'block';
            }else{
                eflitem.isBlockButton__c = 'none';
            }
            
        }

        eSignWrapper eSignWrapper = new eSignWrapper(isSubmit);
        //匹配对应的签收单明细
        eSignWrapper.eSignFormLineItems =eSignFormLineItems;
        //签收单
        eSignWrapper.eSignForm = loadeSignForm(eSignForm,'经销商收货',eSignForm.ID);
        eSignWrapper.isSubmit =isSubmit;
        return eSignWrapper;
    }


    @AuraEnabled
    public static saveeSignFormEntryResult saveeSignFormEntry(
        list<eSignFormLineItem__c> eSignFormLineItems, eSignForm__c eSignForm
        , string entryType, boolean IsSubmit,boolean IsAgencyScan,String AgencyWorkflowEmailBack){
            saveeSignFormEntryResult tempResult = new saveeSignFormEntryResult();
        try{
            eSignFormEntry__c tempeSignFormEntry = new eSignFormEntry__c();

            List<eSignFormEntry__c> lastESignFormEntryList = [select id,agencyScanDayBack__c,agencySignUpDateBack__c,agencyConfirmDateBack__c,
            HPScanDayBack__c,HPSignUpDateBack__c,IsSubmit__c,IsHPSubmit__c,AgencyWorkflowEmailBack__c,HPWorkflowEmailBack__c,AgencyWorkflowEmail__c,HPWorkflowEmail__c,HPSignUpStatus__c,agencyReject__c,HPReject__c,IsAgencyScan__c,IsHPScan__c,IsHandled__c   
                from eSignFormEntry__c
                where eSignForm__c = :eSignForm.ID
                order by createddate desc limit 1];
            if(lastESignFormEntryList.size()>0){

                //经销商扫描日
                tempeSignFormEntry.agencyScanDayBack__c = lastESignFormEntryList[0].agencyScanDayBack__c;
                //经销商签收日
                tempeSignFormEntry.agencySignUpDateBack__c = lastESignFormEntryList[0].agencySignUpDateBack__c;

                //医院扫描日
                tempeSignFormEntry.HPScanDayBack__c = lastESignFormEntryList[0].HPScanDayBack__c;
                //医院签收日
                tempeSignFormEntry.HPSignUpDateBack__c = lastESignFormEntryList[0].HPSignUpDateBack__c;
                //经销商是否提交
                tempeSignFormEntry.IsSubmit__c = lastESignFormEntryList[0].IsSubmit__c;
                //医院是否提交
                tempeSignFormEntry.IsHPSubmit__c = lastESignFormEntryList[0].IsHPSubmit__c;
                //增加扫描标识，batch取消驳回勾选 2020/12/30 wql start
                //经销商是否扫描
                tempeSignFormEntry.IsAgencyScan__c = lastESignFormEntryList[0].IsAgencyScan__c;
                //医院是否扫描
                tempeSignFormEntry.IsHPScan__c = lastESignFormEntryList[0].IsHPScan__c;
                //增加扫描标识，batch取消驳回勾选 2020/12/30 wql end
                
                //经销商邮箱
                tempeSignFormEntry.AgencyWorkflowEmailBack__c = lastESignFormEntryList[0].AgencyWorkflowEmail__c;
                //医院邮箱
                tempeSignFormEntry.HPWorkflowEmailBack__c = lastESignFormEntryList[0].HPWorkflowEmailBack__c;

                
                //如果上一条医院已处理，但是签收单被驳回了，那么经销商签收的中间表就不应该有这两个医院的勾
                //其它情况都应该带着
                if(lastESignFormEntryList[0].IsHandled__c && lastESignFormEntryList[0].HPSignUpStatus__c == '不批准'){
                    tempeSignFormEntry.IsHPSubmit__c = false;
                    tempeSignFormEntry.IsHPScan__c = false;
                }else{
                    tempeSignFormEntry.IsHPSubmit__c = lastESignFormEntryList[0].IsHPSubmit__c;
                    tempeSignFormEntry.IsHPScan__c = lastESignFormEntryList[0].IsHPScan__c;
                }
            }

            //名称
            tempeSignFormEntry.Name = eSignForm.Name + '-' + entryType;
            //类型
            tempeSignFormEntry.entryType__c = entryType;
            //经销商是否提交
            tempeSignFormEntry.IsSubmit__c = IsSubmit;
            //经销商是否扫描
            tempeSignFormEntry.IsAgencyScan__c = IsAgencyScan;
            //签收单
            tempeSignFormEntry.eSignForm__c = eSignForm.ID;
            
            //经销商扫描日
            tempeSignFormEntry.agencyScanDayBack__c = Date.today();
            if(IsSubmit){
            tempeSignFormEntry.agencySignUpDateBack__c =  Date.today();
            }
            //经销商签收日
            //经销商邮箱
            tempeSignFormEntry.AgencyWorkflowEmailBack__c = AgencyWorkflowEmailBack;
            insert tempeSignFormEntry;
            list<eSignFormLineItemEntry__c> eSignFormLineItemEntryList =
                new list<eSignFormLineItemEntry__c>();
            for(eSignFormLineItem__c tempeSignFormLineItem : eSignFormLineItems){
                eSignFormLineItemEntry__c tempeSignFormLineItemEntry =
                    new eSignFormLineItemEntry__c();
                tempeSignFormLineItemEntry.eSignFormEntry__c =  tempeSignFormEntry.id;
                tempeSignFormLineItemEntry.Name =  tempeSignFormLineItem.Name;
                tempeSignFormLineItemEntry.eSignFormLineItem__c =  tempeSignFormLineItem.id;
                tempeSignFormLineItemEntry.agencyGoodStatus__c =  tempeSignFormLineItem.agencyGoodStatus__c;
                tempeSignFormLineItemEntry.HPGoodStatus__c = tempeSignFormLineItem.HPGoodStatus__c;
                //如果经销商货物情况为完好，默认赋值为同意
                if(tempeSignFormLineItem.agencyGoodStatus__c == '完好' ){
                    tempeSignFormLineItemEntry.agencyConfirmResult__c = '同意';
                }
                eSignFormLineItemEntryList.add(tempeSignFormLineItemEntry);
            }
            if(eSignFormLineItemEntryList.size() > 0 ){
                insert eSignFormLineItemEntryList;
            }
            tempResult.isSuccess = true;
            tempResult.result = tempeSignFormEntry.id;
            if(IsSubmit){
                List<eSignFormEntry__c> backHomeList = [SELECT Id,DNNameNo0__c,agencyDNSignUpStatus__c,HPDNSignUpStatus__c,agencySignUpDate__c 
                FROM eSignFormEntry__c
                where id =: tempeSignFormEntry.id
                order by createddate desc];
                tempResult.agencyDNSignUpStatus =backHomeList[0].agencyDNSignUpStatus__c;
                tempResult.HPDNSignUpStatus =backHomeList[0].HPDNSignUpStatus__c;
                tempResult.agencySubmit = backHomeList[0].agencySignUpDate__c;
                tempResult.DNNameSpare =backHomeList[0].DNNameNo0__c;
            }
            
        }catch(Exception e){
            tempResult.result = e.getMessage();
        }

        return tempResult;
    }
    public static List<eSignFormLineItem__c> loadeSignFormEntry(
        List<eSignFormLineItem__c> eSignFormLineItems, string eSignFormID ){
        list<eSignFormEntry__c> tempeSignFormEntryList =
            [select id
                from eSignFormEntry__c
                where eSignForm__c = :eSignFormID
                order by createddate desc limit 1
            ];
        if( tempeSignFormEntryList.size() == 0){
            for( eSignFormLineItem__c tempEsignItem: eSignFormLineItems){
                //设置默认值
                if(tempEsignItem.agencyGoodStatus__c == null){
                    tempEsignItem.agencyGoodStatus__c = '完好';
                }
                //设置默认值
                if(tempEsignItem.HPGoodStatus__c == null){
                    tempEsignItem.HPGoodStatus__c = '完好';
                }

            }
            return eSignFormLineItems;
        }
        list<eSignFormLineItemEntry__c> eSignFormLineItemEntryList =
         [select id ,HPGoodStatus__c,agencyGoodStatus__c,
         eSignFormLineItem__c,CaseNumber__c 
            from eSignFormLineItemEntry__c
            where eSignFormEntry__c =: tempeSignFormEntryList[0].id
         ];
        map<ID, eSignFormLineItemEntry__c> eSignFormLineItemEntryMap =
        new map<ID, eSignFormLineItemEntry__c>();
        for( eSignFormLineItemEntry__c tempESignEntryItem : eSignFormLineItemEntryList){
            eSignFormLineItemEntryMap.put(tempESignEntryItem.eSignFormLineItem__c, tempESignEntryItem);
        }
        for( eSignFormLineItem__c tempEsignItem: eSignFormLineItems){
            eSignFormLineItemEntry__c tempESignEntryItem =
                eSignFormLineItemEntryMap.get(tempEsignItem.id);
            //设置默认值
            // tempEsignItem.CaseNumber__c = tempESignEntryItem.CaseNumber__c;
            if(tempESignEntryItem.agencyGoodStatus__c != null){
            tempEsignItem.agencyGoodStatus__c = tempESignEntryItem.agencyGoodStatus__c;
            }else{
                tempEsignItem.agencyGoodStatus__c = '完好';
            }
            if(tempESignEntryItem.HPGoodStatus__c != null){
            tempEsignItem.HPGoodStatus__c = tempESignEntryItem.HPGoodStatus__c;
            }else{
                tempEsignItem.HPGoodStatus__c = '完好';
            }
        }

        return eSignFormLineItems;
    }
    //获取上一次的录入表 主要为了获取邮箱
    public static eSignForm__c loadESignForm(eSignForm__c eSignForm,string entryType,string eSignFormID ){
        list<eSignFormEntry__c> tempeSignFormEntryList =
            [select id,AgencyWorkflowEmailBack__c
                from eSignFormEntry__c
                where eSignForm__c = :eSignFormID
                and  entryType__c =: entryType
                order by createddate desc limit 1
            ];
        if( tempeSignFormEntryList.size() > 0){
            eSignForm.AgencyWorkflowEmail__c= tempeSignFormEntryList[0].AgencyWorkflowEmailBack__c;
        }

        return eSignForm;
    }
    public class saveeSignFormEntryResult{
        @AuraEnabled
        public Boolean isSuccess;
        @AuraEnabled
        public string result;

        //经销商状态
        @AuraEnabled
        public string agencyDNSignUpStatus;
        //医院状态
        @AuraEnabled
        public string HPDNSignUpStatus;
        //是否提交
        @AuraEnabled
        public Date agencySubmit;
        //备用DN号
        @AuraEnabled
        public string DNNameSpare;

        public saveeSignFormEntryResult(){
            isSuccess = false;
            result = '';
            agencyDNSignUpStatus ='';
            HPDNSignUpStatus = '';
            agencySubmit = null;
            DNNameSpare = '';
        }
    }
    public class eSignWrapper{
        @AuraEnabled
        public List<eSignFormLineItem__c> eSignFormLineItems;

        @AuraEnabled
        public eSignForm__c eSignForm;
        @AuraEnabled
        public Boolean isSubmit;


        public eSignWrapper(Boolean isSubmit){
            //当没有中间表的时候，返回签收单信息
            eSignFormLineItems = new List<eSignFormLineItem__c>();
            eSignForm = new eSignForm__c();
            isSubmit = isSubmit;

        }

    }
    //文件上传
    @AuraEnabled
    public static Id saveChunk(Id parentId, String fileName, String base64Data, String contentType, String fileId) {
        // check if fileId id ''(Always blank in first chunk), then call the saveTheFile method,
        //  which is save the check data and return the attachemnt Id after insert, 
        //  next time (in else) we are call the appentTOFile() method
        //   for update the attachment with reamins chunks   
        if (fileId == '') {
            fileId = saveTheFile(parentId, fileName, base64Data, contentType);
        } else {
            appendToFile(fileId, base64Data);
        }
 
        return Id.valueOf(fileId);
    }
 
    public static Id saveTheFile(Id parentId, String fileName, String base64Data, String contentType) {
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
 
        // Attachment oAttachment = new Attachment();
        // oAttachment.parentId = parentId;
 
        // oAttachment.Body = EncodingUtil.base64Decode(base64Data);
        // oAttachment.Name = fileName;
        // oAttachment.ContentType = contentType;
 
        // insert oAttachment;
        ContentVersion version = new ContentVersion();
        version.Title = fileName;
        version.VersionData = EncodingUtil.base64Decode(base64Data);
        version.ContentLocation = 's';
        version.PathOnClient = fileName + '.' +contentType;
        insert version;
        version = [select ContentDocumentId from ContentVersion where Id =: version.Id limit 1];
        ContentDocumentLink link = new ContentDocumentLink();
        link.ContentDocumentId = version.ContentDocumentId;
        link.LinkedEntityId = parentId;
        link.ShareType = 'I';
        link.Visibility = 'AllUsers';
        insert link;

        return link.ContentDocumentId;
    }
 
    private static void appendToFile(Id fileId, String base64Data) {
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
 
        // Attachment a = [
        //     SELECT Id, Body
        //     FROM Attachment
        //     WHERE Id =: fileId
        // ];
        ContentVersion version = [select Id,VersionData from ContentVersion where ContentDocumentId =: fileId];
 
        // String existingBody = EncodingUtil.base64Encode(a.Body);
        String existingBody = EncodingUtil.base64Encode(version.VersionData);
 
        // a.Body = EncodingUtil.base64Decode(existingBody + base64Data);
        version.VersionData = EncodingUtil.base64Decode(existingBody + base64Data);
 
        update version;
    }

    //文件删除功能  精琢技术 thh 2021-09-26 start
    @AuraEnabled
    public static void deleteChunk(Id AttachmentId) {
        // Attachment attachment = new Attachment();
        // attachment.id = AttachmentId;
        ContentDocument con = new ContentDocument();
        con.Id = AttachmentId;
        delete con;
        // delete attachment;
    }
    //文件删除功能  精琢技术 thh 2021-09-26 end
}