// RowDataを残すため、@future execute にします
global class NFM006WebService {
    // Integer batchsize = 200;  考量する必要がないと思います。
    global class SFDAStatuses {
        webservice NFMUtil.Monitoring Monitoring;
        webservice NFM006WebService.SFDAStatus[] SFDAStatus;
    }
    global class SFDAStatus {
        webservice String ItemCode;
        webservice String Status;
        webservice String SFDANo;
        webservice String EffectiveDateFrom;
        webservice String EffectiveDateTo;
        webservice String PurposeOfAdvice;
    }

    // 非同期を見せかけ、常にreturn void
    webservice static void NFM006(NFM006WebService.SFDAStatuses SFDAStatuses) {
        if (SFDAStatuses == null) {
            return;
        }
        NFMUtil.Monitoring Monitoring = SFDAStatuses.Monitoring;
        if (Monitoring == null) {
            return;
        }
        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM006', SFDAStatuses.SFDAStatus);
        if (String.isBlank(rowData.Log__c) == false) executefuture(rowData.Id);
    }

    @future
    global static void executefuture(String rowData_Id) {
        execute(rowData_Id);
    }
    global static void execute(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 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 = 'NFM006';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;

        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<SFDAStatus> sFDAStatusList = (List<SFDAStatus>) JSON.deserialize(rowDataStr, List<SFDAStatus>.class);

        if (sFDAStatusList == null || sFDAStatusList.size() == 0) {
            return;
        }

        // BatchIF転送表 から、コード変換のMapを作成
        Map<String, String> transferMap = new Map<String, String>();
        List<BatchIF_Transfer__c> transferList = [select Table__c,
                                                         Column__c,
                                                         External_value__c,
                                                         Internal_value__c
                                                    from BatchIF_Transfer__c
                                                   where Dropped_Flag__c = false
                                                     and Table__c = 'Product2'];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }

        Savepoint sp = Database.setSavepoint();
        try {
            // 更新対応配列とMapなどをセット
            List<String> productCodeList = new List<String>();
            for (NFM006WebService.SFDAStatus SFDAStatus : sFDAStatusList) {
                if (SFDAStatus.PurposeOfAdvice == '1') {
                    // deleteを無視
                    continue;
                }
                if (SFDAStatus.ItemCode == null || SFDAStatus.ItemCode == '' ||
                    SFDAStatus.Status == null || SFDAStatus.Status == ''
                ) {
                    // 必須項目がない場合、処理と飛ばす
                    continue;
                }
                productCodeList.add(SFDAStatus.ItemCode);
            }
            List<Product2> prdList = [select Id, Name, ProductCode, ProductCode_Ext__c,
                                             SFDA_Status__c,
                                             SFDA_Approbation_No__c,
                                             SFDA_Approbated_Date__c,
                                             SFDA_Expiration_Date__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);
            }
            
            // 更新対応配列をセット
            prdList = new List<Product2>();
            Map<String, Product2> prdUpdateMap = new Map<String, Product2>();
            for (NFM006WebService.SFDAStatus SFDAStatus : sFDAStatusList) {
                if (SFDAStatus.PurposeOfAdvice == '1') {
                    // deleteを無視
                    logstr += 'PurposeOfAdvice==1 ';
                    continue;
                }
                if (SFDAStatus.ItemCode == null || SFDAStatus.ItemCode == '') {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += 'ItemCode is required\n';
                    continue;
                }
                if (SFDAStatus.Status == null || SFDAStatus.Status == '' ||
                    NFMUtil.getMapValue(transferMap, 'SFDA_Status__c', SFDAStatus.Status, iflog) == SFDAStatus.Status
                ) {
                    // 必須項目がない場合、処理と飛ばす
                    iflog.ErrorLog__c += '[' + SFDAStatus.ItemCode + ']Status is required\n';
                    continue;
                }
                Product2 prd = prdsMap.get(SFDAStatus.ItemCode);
                if (prd == null) {
                    // 更新対象商品がない場合
                    prd = new Product2();
                    prd.Name = SFDAStatus.ItemCode;
                }
                
                // 項目転送のセット
                prd.ProductCode = SFDAStatus.ItemCode;
                if (prdUpdateMap.get(prd.ProductCode) == null) {
                    prdList.add(prd);
                    prdUpdateMap.put(prd.ProductCode, prd);
                    logstr += SFDAStatus.ItemCode + '(' + SFDAStatus.Status + ') ';
                } else {
                    prd = prdUpdateMap.get(prd.ProductCode);
                    logstr += SFDAStatus.ItemCode + '(' + SFDAStatus.Status + ') ';
                }
                prd.SFDA_Status__c          = NFMUtil.getMapValue(transferMap, 'SFDA_Status__c', SFDAStatus.Status, iflog);
                prd.SFDA_Approbation_No__c  = SFDAStatus.SFDANo;
                prd.SFDA_Approbated_Date__c = NFMUtil.parseStr2Date(SFDAStatus.EffectiveDateFrom, false);
                prd.SFDA_Expiration_Date__c = NFMUtil.parseStr2Date(SFDAStatus.EffectiveDateTo);
            }
            if (prdList.size() > 0) {
                upsert prdList;
            }
            logstr += '\nend';
            rowData.retry_cnt__c=0;
        } catch(Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM006_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM006_' + 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;
    }
}