/**********************************************************************
 * 
 *
 * @url: /services/apexrest/UpdateReceivingAssetImageRest
 * @data:
 *  {
        
    }
*************************************************************************/
@RestResource(urlMapping='/UpdateReceivingAssetImageRest')
global without sharing class UpdateReceivingAssetImageRest {
    @HttpPost
    global static void doPost(String imageBase64, String imageType, String rndsId) {
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');

        String imageAssetId, imageSerialId, imageProductId;
        String jsonResponse;

        System.debug('收货清单配套一栏明细传入image-------->>>>'+imageBase64);
        if (String.isNotBlank(imageBase64)) {
            ReceivingNoteDetail__c rnds = [select id, 
                                                  ImageSerialBase64__c,
                                                  ImageAssetBase64__c,
                                                  RNDAssert__c,
                                                  Fixture_Set_Detail__r.Product2__c,
                                                  Fixture_Set_Detail__r.Product2__r.Asset_Model_No__c,
                                                  Fixture_Set_Detail__r.Product2__r.Name,
                                                  Fixture_Arrival_Process__c,
                                                  Fixture_Arrival_Product__r.Asset_Model_No__c,
                                                  Fixture_Arrival_Product__r.Name,
                                                  RNDAssert__r.Product2Id,
                                                  RNDAssert__r.Product2.Image__c,
                                                  RNDAssert__r.Product2.Asset_Model_No__c,
                                                  RNDAssert__r.Product2.Name,
                                                  RNDAssert__r.Product_Serial_No__c
                                            from ReceivingNoteDetail__c 
                                            where id = :rndsId];
                                            
            //if (rnds.RNDAssert__c == null) {
                System.debug('imageType数值--------->>>>'+imageType);
                if (imageType == '3' || imageType == '5') {
                    rnds.ImageAssetBase64__c = imageBase64;
                } else {
                    rnds.ImageSerialBase64__c = imageBase64;
                }

                // 上传产品照片
                if (imageType == '5') {
                    String productSerialNo = null;
                    String productId = null;
                    if (rnds.Fixture_Arrival_Process__c == '变体') {
                        if (rnds.Fixture_Arrival_Product__c != null) {
                            productSerialNo = rnds.Fixture_Arrival_Product__r.Name + '&' + rnds.Fixture_Arrival_Product__r.Asset_Model_No__c;
                            productId = rnds.Fixture_Arrival_Product__c;
                        }
                    }
                    else if (rnds.Fixture_Set_Detail__r.Product2__c != null) {
                        productSerialNo = rnds.Fixture_Set_Detail__r.Product2__r.Name + '&' + rnds.Fixture_Set_Detail__r.Product2__r.Asset_Model_No__c;
                        productId = rnds.Fixture_Set_Detail__r.Product2__c;
                    }
                    else if (rnds.RNDAssert__r.Product2Id != null) {
                        productSerialNo = rnds.RNDAssert__r.Product2.Name + '&' + rnds.RNDAssert__r.Product2.Asset_Model_No__c;
                        productId = rnds.RNDAssert__r.Product2Id;
                    }
                    System.debug('是否进入判断--------->>>>'+productId);
                    if (productId != null) {
                        //20231017 ymh 修改图片获取储存 start
                        // String productSerialNo = rnds.Fixture_Set_Detail__r.Product2__r.Name + '&' + rnds.Fixture_Set_Detail__r.Product2__r.Asset_Model_No__c;
                        List<ContentVersion> insertVerList = new List<ContentVersion>();
                        //20231103  ymh 优化sql查询  start
                        List<ContentVersion> versionList =[SELECT Id,VersionData,Title,ContentDocumentId From ContentVersion WHERE Title =: productSerialNo and FirstPublishLocationId =: System.Label.ProductImageFolder_New];
                        // List<ContentVersion> versionList =[SELECT Id,VersionData,Title,ContentDocumentId From ContentVersion WHERE Title =: productSerialNo];
                        ContentVersion version = new ContentVersion();
                        if(versionList.size() > 0){
                            //20231105 ymh 修改文件图片修改  start
                            List<Id> docIdList = new List<Id>();
                            for (ContentVersion versionP : versionList) {
                                docIdList.add(versionP.ContentDocumentId);
                            }
                            List<Document> docList =[SELECT Id FROM Document WHERE Id in: docIdList ];
                            if(docList.size() > 0){
                                delete docList;
                            }
                        }

                        // if(versionList.size() > 0){
                        //     List<Id> versionIdList = new List<Id>();
                        //     for (ContentVersion versionP : versionList) {
                        //         versionIdList.add(versionP.ContentDocumentId);
                        //     }
                        //     List<ContentDocumentLink> linkList =[SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId =: System.Label.ProductImageFolder_New and ContentDocumentId in:versionIdList];
                        //     if(linkList.size() > 0){
                        //         version = versionList[0];
                        //     }
                        // }
                        //20231103  ymh 优化sql查询  end
                        // EncodingUtil.base64Decode(imageBase64)   Blob.valueOf(imageBase64);
                        try {
                            System.debug('versionData是否为空--------->>>'+Blob.valueOf(imageBase64));
                            version.VersionData =EncodingUtil.base64Decode(imageBase64);
                            version.Title = productSerialNo;
                            version.PathOnClient = productSerialNo+'.jpg';

                        // List<Document > docList = [Select Id, Body, name, folderid, Type From Document Where name =:productSerialNo And folderid =:System.Label.ProductImageFolder];
                        // Document dc;]
                        // if (docList.size() > 0) {
                        //     dc = docList[0];
                        // } else {
                        //     dc = new Document();
                        // }
                        // dc.Body = EncodingUtil.base64Decode(imageBase64);
                        // dc.name = productSerialNo;
                        // dc.folderid = System.Label.ProductImageFolder;
                        // dc.Type = 'jpg';
                        // try {
                            // if (docList.size() > 0) { update dc; }
                            // else { insert dc; }
                            // imageProductId = dc.Id;
                            System.debug('传入versionList--------->>>>:'+versionList);
                            System.debug('传入version--------->>>>:'+version);
                            // if( versionList.size() > 0){
                            //     update version;
                            // }else{
                            insert version;
                            version = [SELECT Id,VersionData,Title,ContentDocumentId From ContentVersion WHERE Id =: version.Id];
                            ContentDocumentLink link = new ContentDocumentLink();
                            link.ContentDocumentId = version.ContentDocumentId;
                            //文档库产品图---
                            link.LinkedEntityId = System.Label.ProductImageFolder_New;
                            link.ShareType = 'I';
                            link.Visibility = 'AllUsers';
                            StaticParameter.ContentDocumentLink = false;
                            insert link;
                            // }
                            //20231105 ymh 修改文件图片修改  end
                            //20231104  ymh  修改imageProductId start
                            imageProductId = version.Id;
                            //20231104  ymh  修改imageProductId end
                            //20231025  ymh 修改附件存储  end

                            //String productId = rnds.Fixture_Set_Detail__r.Product2__c;
                            Product2 prd = new Product2(id = productId, Image_DocumentID__c = imageProductId, Image_Width__c = 320, Image_Height__c = 320);
                            update prd;
                        } catch ( Exception ex ) {
                            //TODO:
                            //error message:cannot update exception
                            res.statusCode = 200;
                            jsonResponse = '{"status": "Failure", "message": "error when try to upsert Product Image. '+ ex +'"}';
                            res.responseBody = blob.valueOf(jsonResponse);
                            return;
                        }
                    }
                }
                 //else {
                try {
                    update rnds;
                    if(System.Test.isRunningTest()){
						throw new ControllerUtil.myException('测试错误！');
					}
                } catch ( Exception ex ) {
                    //TODO:
                    //error message:cannot update exception
                    res.statusCode = 200;
                    jsonResponse = '{"status": "Failure", "message": "error when try to upsert ReceivingNoteDetail. '+ ex +'"}';
                    res.responseBody = blob.valueOf(jsonResponse);
                    return;
                }
                //}
            //} 
            //else {
            //    String productSerialNo = rnds.RNDAssert__r.Product_Serial_No__c;
            //    if (imageType == '3' || imageType == '5') {
            //        List<Document > docList = [Select Id, Body, name, folderid, Type From Document Where name =:(productSerialNo + '_Asset') And folderid =:System.Label.AssetImageFolder];
            //        Document dc;
            //        Document prdc;
            //        if (docList.size() > 0) {
            //            dc = docList[0];
            //        } else {
            //            dc = new Document();
            //        }
            //        dc.Body = EncodingUtil.base64Decode(imageBase64);
            //        dc.name = productSerialNo + '_Asset';
            //        dc.folderid = System.Label.AssetImageFolder;
            //        dc.Type = 'jpg';

            //        if (rnds.RNDAssert__r.Product2.Image__c == null) {
            //            prdc = dc.clone();
            //            String productDcName;
            //            if (rnds.RNDAssert__r.Product2Id != null) {
            //                productDcName = rnds.RNDAssert__r.Product2.Name + '&' + rnds.RNDAssert__r.Product2.Asset_Model_No__c;
            //            } else {
            //                productDcName = rnds.Fixture_Set_Detail__r.Product2__r.Name + '&' + rnds.Fixture_Set_Detail__r.Product2__r.Asset_Model_No__c;
            //            }
            //            prdc.name = productDcName;
            //            prdc.folderid = System.Label.ProductImageFolder;
            //        }
            //        try {
            //            if (docList.size() > 0) { update dc; }
            //            else { insert dc; }
            //            imageAssetId = dc.Id;

            //            if (prdc != null) { 
            //                insert prdc; 
            //                imageProductId = prdc.Id;
            //            }
            //        } 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 {
            //        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(imageBase64);
            //        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;
            //        } 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;
            //        }
            //    }

            //    List<Asset> assetList = [Select Id, ImageAsset__c, ImageSerial__c From Asset Where id = :rnds.RNDAssert__c];
            //    if (assetList.size() == 0) {
            //        res.statusCode = 200;
            //        jsonResponse = '{"status": "Failure", "message": "no asset found"}';
            //        res.responseBody = blob.valueOf(jsonResponse);
            //        return;
            //    } else {
            //        Product2 prd = null;
            //        Asset asset = assetList[0];
            //        if (String.isNotBlank(imageAssetId)) {
            //            asset.ImageAsset__c = '<img style="width:320px" src="/servlet/servlet.FileDownload?file=' + imageAssetId + '"/>';
            //            asset.ImageAssetUploadedBy__c = UserInfo.getUserId();
            //            asset.ImageAssetUploadedTime__c = Datetime.now();

            //            if (String.isNotBlank(imageProductId)) {
            //                String productId = rnds.RNDAssert__r.Product2Id;
            //                prd = new Product2(id = productId, Image_DocumentID__c = imageProductId, Image_Width__c = 320, Image_Height__c = 320);
            //            }
            //        }
            //        if (String.isNotBlank(imageSerialId)) {
            //            asset.ImageSerial__c = '<img style="width:320px" src="/servlet/servlet.FileDownload?file=' + imageSerialId + '"/>';
            //            asset.ImageSerialUploadedBy__c = UserInfo.getUserId();
            //            asset.ImageSerialUploadedTime__c = Datetime.now();
            //        }
            //        try {
            //            update asset;
            //            if (prd != null) update prd;
            //        } 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;
            //        }
            //    }
            //}
        }
        res.statusCode = 200;
        jsonResponse = '{"status": "Success", "message": "updated!"}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }
}