@RestResource(urlMapping = '/NFM008/*')
global with sharing class NFM008Rest  {
    public static boolean isRunning = false;
    // Integer batchsize = 200;  考量する必要がないと思います。
    global class InstallationInformationRest {
        public InstallationInformation InstallationInformation;
    }

    global class InstallationInformation {
        public NFMUtil.Monitoring Monitoring;
        public InstallationInfo[] InstallationInfo;
    }
    global class InstallationInfo {
        public InstallationInfoH InstallationInfoH;
        public InstallationInfoI[] InstallationInfoI;
    }
    global class InstallationInfoH {
        public String InquiryNo;
        // 电子签收单 start
        public string DeliveryNote;
        // 电子签收单 end
        public String InstallationDateH;               // 受信しない
        public String PostingDate;
        public String CompanyCode;
        public String DepartmentCode;
        public String PurposeOfAdvice;
        public String EntryDate;
    }
    global class InstallationInfoI {
        public String MaterialNo;
        public Double Quantity;                        // 受信しない
        public String SerialNo;
        public String InstallationDateI;
        public String ReturnExchangeReplenishMark;     // 返品区分、1の場合、レコード削除
        public String SLMark;
        public String GuaranteePeriod;
        public String GuaranteeType;
        public String Location;
        public String PurposeOfAdvice;
        public String ProvistonPeriod;  // 计提年限
    }

    @HttpPost
    global static void execute() {

        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        InstallationInformationRest ges = (InstallationInformationRest) JSON.deserializeStrict(strData, InstallationInformationRest.class);

        if (ges == null ) {
            return;
        }

        NFMUtil.Monitoring Monitoring = ges.InstallationInformation.Monitoring;
        if (Monitoring == null) {
            return;
        }

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM008', ges.InstallationInformation.InstallationInfo);
        if (String.isBlank(rowData.Log__c) == false) {
            executefuture(rowData.Id);
        }

        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
        String jsonResponse = '{"status": "Success", "Message":""}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }

    @future
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }
    global static void main(String rowData_Id) {
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
        String logstr = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'NFM008';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<InstallationInfo> installationInfoList = (List<InstallationInfo>) JSON.deserialize(rowDataStr, List<InstallationInfo>.class);
        if (installationInfoList == null || installationInfoList.size() == 0) {
            return;
        }

        isRunning = true;

        Savepoint sp = Database.setSavepoint();
        try {
            // 更新対応配列とMapなどをセット
            List<String> managementCodeList = new List<String>();
            List<String> productCodeList = new List<String>();
            List<String> productSerialNoList = new List<String>();
            for (InstallationInfo InstallationInfo : installationInfoList) {
                InstallationInfoH InstallationInfoH = InstallationInfo.InstallationInfoH;
                if (InstallationInfoH == null) {
                    continue;
                }
                if (InstallationInfo.InstallationInfoI == null || InstallationInfo.InstallationInfoI.size() == 0) {
                    continue;
                }
                // InstallationInfoH より、病院と診療科の管理コード
                InstallationInfoH.CompanyCode = NFMUtil.trimLeft(InstallationInfoH.CompanyCode, '0');
                InstallationInfoH.DepartmentCode = NFMUtil.trimLeft(InstallationInfoH.DepartmentCode, '0');
                if (InstallationInfoH.CompanyCode == null || InstallationInfoH.CompanyCode  == '' ||
                        InstallationInfoH.DepartmentCode == null || InstallationInfoH.DepartmentCode == ''
                   ) {
                    // 病院と診療科の管理コードがない場合、処理と飛ばす
                    continue;
                }
                managementCodeList.add(InstallationInfoH.CompanyCode);
                managementCodeList.add(InstallationInfoH.DepartmentCode);
                for (InstallationInfoI InstallationInfoI : InstallationInfo.InstallationInfoI) {
                    if (InstallationInfoI.MaterialNo == null || InstallationInfoI.MaterialNo == '' ||
                            InstallationInfoI.SerialNo == null || InstallationInfoI.SerialNo == ''
                       ) {
                        // 商品コードがない場合、処理と飛ばす
                        continue;
                    }
                    productCodeList.add(InstallationInfoI.MaterialNo);
                    //MODIFY BY SUNLEI 20160808
                    //productSerialNoList.add(InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo.trim());
                    productSerialNoList.add(InstallationInfoI.SerialNo.trim());
                }
            }
            // 診療科のみを取得
            List<Account> accList = [select Id, Management_Code__c, Department_Class__c, Hospital__c, RecordType.DeveloperName
                                     from Account
                                     where Management_Code__c in :managementCodeList];
            Map<String, Account> accsMap = new Map<String, Account>();
            for (Account acc : accList) {
                accsMap.put(acc.Management_Code__c, acc);
            }
            List<Product2> prdList = [select Id, Name, ProductCode, ProductCode_Ext__c, MDM_Model_No__c
                                      from Product2
                                      where ProductCode_Ext__c in :productCodeList];
            Map<String, Product2> prdsMap = new Map<String, Product2>();
            for (Product2 prd : prdList) {
                prdsMap.put(prd.ProductCode_Ext__c, prd);
            }

            //  报表可视化开发估时20210617   精琢科技    zxk    2021-08-26   start
            //添加的保有设备ID
            List<String> oldIdList = new List<String>();
            //  报表可视化开发估时20210617   精琢科技    zxk    2021-08-26   end

            List<Asset> astList = [select Id, Name, Product2.ProductCode, SerialNumber, Product_Serial_No__c, Repair_Count__c,
                                   Product2Id, AccountId, Account.Management_Code__c, Department_Class__c, Hospital__c,
                                   Posting_Date__c, InstallDate, SLMark__c,
                                   Guarantee_period_for_products__c, Installation_Site__c, OT_CODE__c, MDM_Model_No__c, CIC_call_back_check__c
                                   from Asset
                                   where SerialNumber in :productSerialNoList and Information_From__c <> '失单'];// and Delete_Flag__c = false];
            Map<String, Asset> astsMap = new Map<String, Asset>();
            Map<String, Integer> astcheckMap = new Map<String, Integer>();
            for (Asset ast : astList) {

                // 报表可视化开发估时20210617   精琢科技    zxk    2021-08-26   start
                oldIdList.add(ast.Id);
                // 报表可视化开发估时20210617   精琢科技    zxk    2021-08-26   end

                astsMap.put(ast.MDM_Model_No__c + ':' + ast.SerialNumber, ast);
                // HHOA-AGN2EH start
                if (astcheckMap.containsKey(ast.MDM_Model_No__c + ':' + ast.SerialNumber) == false) {
                    astcheckMap.put(ast.MDM_Model_No__c + ':' + ast.SerialNumber, 1);
                } else {
                    astcheckMap.put(ast.MDM_Model_No__c + ':' + ast.SerialNumber, astcheckMap.get(ast.MDM_Model_No__c + ':' + ast.SerialNumber) + 1);
                }
                // HHOA-AGN2EH end
            }

            // 更新対応配列をセット
            astList = new List<Asset>();
            Map<String, Asset> astUpdateMap = new Map<String, Asset>();
            List<Asset> astDelList = new List<Asset>();
            Map<String, Asset> astDelMap = new Map<String, Asset>();
            for (InstallationInfo InstallationInfo : installationInfoList) {
                InstallationInfoH InstallationInfoH = InstallationInfo.InstallationInfoH;
                if (InstallationInfoH == null) {
                    iflog.ErrorLog__c += 'Error! InstallationInfoH is required. This inquiry is skipped.\n';
                    continue;
                }
                if (InstallationInfo.InstallationInfoI == null || InstallationInfo.InstallationInfoI.size() == 0) {
                    iflog.ErrorLog__c += 'Error! InstallationInfoI is required. This inquiry is skipped.\n';
                    continue;
                }
// InstallationInfoH.PurposeOfAdvice を見ない
//                if (InstallationInfoH.PurposeOfAdvice == '1') {
//                    // deleteを無視
//                    logstr += 'InstallationInfoH.PurposeOfAdvice==1 ';
//                    continue;
//                }
                // InstallationInfoH より、病院と診療科の管理コード
                if (InstallationInfoH.CompanyCode == null || InstallationInfoH.CompanyCode == '') {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += 'Error! CompanyCode is required. This inquiry is skipped.\n';
                    continue;
                }
                if (InstallationInfoH.DepartmentCode == null || InstallationInfoH.DepartmentCode == '') {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += 'Error! DepartmentCode is required. This inquiry is skipped.\n';
                    continue;
                }
                if (accsMap.get(InstallationInfoH.CompanyCode) == null) {
                    iflog.ErrorLog__c += 'Error! Company[' + InstallationInfoH.CompanyCode + ']NotExist. This inquiry is skipped.\n';
                    continue;
                } else if (accsMap.get(InstallationInfoH.CompanyCode).RecordType.DeveloperName != 'HP'
                           && accsMap.get(InstallationInfoH.CompanyCode).RecordType.DeveloperName != 'Agency') {
                    iflog.ErrorLog__c += 'Error! Company[' + InstallationInfoH.CompanyCode + ']Is Not HP(Agency). This inquiry is skipped.\n';
                    continue;
                }
                if (accsMap.get(InstallationInfoH.DepartmentCode) == null) {
                    iflog.ErrorLog__c += 'Error! Department[' + InstallationInfoH.DepartmentCode + ']NotExist. This inquiry is skipped.\n';
                    continue;
                }
                for (InstallationInfoI InstallationInfoI : InstallationInfo.InstallationInfoI) {
                    if (InstallationInfoI.MaterialNo == null || InstallationInfoI.MaterialNo == '') {
                        // 必須項目がない場合、処理と飛ばす
                        iflog.ErrorLog__c += 'Error! MaterialNo is required. This asset is skipped.\n';
                        continue;
                    }
                    if (InstallationInfoI.SerialNo == null || InstallationInfoI.SerialNo == '') {
                        // 必須項目がない場合、処理と飛ばす
                        iflog.ErrorLog__c += 'Error! Product[' + InstallationInfoI.MaterialNo + '] SerialNo is required. This asset is skipped.\n';
                        continue;
                    }
                    Product2 prd = prdsMap.get(InstallationInfoI.MaterialNo);
                    if (prd == null) {
                        iflog.ErrorLog__c += 'Error! [' + InstallationInfoI.SerialNo + ']Product[' + InstallationInfoI.MaterialNo + ']NotExist. This asset is skipped.\n';
                        continue;
                    }
                    // HHOA-AGN2EH start
                    if (astcheckMap.containsKey(prd.MDM_Model_No__c + ':' + InstallationInfoI.SerialNo.trim()) == true && astcheckMap.get(prd.MDM_Model_No__c + ':' + InstallationInfoI.SerialNo.trim()) > 1) {
                        iflog.ErrorLog__c += 'Error! [' + InstallationInfoI.SerialNo + ']Product[' + InstallationInfoI.MaterialNo + '] Exist more than one. This asset is skipped.\n';
                        continue;
                    }
                    // HHOA-AGN2EH end
                    Asset ast = astsMap.get(prd.MDM_Model_No__c + ':' + InstallationInfoI.SerialNo.trim());
                    if (ast == null) {
                        // 保有設備存在しないのに、delete 受信の場合
                        //if (InstallationInfoI.ReturnExchangeReplenishMark == '1' || InstallationInfoI.PurposeOfAdvice == '1') {
                        // HHOA-AGN2EH start
                        //iflog.ErrorLog__c += 'Warning! Delete Asset[' + InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo + ']NotExist\n';
                        // HHOA-AGN2EH end
                        //    continue;
                        //}
                        //iflog.ErrorLog__c += '194[prd.MDM_Model_No__c:' + prd.MDM_Model_No__c + ']SUNLEI TEST[InstallationInfoI.SerialNo' + InstallationInfoI.SerialNo + '] DEUG\n';
                        //iflog.ErrorLog__c += '195[prd.MDM_Model_No__c:' + prd.MDM_Model_No__c + ']SUNLEI TEST[InstallationInfoI.SerialNo' + InstallationInfoI.SerialNo + '] DEUG\n';
                        //add by sunlei 20160810 保有設備存在しない新規の場合、何もしない
                        ast = new Asset();
                        ast.SerialNumber                     = InstallationInfoI.SerialNo.trim();
                        //continue;

                    } else {
                        if (InstallationInfoI.ReturnExchangeReplenishMark == '1' || InstallationInfoI.PurposeOfAdvice == '1') {
                            // 物理削除用
                            if (astDelMap.get(ast.Product_Serial_No__c) == null) {
                                astDelList.add(ast);
                                astDelMap.put(ast.Product_Serial_No__c, ast);
                            }
                            logstr += InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo + '(delete) ';
                            // 修理がある場合、Warning! を出す
                            if (ast.Repair_Count__c > 0) {
                                // HHOA-AGN2EH start
                                //iflog.ErrorLog__c += 'Warning! Delete Asset[' + InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo + '] with repair.\n';
                                // HHOA-AGN2EH end
                            }
                            continue;
                        }

                        // HHOA-AGN2EH start
                        if (ast.Hospital__c != accsMap.get(InstallationInfoH.CompanyCode).Id) {
                            iflog.ErrorLog__c += 'Warning! CompanyCode:' + '[' + InstallationInfoH.CompanyCode + '] is not match with the Asset[' + ast.OT_CODE__c + ':' + ast.SerialNumber + ']. This asset is skipped.\n';
                            continue;
                        }
                        // HHOA-AGN2EH end

                        //Modify by sunlei 20160804 更新的情况下 判断科室是否一致
                        if (ast.AccountId != accsMap.get(InstallationInfoH.DepartmentCode).Id) {
                            // interface科室 <>保有设备的科室、処理と飛ばす
                            iflog.ErrorLog__c += 'Warning! Asset' + '[' + ast.OT_CODE__c + ':' + ast.SerialNumber  + '] DepartmentCode:' + ast.Account.Management_Code__c + ' is updated to ' + InstallationInfoH.DepartmentCode + '.\n';
                            // HHOA-AGN2EH start
                            //continue;
                            // HHOA-AGN2EH end
                        }
                    }
                    if (InstallationInfoI.InstallationDateI == null || InstallationInfoI.InstallationDateI == '') {
                        // 必須項目がない場合、処理と飛ばす
                        iflog.ErrorLog__c += 'Error! [' + InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo + ']InstallationDateI is required. This asset is skipped.\n';
                        continue;
                    }
                    if (InstallationInfoI.SLMark == null || InstallationInfoI.SLMark == '') {
                        // 必須項目がない場合、処理と飛ばす
                        iflog.ErrorLog__c += 'Error! [' + InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo + ']SLMark is required. This asset is skipped.\n';
                        continue;
                    }

                    //Add by sunlei 20160804 更新的情况下[保有设备]的OT-CODE和机身编号一致进行更新
                    if (ast.SerialNumber == InstallationInfoI.SerialNo.trim() &&
                            ast.MDM_Model_No__c == prdsMap.get(InstallationInfoI.MaterialNo).MDM_Model_No__c &&
                            ast.OT_CODE__c != InstallationInfoI.MaterialNo  ) {
                        iflog.ErrorLog__c += 'Warning! Asset' + '[' + ast.OT_CODE__c + ':' + ast.SerialNumber  + '] is updated to [' + InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo + ']\n';
                        //iflog.ErrorLog__c += '241Warning! Asset' + '[' + ast.OT_CODE__c + ':' + ast.SerialNumber  + '] is sunleitest to [' + InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo + ']\n';
                        //continue;
                    }

                    // upsert用、項目転送
                    ast.Product_Serial_No__c = InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo.trim();
                    if (astUpdateMap.get(ast.Product_Serial_No__c) == null) {
                        astList.add(ast);
                        astUpdateMap.put(ast.Product_Serial_No__c, ast);
                        logstr += InstallationInfoI.MaterialNo + ':' + InstallationInfoI.SerialNo.trim() + ' ';
                    } else {
                        ast = astUpdateMap.get(ast.Product_Serial_No__c);
                    }
                    ast.Name                             = prd.Name;
                    ast.Order_No__c                      = InstallationInfoH.InquiryNo;
                    ast.Posting_Date__c                  = NFMUtil.parseStr2Date(InstallationInfoH.PostingDate);
                    ast.AccountId                        = accsMap.get(InstallationInfoH.DepartmentCode).Id;
                    ast.Department_Class__c              = accsMap.get(InstallationInfoH.DepartmentCode).Department_Class__c;
                    // HHOA-AGN2EH start
                    //ast.Hospital__c                      = accsMap.get(InstallationInfoH.CompanyCode).Id;
                    // HHOA-AGN2EH end
                    ast.Product2Id                       = prdsMap.get(InstallationInfoI.MaterialNo).Id;
                    // HHOA-AGN2EH start
                    //ast.SerialNumber                     = InstallationInfoI.SerialNo.trim();
                    // HHOA-AGN2EH end
                    ast.InstallDate                      = NFMUtil.parseStr2Date(InstallationInfoI.InstallationDateI);
                    System.debug('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++'+ast.InstallDate);
                    ast.SLMark__c                        = InstallationInfoI.SLMark;
                    // CHAN-AVC54T start
                    //ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(InstallationInfoI.GuaranteePeriod);
                    //Date gp = NFMUtil.parseStr2Date(InstallationInfoI.GuaranteePeriod);
                    //if (gp != null) {
                    //    ast.Guarantee_period_for_products__c = gp;
                    //}
                    // 20190906 2位数是年限 新数据，8位数是期限 老数据
                    if (String.isNotBlank(InstallationInfoI.GuaranteePeriod)) {
                        if (InstallationInfoI.GuaranteePeriod.trim().length() == 2) {
                            ast.New_logic_data__c            = true;
                            ast.Guarantee_period_year__c     = Decimal.valueOf(InstallationInfoI.GuaranteePeriod);
                        } else {
                            ast.New_logic_data__c            = False;
                            ast.Guarantee_period_for_products__c = NFMUtil.parseStr2Date(InstallationInfoI.GuaranteePeriod);
                        }
                    } else {
                        ast.New_logic_data__c               = true;
                    }
                    if (String.isNotBlank(InstallationInfoI.ProvistonPeriod)) {
                        ast.ProvistonPeriod__c              =  Decimal.valueOf(InstallationInfoI.ProvistonPeriod);
                    }
                    ast.EntryDate__c                        = NFMUtil.parseStr2Date(InstallationInfoH.EntryDate);
                    // CHAN-AVC54T end
                    //if (InstallationInfoI.Location != null) {
                    //    ast.Installation_Site__c         = InstallationInfoI.Location;
                    //}
                    ast.IF_Information_From__c           = true;
                }
            }
            if (astList.size() > 0) {
                upsert astList;
                for (Asset astID : astList) {
                    oldIdList.add(astID.Id);
                }

            }

            // 报表可视化开发估时20210617   精琢科技    zxk    2021-08-26   start
            //创建集合用来存放发货DN ID
            List<String> esingFromIdList = new List<String>();
            // Map<String,Statu_Achievements__c> statuAchievementsMap = new Map<String,Statu_Achievements__c>();
            if (oldIdList.size() > 0) {
                //用来存放发货DN对象 最后用来更新发货DN对象。
                Map<String, Statu_Achievements_DN__c> statuMap = new Map<String, Statu_Achievements_DN__c>();
                //根据保有设备ID作为调价查询保有设备里面的安装日期和安装状态，用来给发货DN对象安装日期和安装状态赋值。
                // 2021-11-12 "视同签收"功能修改 检索DN明细时候剔除外贸订单
                List<Statu_Achievements_DN_details__c> statuList = [select Id, asset__c, asset__r.InstallDate, asset__r.CIC_call_back_check__c,
                                                       Statu_Achievements_DN__c from Statu_Achievements_DN_details__c
                                                       where asset__c in:oldIdList and Statu_Achievements_DN__r.Opportunity__r.Trade__c != '外貿' 
                                                       Order by Statu_Achievements_DN__c, asset__r.InstallDate
                                                                   ];
                for (Statu_Achievements_DN_details__c sadnd : statuList) {
                    String DNId = sadnd.Statu_Achievements_DN__c;
                    Statu_Achievements_DN__c statu = new  Statu_Achievements_DN__c();
                    // Statu_Achievements__c statuAchievements = new Statu_Achievements__c();
                    statu.Id = DNId;
                    // String statuAchievementsId = sadnd.Statu_Achievements__c;
                    // statuAchievements.id = statuAchievementsId;
                    statu.InstallationStatus__c = '未安装';
                    if (statuMap.containsKey(DNId)) {
                        statu = statuMap.get(DNId);
                    }
                    //给发货DN对象安装日期赋值
                    statu.InstallDate__c = sadnd.asset__r.InstallDate;
                    if (statu.InstallDate__c != null) {
                        statu.InstallationStatus__c = '已安装';
                        // statuAchievements.Installation_Day__c = sadnd.asset__r.InstallDate;
                        esingFromIdList.add(DNId);
                    }
                    statuMap.put(DNId, statu);
                    // statuAchievementsMap.put(statuAchievementsId,statuAchievements);
                }

                if (statuMap.size() > 0) {
                    update statuMap.values();
                }
                // if (statuAchievementsMap.size()>0) {
                //     update statuAchievementsMap.values();
                // }
            }

            //集合用来存放签收单日期数据，目的为了如果签收已完成就不进行更新。
            Map<String, eSignForm__c> esMap =  new  Map<String, eSignForm__c>();

            if (esingFromIdList.size() > 0) {
                //根据发货DN  ID来查询经销商4个日期和医院4个日期，最后用来更新签收单数据。
                List<eSignForm__c> eSignFormDataList = [SELECT 
                                                            Id, 
                                                            agencyScanDay__c, 
                                                            agencySignUpDate__c, 
                                                            salesManageConfirmDate__c, 
                                                            Statu_Achievements_DN__c,
                                                            agencyConfirmDate__c, 
                                                            endUser__c, 
                                                            Sales_Root_Formula__c, 
                                                            HPScanDay__c, 
                                                            HPSignUpDate__c, 
                                                            Statu_Achievements_DN__r.InstallDate__c,
                                                            salesHPManageConfirmDate__c,
                                                            skip_Hospital_Sign__c, 
                                                            HPConfirmDate__c, 
                                                            DeemedReceipt__c, 
                                                            agencyDNSignUpStatus__c, 
                                                            HPDNSignUpStatus__c,
                                                            Statu_Achievements__r.Opportunity__r.Trade__c // 内贸/外贸 
                                                        From eSignForm__c
                                                        where Statu_Achievements_DN__c in:esingFromIdList
                                                       ];


                for (eSignForm__c eSignFormList : eSignFormDataList) {
                    
                    /**
                     * 1、经销商直销：只卖给经销商  契约
                     * 2、医院直销  ：只卖给医院    OCSM直接销售
                     * 3、经销商分销：卖给经销商  --->  医院   不等于契约   和  不等于OCSM直接销售
                     **/

                    String esnewId = eSignFormList.Id;

                    // 2022-01-18 只更新内贸订单
                    if (String.isNotBlank(eSignFormList.Statu_Achievements__r.Opportunity__r.Trade__c) && 
                        '内貿'.equals(eSignFormList.Statu_Achievements__r.Opportunity__r.Trade__c)) {
                        //只更新医院       直销
                        if ( !eSignFormList.skip_Hospital_Sign__c && eSignFormList.HPDNSignUpStatus__c != '签收已完成') {
                            eSignFormDataList02(eSignFormList);
                            esMap.put(esnewId, eSignFormList);
                        }
                        // 视同签收
                        eSignFormList.DeemedReceipt__c = true;
                    }
                }
                if (esMap.size() > 0) {
                    update esMap.values();
                }

            }
            //  报表可视化开发估时20210617    精琢科技    zxk    2021-08-26   end


            if (astDelList.size() > 0) {
                //delete astDelList;
                // TODO 今後 返品設備の科室に移動する可能性がある
                // HHOA-AGN2EH start
                //for (Asset ast : astDelList) {
                //    ast.Return_Flag__c = true;
                //}
                //update astDelList;
                // HHOA-AGN2EH end
            }
            logstr += '\nend';
            rowData.retry_cnt__c = 0;
        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM008_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM008_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                rowData.retry_cnt__c++;
                LogAutoSendSchedule.assignOneMinute();
            }
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信';
            }
        }

        update rowData;
        iflog.Log__c = logstr;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        update iflog;

    }
    // global static eSignForm__c eSignFormDataList01(eSignForm__c eSignFormList) {
    //     eSignFormList.agencyScanDay__c  = eSignFormList.Statu_Achievements_DN__r.InstallDate__c;
    //     eSignFormList.agencySignUpDate__c    = eSignFormList.Statu_Achievements_DN__r.InstallDate__c;
    //     eSignFormList.salesManageConfirmDate__c = eSignFormList.Statu_Achievements_DN__r.InstallDate__c;
    //     eSignFormList.agencyConfirmDate__c   = eSignFormList.Statu_Achievements_DN__r.InstallDate__c;
    //     return eSignFormList;
    // }
    global static eSignForm__c eSignFormDataList02(eSignForm__c eSignFormList) {
        eSignFormList.HPScanDay__c = eSignFormList.Statu_Achievements_DN__r.InstallDate__c;
        eSignFormList.HPSignUpDate__c = eSignFormList.Statu_Achievements_DN__r.InstallDate__c;
        eSignFormList.salesHPManageConfirmDate__c = eSignFormList.Statu_Achievements_DN__r.InstallDate__c;
        eSignFormList.HPConfirmDate__c = eSignFormList.Statu_Achievements_DN__r.InstallDate__c;
        // 2021-11-11 SAP报表医院签收确认日期显示需要医院审批状态为已批准
        // 视同签收的情况下 设置医院审批状态为已批准
        eSignFormList.HPSignUpStatus__c = '已批准';
        return eSignFormList;

    }

}