@RestResource(urlMapping='/UpdateAssetImage/*')
global with sharing class UpdateAssetImageRest {
    @HttpPost
    global static void doPost(String imageAsset, String imageSerial, String productSerialNo, String repairId, String repairDate, String remarkText) {

        system.debug('UpdateAssetImageRest.start');
        System.debug('接口传递参数打印---------imageAsset--->>>'+imageAsset+'---imageSerial----->>>>'+imageSerial+'----productSerialNo---->>>>'+productSerialNo+'-----repairId---->>>>'+repairId+'----repairDate---->>>>'+repairDate+'----remarkText---->>>>'+remarkText);
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        
        String imageAssetId, imageSerialId;
        String jsonResponse;
        String linkdId = System.Label.AssetImageFolder_new; // ymh add 文档库链接
        
        if (String.isNotBlank(repairId) && String.isNotBlank(repairDate)) {
            List<Repair__c> repair = [Select Id, Repair_Returned_To_HP_Date__c From Repair__c Where Id= :repairId];
            // repair == null
            if (null == repair || repair.size() < 1) {
                res.statusCode = 200;
                jsonResponse = '{"status": "Failure", "message": "no repair found"}';
                res.responseBody = blob.valueOf(jsonResponse);
                return;
            } else {
                try {
                    repair[0].Repair_Returned_To_HP_Date__c = Date.parse(repairDate);
                
                    update repair[0];
                } catch ( Exception ex ) {
                    //TODO:
                    //error message:cannot update exception
                    res.statusCode = 200;
                    jsonResponse = '{"status": "Failure", "message": "error when try to update repair data. '+ ex +'"}';
                    res.responseBody = blob.valueOf(jsonResponse);
                    return;
                }
            }
        }
        //20231017 ymh 修改图片获取储存 start
        // List<Document > docList = [Select Id, Body, name, folderid, Type From Document Where name =:(productSerialNo + '_Asset') And folderid =:System.Label.AssetImageFolder];
            // Document dc;
            // if (docList.size() > 0) {
            //  dc = docList[0];
            // } else {
            //  dc = new Document();
            // }
            // dc.Body = EncodingUtil.base64Decode(imageAsset);
            // dc.name = productSerialNo + '_Asset';
            // dc.folderid = System.Label.AssetImageFolder;
            // dc.Type = 'jpg';
        
        System.debug('传入imageAsset--------->>>>:'+imageAsset);
        if (String.isNotBlank(imageAsset)) {
			System.debug('productSerialNo转Title--------->>>>:'+productSerialNo+'_Asset');
            List<ContentVersion> insertVerList = new List<ContentVersion>();
            //20231103  ymh  优化sql  satrt
            List<ContentVersion> versionListA =[SELECT Id,VersionData,Title,ContentDocumentId From ContentVersion WHERE Title =: (productSerialNo + '_Asset') and  FirstPublishLocationId =:linkdId];
            // List<ContentVersion> versionListA =[SELECT Id,VersionData,Title,ContentDocumentId From ContentVersion WHERE Title =: (productSerialNo + '_Asset') ];
            ContentVersion versionA = new ContentVersion();
            if(versionListA.size() > 0){
				//20231105  ymh  修改保有设备图片上传修改  start
                // versionA = versionListA[0];
				List<Id> docIdList = new List<Id>();
                for (ContentVersion versionAs : versionListA) {
                    docIdList.add(versionAs.ContentDocumentId);
                }
                List<Document> docList =[SELECT Id FROM Document WHERE Id in: docIdList];
                if(docList.size() > 0){
					delete docList;
                }
				
            }
            // if(versionListA.size() > 0){
            //     List<Id> versionIdList = new List<Id>();
            //     for (ContentVersion versionAs : versionListA) {
            //         versionIdList.add(versionAs.ContentDocumentId);
            //     }
            //     List<ContentDocumentLink> linkList =[SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId =: System.Label.AssetImageFolder_new and ContentDocumentId in:versionIdList];
            //     if(linkList.size() > 0){
            //      versionA = versionListA[0];
            //     }
            // }
            //20231103  ymh  优化sql  end
            versionA.VersionData = EncodingUtil.base64Decode(imageAsset);
            versionA.Title = productSerialNo + '_Asset';
            versionA.PathOnClient = productSerialNo + '_Asset'+'.jpg';

            
            try {
                // if (docList.size() > 0) { update dc; }
                // else { insert dc; }
                // imageAssetId = dc.Id;
                System.debug('versionList数据--------->>>>'+versionListA);
                System.debug('versionA数据--------->>>>'+versionA);
                // if( versionListA.size() > 0){
                //     update versionA;
                // }else{
				insert versionA;
				System.debug('versionA数据插入完成----yes--------->>>');
				versionA = [SELECT Id,VersionData,Title,ContentDocumentId From ContentVersion WHERE Id =: versionA.Id];
				ContentDocumentLink link = new ContentDocumentLink();
				link.ContentDocumentId = versionA.ContentDocumentId;
				link.LinkedEntityId = linkdId;
				link.ShareType = 'I';
				link.Visibility = 'AllUsers';
				StaticParameter.ContentDocumentLink = false;
				StaticParameter.ContentDocumentTrigger = false;
				System.debug('link数据插入准备----yes--------->>>');
				insert link;
                // }
                imageAssetId = versionA.Id;
				//20231105  ymh  修改保有设备图片上传修改  end

            } catch ( Exception ex ) {
                //TODO:
                //error message:cannot update exception
                res.statusCode = 200;
                jsonResponse = '{"status": "Failure", "message": "error when try to upsert Asset Doc. '+ ex +'"}';
                res.responseBody = blob.valueOf(jsonResponse);
                return;
            }
        } else {
            //no imageAsset
        }
        
        System.debug('传入imageSerial--------->>>>:'+imageSerial);
        if (String.isNotBlank(imageSerial)) {
			System.debug('productSerialNo转Title--------->>>>:'+productSerialNo+'_Serial');
            List<ContentVersion> insertVerList = new List<ContentVersion>();
            List<ContentVersion> versionListS =[SELECT Id,VersionData,Title,ContentDocumentId From ContentVersion WHERE Title =: (productSerialNo + '_Serial') and FirstPublishLocationId =:linkdId];
            ContentVersion versionS = new ContentVersion();
            if(versionListS.size() > 0){
                List<Id> docIdList = new List<Id>();
                for (ContentVersion versionSe : versionListS) {
                    docIdList.add(versionSe.ContentDocumentId);
                }
				List<Document> docList =[SELECT Id FROM Document WHERE Id in: docIdList];
				if(docList.size() > 0){
					delete docList;
                }
            }
            
            versionS.VersionData = EncodingUtil.base64Decode(imageSerial);
            versionS.Title = productSerialNo + '_Serial';
            versionS.PathOnClient = productSerialNo + '_Serial'+'.jpg';

            // List<Document > docList = [Select Id, Body, name, folderid, Type From Document Where name =:(productSerialNo + '_Serial') And folderid =:System.Label.AssetImageFolder];
            // Document dc;
            // if (docList.size() > 0) {
            //  dc = docList[0];
            // } else {
            //  dc = new Document();
            // }
            // dc.Body = EncodingUtil.base64Decode(imageSerial);
            // dc.name = productSerialNo + '_Serial';
            // dc.folderid = System.Label.AssetImageFolder;
            // dc.Type = 'jpg';
            try {
                // if (docList.size() > 0) { update dc; }
                // else { insert dc; }
                // imageSerialId = dc.Id;
                
                // if( versionListS.size() > 0){
                //     update versionS;
                // }else{
				insert versionS;
				System.debug('versionS数据插入完成----yes--------->>>');

				versionS = [SELECT Id,VersionData,Title,ContentDocumentId From ContentVersion WHERE Id =: versionS.Id];
				ContentDocumentLink link = new ContentDocumentLink();
				link.ContentDocumentId = versionS.ContentDocumentId;
				link.LinkedEntityId = linkdId;
				link.ShareType = 'I';
				link.Visibility = 'AllUsers';
				StaticParameter.ContentDocumentLink = false;
				StaticParameter.ContentDocumentTrigger = false;
				System.debug('link数据插入准备----yes--------->>>');
				insert link;
                // }
                imageSerialId = versionS.Id;
            } catch ( Exception ex ) {
                //TODO:
                //error message:cannot update exception
                res.statusCode = 200;
                jsonResponse = '{"status": "Failure", "message": "error when try to upsert Serial Doc. '+ ex +'"}';
                res.responseBody = blob.valueOf(jsonResponse);

                return;
            }
        } else {
            //no imageSerial
        }
        
        try {
            List<Asset> asset = [Select Id, ImageAsset__c, ImageSerial__c From Asset Where Product_Serial_No__c = :productSerialNo];
			
            if (asset.size() < 1) {
                res.statusCode = 200;
                jsonResponse = '{"status": "Failure", "message": "no asset found"}';
                res.responseBody = blob.valueOf(jsonResponse);
                return;
            } else {
                if (String.isNotBlank(imageAssetId)) {
                    // asset.ImageAsset__c = '<img style="width:320px" src="/servlet/servlet.FileDownload?file=' + imageAssetId + '"/>';
                    asset[0].ImageAsset__c = '<img style="width:320px" src="/sfc/servlet.shepherd/version/download/' + imageAssetId + '"/>';
                    asset[0].ImageAssetUploadedBy__c = UserInfo.getUserId();
                    asset[0].ImageAssetUploadedTime__c = Datetime.now();
                }
                if (String.isNotBlank(imageSerialId)) {
                    // asset.ImageSerial__c = '<img style="width:320px" src="/servlet/servlet.FileDownload?file=' + imageSerialId + '"/>';
                    asset[0].ImageSerial__c = '<img style="width:320px" src="/sfc/servlet.shepherd/version/download/' + imageSerialId + '"/>';
                    asset[0].ImageSerialUploadedBy__c = UserInfo.getUserId();
                    asset[0].ImageSerialUploadedTime__c = Datetime.now();
                }
        
                
                if (String.isNotBlank(remarkText)) {
                    asset[0].Remark__c = remarkText;
                    asset[0].RemarkFlg__c = true;
                }
                // try {
                    update asset[0];
                    res.statusCode = 200;
                    jsonResponse = '{"status": "Success", "message": {"assetId": "'+ asset[0].Id +'", "imgaId": "'+ imageAssetId +'", "imgsId": "'+ imageSerialId +'"}}';
                    res.responseBody = blob.valueOf(jsonResponse);

					if (System.Test.isRunningTest()) {
						throw new ControllerUtil.myException('测试错误！');
					}
                    return;
            // } catch ( Exception ex ) {
            //     //TODO:
            //     //error message:cannot update exception
            //     res.statusCode = 200;
            //     jsonResponse = '{"status": "Failure", "message": "error when try to update asset data. '+ ex +'"}';
            //     res.responseBody = blob.valueOf(jsonResponse);
            //     return;
            // }
            }
        } catch ( Exception ex ) {
            //TODO:
            //error message:cannot update exception
            res.statusCode = 200;
            jsonResponse = '{"status": "Failure", "message": "error when try to update asset data. '+ ex +'"}';
            res.responseBody = blob.valueOf(jsonResponse);
            return;
        }
        ////20231017 ymh 修改图片获取储存 end

        
    }
}