public without sharing class eSignHospitalPageController {
   //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,
            agencyConfirmResult__c,
            agencyGoodStatus__c,
            HPConfirmResult__c,
            HPGoodStatus__c 
            ,
            CaseNumber__c
            FROM eSignFormLineItem__c
            where eSignForm__r.DNNameNo0__c =: DNName
            order by CaseNumber__c asc
            ];
        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,
             Hospital_Name__c,account_Name__c,agencySignUpDate__c
             //CHAN-BWCBL8 精琢技术 wql 20201225 start 
             ,HPSignUpStatus__c,HPReject__c,HPDenyReason__c,HPRejectDate__c 
             //CHAN-BWCBL8 精琢技术 wql 20201225 end 
                //GoodDetails__c, weight__c,
                FROM eSignForm__c
                where DNNameNo0__c =: DNName];
        eSignWrapper eSignWrapper = new eSignWrapper();
        eSignWrapper.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.eSignFormLineItems =eSignFormLineItems;
        eSignWrapper.eSignForm = loadeSignForm(eSignForm,'医院收货',eSignForm.ID);
        return eSignWrapper;
    }
        

    @AuraEnabled
    public static saveeSignFormEntryResult saveeSignFormEntry(
        list<eSignFormLineItem__c> eSignFormLineItems, eSignForm__c eSignForm
        , string entryType, boolean IsSubmit,boolean IsHPSubmit,boolean IsHPScan,Date agencyScanDayBack,
        Date agencySignUpDateBack,Date agencyConfirmDateBack,String HPWorkflowEmailBack){
            saveeSignFormEntryResult tempResult = new saveeSignFormEntryResult();
        try{
            eSignFormEntry__c tempeSignFormEntry = new eSignFormEntry__c();
            tempeSignFormEntry.Name = eSignForm.Name + '-' + entryType;
            tempeSignFormEntry.entryType__c = entryType;
            // tempeSignFormEntry.IsSubmit__c = IsSubmit;
            tempeSignFormEntry.IsHPScan__c = IsHPScan;
            tempeSignFormEntry.IsHPSubmit__c = IsHPSubmit;
            tempeSignFormEntry.eSignForm__c = eSignForm.ID;

            List<eSignFormEntry__c> lastESignFormEntryList = [select id,agencyScanDayBack__c,agencySignUpDateBack__c,agencyConfirmDateBack__c,
            HPScanDayBack__c,HPSignUpDateBack__c,entryType__c,AgencyWorkflowEmailBack__c,HPWorkflowEmailBack__c,agencyAutoSignUpStatus__c,agencyReject__c,HPReject__c,IsAgencyScan__c,IsHPScan__c,IsHandled__c,IsSubmit__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.agencyConfirmDateBack__c = lastESignFormEntryList[0].agencyConfirmDateBack__c;
                //经销商邮箱
                tempeSignFormEntry.AgencyWorkflowEmailBack__c = lastESignFormEntryList[0].AgencyWorkflowEmailBack__c;
                //医院扫描日
                tempeSignFormEntry.HPScanDayBack__c =  lastESignFormEntryList[0].HPScanDayBack__c;
                //医院签收日
                tempeSignFormEntry.HPSignUpDateBack__c =  lastESignFormEntryList[0].HPSignUpDateBack__c;
                //如果上一条经销商已处理，但是签收单被驳回了，那么医院签收的中间表就不应该有这两个经销商的勾
                //其它情况都应该带着
                if(lastESignFormEntryList[0].IsHandled__c && lastESignFormEntryList[0].agencyAutoSignUpStatus__c == '不批准'){
                    tempeSignFormEntry.IsSubmit__c = false;
                    tempeSignFormEntry.IsAgencyScan__c = false;
                }else{
                    tempeSignFormEntry.IsSubmit__c = lastESignFormEntryList[0].IsSubmit__c;
                    tempeSignFormEntry.IsAgencyScan__c = lastESignFormEntryList[0].IsAgencyScan__c;
                }

                
            }
                //医院扫描日
                tempeSignFormEntry.HPScanDayBack__c =  Date.today();
                //医院邮箱
                tempeSignFormEntry.HPWorkflowEmailBack__c = HPWorkflowEmailBack;
                //医院签收日
                if(IsHPSubmit){
                    tempeSignFormEntry.HPSignUpDateBack__c =  Date.today();
                }

            
            

            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.HPGoodStatus__c =  tempeSignFormLineItem.HPGoodStatus__c;
                //更新之前的经销商的操作流程信息 货物情况(经销商)、处理意见(经销商)、确认结果(经销商)
                tempeSignFormLineItemEntry.agencyGoodStatus__c = tempeSignFormLineItem.agencyGoodStatus__c;
                tempeSignFormLineItemEntry.agencyConfirmResult__c = tempeSignFormLineItem.agencyConfirmResult__c;
                //如果医院货物情况为完好，默认赋值为同意
                if(tempeSignFormLineItem.HPGoodStatus__c == '完好'){
                    tempeSignFormLineItemEntry.HPConfirmResult__c = '同意';
                }
                eSignFormLineItemEntryList.add(tempeSignFormLineItemEntry);
            }
            if(eSignFormLineItemEntryList.size() > 0 ){
                insert eSignFormLineItemEntryList;
            }
            tempResult.isSuccess = true;
            tempResult.result = tempeSignFormEntry.id;
        }catch(Exception e){
            tempResult.result = e.getMessage();
        }
        
        return tempResult;
    }

    public static List<eSignFormLineItem__c> loadeSignFormEntry(
        List<eSignFormLineItem__c> eSignFormLineItems, string entryType, string eSignFormID ){
        list<eSignFormEntry__c> tempeSignFormEntryList =
            [select id
                from eSignFormEntry__c
                where eSignForm__c = :eSignFormID
                // and  entryType__c =: entryType
                order by createddate desc limit 1
            ];
        if( tempeSignFormEntryList.size() == 0){
            for( eSignFormLineItem__c tempEsignItem: eSignFormLineItems){
                
                if(tempEsignItem.HPGoodStatus__c == null){
                    tempEsignItem.HPGoodStatus__c = '完好';
                }
            }
            return eSignFormLineItems;
        }
        list<eSignFormLineItemEntry__c> eSignFormLineItemEntryList =
         [select id ,GoodStatus__c,HPGoodStatus__c,eSignFormLineItem__c,HPConfirmResult__c,agencyGoodStatus__c,agencyConfirmResult__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.agencyGoodStatus__c =  tempESignEntryItem.agencyGoodStatus__c;
            tempEsignItem.agencyConfirmResult__c =tempESignEntryItem.agencyConfirmResult__c;
            //如果经销商货物情况为完好，默认赋值为同意
            // tempEsignItem.CaseNumber__c = tempESignEntryItem.CaseNumber__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,HPWorkflowEmailBack__c
                from eSignFormEntry__c
                where eSignForm__c = :eSignFormID
                and  entryType__c =: entryType
                order by createddate desc limit 1
            ];
        if( tempeSignFormEntryList.size() > 0){
            eSignForm.HPWorkflowEmail__c= tempeSignFormEntryList[0].HPWorkflowEmailBack__c;
        }

        return eSignForm;
    }
    public class saveeSignFormEntryResult{
        @AuraEnabled
        public Boolean isSuccess;
        @AuraEnabled
        public string result;
        public saveeSignFormEntryResult(){
            isSuccess = false;
            result = '';
        }
    }
    public class eSignWrapper{
        @AuraEnabled
        public List<eSignFormLineItem__c> eSignFormLineItems;

        @AuraEnabled
        public eSignForm__c eSignForm;
        public eSignWrapper(){
            eSignFormLineItems = new List<eSignFormLineItem__c>();
            eSignForm = new eSignForm__c();
        }

    }
    //文件上传
    @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');
        // 20231103   Lightning文件修改 Start
        // 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.LinkedEntityId = parentId;
        link.ContentDocumentId = version.ContentDocumentId;
        link.ShareType = 'I';
        link.Visibility = 'AllUsers';
        insert link;
 
        return link.ContentDocumentId;
        // 20231103   Lightning文件修改 End
    }
 
    private static void appendToFile(Id fileId, String base64Data) {
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
        // 20231103   Lightning文件修改 Start
        // Attachment a = [
        //     SELECT Id, Body
        //     FROM Attachment
        //     WHERE Id =: fileId
        // ];
        ContentVersion verison = [select Id,VersionData from ContentVersion where ContentDocumentId =: fileId];
 
        // String existingBody = EncodingUtil.base64Encode(a.Body);
        String existingBody = EncodingUtil.base64Encode(verison.VersionData);
 
        verison.VersionData = EncodingUtil.base64Decode(existingBody + base64Data);
 
        update verison;
        // 20231103   Lightning文件修改 End
    }
    
    //文件删除功能  精琢技术 thh 2021-09-26 start
    @AuraEnabled
    public static void deleteChunk(Id AttachmentId) {
        // 20231103   Lightning文件修改 Start
        // Attachment attachment = new Attachment();
        // attachment.id = AttachmentId;

        // delete attachment;
        ContentDocument con =  new ContentDocument();
        con.Id = AttachmentId;
        delete con;
        // 20231103   Lightning文件修改 End
    }
    //文件删除功能  精琢技术 thh 2021-09-26 end

    //获取AWS信息 zhj 2023-01-03 start
    @AuraEnabled
    public static ControllerResponse getAWS(String objectName){
        ControllerResponse res = new ControllerResponse();
        try{
            res.Data = JSON.serialize(PIHelper.getPIIntegrationInfo(objectName));
            res.IsSuccess = true;
        }catch(Exception e){
            res.IsSuccess = false;
            res.Message = e.getMessage();
        }
        return res;
    }
    //获取AWS信息 zhj 2023-01-03 end

    //AWS改造文件上传 deloitte zhj 2023-01-03 start
    @AuraEnabled
    public static Id saveFile(String fileName,String key,String transId,String parentId){
        FileAddress__c file = new FileAddress__c();
        PIHelper.PIIntegration pI=PIHelper.getPIIntegrationInfo('Document');
        // 去除filename里得“&” bysushanhu 20220414
        fileName = fileName.remove('&');
        file.DownloadLink__c =pI.undeleteUrl+key+'&fileName='+fileName;
        file.FileName__c =fileName;
        file.ViewLink__c =pI.queryUrl+key;
        file.ParentRecordId__c =parentId;
        file.AWS_File_Key__c = key;
        insert file;
        return file.Id;
    }
    //AWS改造文件上传 deloitte zhj 2023-01-03 end

    //获取上传文件 deloitte zhj 2023-01-03 start
    public static List<FileAddress__c> getFileds(String parentId){
        // SWAG-C9S9P6 2022-05-25 ssm start
        // 文件地址里增加招标项目专用字段（信息Id、项目阶段、更新日期）
        if(String.isNotBlank(parentId)){
            return [SELECT Id,ParentRecordId__c, FileName__c,DownloadLink__c,FileAddress__c.ViewLink__c,AWS_File_Key__c  //deloitte zhj 预览/下载 加token 2022/12/01
                    // SWAG-C9S9P6 新增字段 start
                    , InfoId__c, InfoType__c, subInfoType__c, UpdateDate__c 
                    // SWAG-C9S9P6 新增字段 end
                    FROM FileAddress__c where ParentRecordId__c=:parentId order by createddate desc];
        }
        return [SELECT Id, ParentRecordId__c,FileName__c,DownloadLink__c,FileAddress__c.ViewLink__c,AWS_File_Key__c  //deloitte zhj 预览/下载 加token 2022/12/01
                // SWAG-C9S9P6 新增字段 start
                , InfoId__c, InfoType__c, subInfoType__c, UpdateDate__c 
                // SWAG-C9S9P6 新增字段 end
                FROM FileAddress__c order by createddate desc limit 100];
        // SWAG-C9S9P6 2022-05-25 ssm end
    }
    //获取上传文件 deloitte zhj 2023-01-03 end

    //AWS文件删除功能  deloitte zhj 2022-01-03 start
    @AuraEnabled
    public static String deleteFile(String fileId){
        System.debug('fileId = ' + fileId);
        List<FileAddress__c> fList = [select id,AWS_File_Key__c from FileAddress__c where id =:fileId];
        String awsKey = '';
        if(fList != null && fList.size() > 0){
            awsKey = fList[0].AWS_File_Key__c;
            delete fList;
        }
        return awsKey;
    }
    //AWS文件删除功能  deloitte zhj 2022-01-03 end
}