@RestResource(urlMapping='/NFM104/*')
global with sharing class NFM104Rest  {

    global class RepairQuotationRest {
        public RepairQuotation RepairQuotation;
    }

    global class RepairQuotation {
        public NFMUtil.Monitoring Monitoring;
        public QuotationHeaderInformation[] QuotationHeaderInformation;
    }
    global class QuotationHeaderInformation {
        public String SFDCRepairNo;
        public String SAPRepairNo;
        public String SAPQuotationNo;
        public String FirstQuotationDate;
        public String LatestQuotationDate;
        public String ListPrice;
        public String TotalPrice;
        public String RepairRank;
        public String CafeteriaFlag;
        public DiscountInformation[] DiscountInformation;
        public InspectionResultInformation[] InspectionResultInformation;
        public FailureInformation[] FailureInformation;
        public ActivityInformation[] ActivityInformation;
    }
    global class DiscountInformation {
        public String DiscountType;
        public String DiscountAmount;
    }
    global class InspectionResultInformation {
        public String InspectionResultFlag;
        public String InspectionComment;
        public String FailureCause;
    }
    global class FailureInformation {
        public String LocationGroupName;
        public String LocationName;
        public String PhenomenonName;
        public String CauseName;
        public String DescriptionName;
    }
    global class ActivityInformation {
        public String ActivityDescription;
    }

    @HttpPost
    global static void execute() {

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

        if (ges == null ) {
            return;
        }

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

        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM104', ges.RepairQuotation.QuotationHeaderInformation);
        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, TransmissionDateTime__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 = 'NFM104';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;
        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<QuotationHeaderInformation> quotationInformationList = (List<QuotationHeaderInformation>) JSON.deserialize(rowDataStr, List<QuotationHeaderInformation>.class);
        if (quotationInformationList == null || quotationInformationList.size() == 0) {
            return;
        }

        Savepoint sp = Database.setSavepoint();
        try {
            //repairNo list
            List<String> receiptNoList = new List<String>();
            //报价No SAPQuotationNo list
            List<String> quotationNoList = new List<String>();
            // 2018/8/20 HWAG-B3P55Z start 存储CafeteriaFlagList
            list<string> CafeteriaFlagList = new list<string>();
            // 2018/8/20 HWAG-B3P55Z start 存储CafeteriaFlagList
            for (NFM104Rest.QuotationHeaderInformation quoteInfo : quotationInformationList) {
                // 必須項目がない場合、処理と飛ばす
                if (quoteInfo.SAPQuotationNo == null || quoteInfo.SAPQuotationNo == '') {
                    iflog.ErrorLog__c += 'SAPQuotationNo is required\n';
                    continue;
                }
                if (quoteInfo.SFDCRepairNo == null || quoteInfo.SFDCRepairNo == '') {
                    iflog.ErrorLog__c += '[' + quoteInfo.SAPQuotationNo + ']SFDCRepairNo is required\n';
                    continue;
                }

                if (quoteInfo.SFDCRepairNo != null && quoteInfo.SFDCRepairNo != '') {
                    receiptNoList.add(quoteInfo.SFDCRepairNo);
                }
            // 2018/8/20 HWAG-B3P55Z start 存储CafeteriaFlagList
                if(String.isNotEmpty(quoteInfo.CafeteriaFlag)){
                    CafeteriaFlagList.add(quoteInfo.CafeteriaFlag);
                }
            // 2018/8/20 HWAG-B3P55Z start 存储CafeteriaFlagList
                quotationNoList.add(quoteInfo.SAPQuotationNo);
            }

            //修理を検索
            List<Repair__c> sfdcRpairList = [select Id, Name, SAPRepairNo__c, Repair_Quotation_Id__c
                                                , Repair_Quotation_Id__r.MessageGroupNumber__c
                                           from Repair__c
                                          where Name in :receiptNoList];
            Map<String, Repair__c> sfdcRepairsMap = new Map<String, Repair__c>();
            for (Repair__c recpt : sfdcRpairList) {
                sfdcRepairsMap.put(recpt.Name, recpt);
            }

            List<Repair_Quotation__c> quotationList = [select Id, Name, Repair_Rank__c, Repair__c
                                                              , InspectionComment__c, InspectionResultFlag__c
                                                              , InspectionFailureCause__c
                                                              , LatestQuotationDate__c
                                                              , FirstQuotationDate__c, ListPrice__c, TotalPrice__c
                                                              , Repair_Discount_Date__c
                                                              , CafeteriaFlag__c, MessageGroupNumber__c
                                                         from Repair_Quotation__c
                                                        where Name in :quotationNoList
                                                      ];
            Map<String, Repair_Quotation__c> quotationMap = new Map<String, Repair_Quotation__c>();
            for (Repair_Quotation__c quotation : quotationList) {
                quotationMap.put(quotation.Name, quotation);
            }

            // 更新対応配列をセット
            Map<String, Repair__c> repairUpdateMap = new Map<String, Repair__c>();
            Map<String, Repair_Quotation__c> rqUpdateMap = new Map<String, Repair_Quotation__c>();
            Map<String, List<Repair_Quotation_reason__c>> quotationReasonsMap = new Map<String, List<Repair_Quotation_reason__c>>();
            Map<Id, List<Repair_reason__c>> repairReasonsMap = new Map<Id, List<Repair_reason__c>>();

            // 2018/8/20 HWAG-B3P55Z start 构造经销商map
            list<Account> accs = [select id,Name, Management_Code__c from Account where Management_Code__c in: CafeteriaFlagList];
            map<string, Account> DealersAccMap = new map<string, Account>();
            for(Account acc : accs){
                DealersAccMap.put(acc.Management_Code__c,acc);
            }
            // 2018/8/20 HWAG-B3P55Z end 构造经销商map
            for (NFM104Rest.QuotationHeaderInformation quoteInfo : quotationInformationList) {
                Repair_Quotation__c rq = null;
                if (quoteInfo.SAPQuotationNo != null && quoteInfo.SAPQuotationNo != '') {
                    rq = quotationMap.get(quoteInfo.SAPQuotationNo);
                }
                if (rq == null) {
                    rq = new Repair_Quotation__c();
                }
                //修理を取る
                Repair__c rpr = sfdcRepairsMap.get(quoteInfo.SFDCRepairNo.toUpperCase());
                if (rpr == null) {
                    iflog.ErrorLog__c += 'SFDCRepairNo[' + quoteInfo.SFDCRepairNo + ']NotExist\n';
                    continue;
                } else {
                    // 同期中的询价为空或者MessageGroupNumber小于正在执行的的MessageGroupNumber
                    if (rpr.Repair_Quotation_Id__c == null
                            || String.isBlank(rpr.Repair_Quotation_Id__r.MessageGroupNumber__c)
                            || Integer.valueOf(rpr.Repair_Quotation_Id__r.MessageGroupNumber__c) <= Integer.valueOf(rowData.MessageGroupNumber__c)) {
                        //rprUpdateList.add(rpr);
                        repairUpdateMap.put(quoteInfo.SAPQuotationNo, rpr);
                        rpr.SAPRepairNo__c = quoteInfo.SAPRepairNo;
                        rpr.Repair_Rank__c = quoteInfo.RepairRank;
                        /*if (String.isBlank(quoteInfo.CafeteriaFlag) == false && ( quoteInfo.CafeteriaFlag.length() == 15 || quoteInfo.CafeteriaFlag.length() == 18)) {
                            rpr.Dealer__c = quoteInfo.CafeteriaFlag;
                        }*/
                    }
                }
                if (rq.Repair__c == null) {
                    rq.Repair__c = rpr.Id;
                } else {
                    if (rq.Repair__c != rpr.Id) {
                        iflog.ErrorLog__c += 'isnot SFDCRepairNo[' + quoteInfo.SFDCRepairNo + ']\'s child\n';
                    }
                }

                rq.Name = quoteInfo.SAPQuotationNo;
                if (rqUpdateMap.get(rq.Name) == null) {
                    rqUpdateMap.put(rq.Name, rq);
                    logstr += quoteInfo.SAPQuotationNo + ' ';
                } else {
                    rq = rqUpdateMap.get(rq.Name);
                }

                if (String.isBlank(rq.MessageGroupNumber__c) || Integer.valueOf(rq.MessageGroupNumber__c) <= Integer.valueOf(rowData.MessageGroupNumber__c)) {
                    rq.FirstQuotationDate__c   = NFMUtil.parseStr2Date(quoteInfo.FirstQuotationDate);              // TODO 修理単位？报价単位？
                    rq.LatestQuotationDate__c  = NFMUtil.parseStr2Date(quoteInfo.LatestQuotationDate);             // TODO 修理単位？报价単位？
                    rq.Repair_Rank__c          = quoteInfo.RepairRank;
                    rq.ListPrice__c            = String.isBlank(quoteInfo.ListPrice) ? null : Decimal.valueOf(quoteInfo.ListPrice);
                    rq.TotalPrice__c           = String.isBlank(quoteInfo.TotalPrice) ? null : Decimal.valueOf(quoteInfo.TotalPrice);
                    // 2018/8/17 HWAG-B3P55Z start 注释
                    //rq.CafeteriaFlag__c        = quoteInfo.CafeteriaFlag == 'X' ? true : false;
                    // 2018/8/17 HWAG-B3P55Z start 注释
                    // 2018/8/17 HWAG-B3P55Z start 赋值给经销商管理编码
                    if(String.isNotEmpty(quoteInfo.CafeteriaFlag)){
                        if(DealersAccMap.containsKey(quoteInfo.CafeteriaFlag)){
                            Account acc = DealersAccMap.get(quoteInfo.CafeteriaFlag);
                            rq.Dealer_Name__c               = acc.Name;
                            rq.Dealer_Management_Code__c    = quoteInfo.CafeteriaFlag;
                            rq.Dealer_NameCZ__c             =acc.Id;
                        }
                    }
                    // 2018/8/17 HWAG-B3P55Z end  赋值给经销商管理编码
                }

                if (quoteInfo.DiscountInformation != null && quoteInfo.DiscountInformation.size() != 0) {
                    if (String.isBlank(rq.MessageGroupNumber__c) || Integer.valueOf(rq.MessageGroupNumber__c) <= Integer.valueOf(rowData.MessageGroupNumber__c)) {
                        // 新しいI/F しか処理しない
                        for (NFM104Rest.DiscountInformation di : quoteInfo.DiscountInformation) {
                            if (di.DiscountType == '营业对应') {
                                rq.sales_discount__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '维修协议') {
                                rq.Contract_target__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '新品保修期内无偿') {
                                rq.New_QIS_free__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '新品保修期内非品质问题') {
                                rq.New_QIS_not_QIS_issue__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '维修保修期内无偿') {
                                rq.Contract_free__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '维修保修期非品质问题') {
                                rq.Contract_not_QIS_issue__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '备品修理') {
                                rq.Loaner_repair__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '维护保养项目') {
                                rq.maintenance_pj__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == 'CCD线短') {
                                rq.CCD_cut__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '特别对应') {
                                rq.Special_offer__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            // LHJ 多年保修 Start
                            // else if (di.DiscountType == '多年保修') {
                            //     rq.long_term_insurance__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            // }
                            else if (di.DiscountType == '多年保修' || di.DiscountType == '服务多年保修') {
                                rq.long_term_insurance__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '市场多年保修') {
                                rq.long_term_insurance_MD__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            // LHJ 多年保修 End
                            else if (di.DiscountType == '套餐折扣') {
                                rq.Set_discount__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else if (di.DiscountType == '维修合同') {
                                rq.Servince_contract_discount_amount__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            // add by hanchao 2016.7.21
                            else if (di.DiscountType == '运输索赔') {
                                rq.Delivery_compensation__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            //
                            else if (di.DiscountType == '其他') {
                                rq.Other_discount__c = String.isBlank(di.DiscountAmount) ? null : Decimal.valueOf(di.DiscountAmount);
                            }
                            else {
                                iflog.ErrorLog__c += 'SFDCRepairNo[' + quoteInfo.SFDCRepairNo + '] Undefined DiscountType[' + di.DiscountType + ']\n';
                            }
                        }
                    }
                    if (String.isBlank(rq.MessageGroupNumber__c) || rq.MessageGroupNumber__c > rowData.MessageGroupNumber__c) {
                        // 一回目 or 古いI/Fが来た場合
                        rq.Repair_Discount_Date__c = NFMUtil.parseStr2DateTimeDate(rowData.TransmissionDateTime__c + '00');
                    }
                }
                if (quoteInfo.InspectionResultInformation != null && quoteInfo.InspectionResultInformation.size() != 0) {
                    if (String.isBlank(rq.MessageGroupNumber__c) || Integer.valueOf(rq.MessageGroupNumber__c) <= Integer.valueOf(rowData.MessageGroupNumber__c)) {
                        if (quoteInfo.InspectionResultInformation.size() > 1) {
                            iflog.ErrorLog__c += 'SFDCRepairNo[' + quoteInfo.SFDCRepairNo + '] InspectionResultInformation count is ' + quoteInfo.InspectionResultInformation.size() + '\n';
                        }
                        rq.InspectionResultFlag__c   = quoteInfo.InspectionResultInformation[0].InspectionResultFlag == 'X' ? 'OK' : 'NG';
                        rq.InspectionComment__c      = quoteInfo.InspectionResultInformation[0].InspectionComment;
                        rq.InspectionFailureCause__c = quoteInfo.InspectionResultInformation[0].FailureCause;
                    }
                }
                // Repair_quotation_reason__c delete insert する、見積りはまだinsertされていない可能性もあるので、upsert rqList; のあとやります。
                List<Repair_Quotation_reason__c> quotationReasons = new List<Repair_Quotation_reason__c>();
                quotationReasonsMap.put(rq.Name, quotationReasons);
                List<Repair_reason__c> repairReasons = new List<Repair_reason__c>();
                repairReasonsMap.put(rpr.Id, repairReasons);            // 複数見積りの場合後優先にする
                System.debug('quoteInfo.ActivityInformation=' + quoteInfo.ActivityInformation);
                if (quoteInfo.ActivityInformation != null && quoteInfo.ActivityInformation.size() != 0) {
                System.debug('rq.MessageGroupNumber__c=' + rq.MessageGroupNumber__c);
                    if (String.isBlank(rq.MessageGroupNumber__c) || Integer.valueOf(rq.MessageGroupNumber__c) <= Integer.valueOf(rowData.MessageGroupNumber__c)) {
                        System.debug('before ActivityInformation quotationReasons=' + quotationReasons);
                        for (NFM104Rest.ActivityInformation ai : quoteInfo.ActivityInformation) {
                            if (String.isBlank(ai.ActivityDescription) == false) {
                                Repair_Quotation_reason__c qrsn = new Repair_Quotation_reason__c();
                                quotationReasons.add(qrsn);
                                qrsn.ActivityDescription__c = ai.ActivityDescription;
                                Repair_reason__c rrsn = new Repair_reason__c(Repair__c = rpr.Id);
                                repairReasons.add(rrsn);
                                rrsn.ActivityDescription__c = ai.ActivityDescription;
                            }
                        }
                    }
                }
                if (String.isBlank(rq.MessageGroupNumber__c) || Integer.valueOf(rq.MessageGroupNumber__c) <= Integer.valueOf(rowData.MessageGroupNumber__c)) {
                    if (quoteInfo.FailureInformation != null && quoteInfo.FailureInformation.size() != 0) {
                        for (NFM104Rest.FailureInformation fi : quoteInfo.FailureInformation) {
                            Repair_Quotation_reason__c qrsn = new Repair_Quotation_reason__c();
                            quotationReasons.add(qrsn);
                            qrsn.LocationGroupName__c    = fi.LocationGroupName;
                            qrsn.LocationName__c         = fi.LocationName;
                            qrsn.PhenomenonName__c       = fi.PhenomenonName;
                            qrsn.CauseName__c            = fi.CauseName;
                            qrsn.DescriptionName__c      = fi.DescriptionName;
                            Repair_reason__c rrsn = new Repair_reason__c(Repair__c = rpr.Id);
                            repairReasons.add(rrsn);
                            rrsn.LocationGroupName__c    = fi.LocationGroupName;
                            rrsn.LocationName__c         = fi.LocationName;
                            rrsn.PhenomenonName__c       = fi.PhenomenonName;
                            rrsn.CauseName__c            = fi.CauseName;
                            rrsn.DescriptionName__c      = fi.DescriptionName;
                        }
                    }
                }
                if (String.isBlank(rq.MessageGroupNumber__c) || Integer.valueOf(rq.MessageGroupNumber__c) <= Integer.valueOf(rowData.MessageGroupNumber__c)) {
                    rq.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
                }
            }

            List<Repair_Quotation__c> rqList = rqUpdateMap.values();
            if (rqList.size() > 0) {
                // TODO update false;
                upsert rqList;
                deleteInsertReasons(rqUpdateMap, quotationReasonsMap, null);        // repairReasonsMap
            }
            
            if (repairUpdateMap.size() > 0) {
                //同期中的报价をwrite back, Idについて見積りがupsert後しかとれないです。
                for (String sapQuotationNo : repairUpdateMap.keySet()) {
                    Repair__c rpr = repairUpdateMap.get(sapQuotationNo);
                    rpr.Repair_Quotation_Id__c = rqUpdateMap.get(sapQuotationNo).Id;
                    rpr.Repair_Estimated_Date__c = rqUpdateMap.get(sapQuotationNo).FirstQuotationDate__c;
                    rpr.Repair_Discount_Date__c = rqUpdateMap.get(sapQuotationNo).Repair_Discount_Date__c;
                }
                update repairUpdateMap.values();
            }

            logstr += '\nend';
            rowData.retry_cnt__c=0;
        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM104_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM104_' + 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;
    }
    
    // NFM104とNFM105より呼び出す
    public static void deleteInsertReasons(Map<String, Repair_Quotation__c> rqNameMap,
        Map<String, List<Repair_Quotation_reason__c>> quotationReasonsMap, Map<Id, List<Repair_reason__c>> repairReasonsMap) {
        System.debug('deleteInsertReasons start');
        Boolean fromNFM105 = false;
        if (repairReasonsMap != null) {
            fromNFM105 = true;
        }
        List<Repair_quotation_reason__c> quoReasonList = null;
        if (fromNFM105) {
            // NFM105の場合、理由だけ変更する
            quoReasonList = [Select Id from Repair_quotation_reason__c where Repair_quotation__r.Name IN: quotationReasonsMap.keySet() and ActivityDescription__c = null];
        } else {
            quoReasonList = [Select Id from Repair_quotation_reason__c where Repair_quotation__r.Name IN: quotationReasonsMap.keySet()];
        }
        if (quoReasonList.size() > 0) delete quoReasonList;
        if (repairReasonsMap != null) {
            List<Id> rprIds = new List<Id>();
            for (String rqName : quotationReasonsMap.keySet()) {
                rprIds.add(rqNameMap.get(rqName).Repair__c);
            }
            List<Repair_reason__c> rprReasonList = null;
            if (fromNFM105) {
                // NFM105の場合、理由だけ変更する
                rprReasonList = [Select Id from Repair_reason__c where Repair__c IN: rprIds and ActivityDescription__c = null];
            } else {
                rprReasonList = [Select Id from Repair_reason__c where Repair__c IN: rprIds];
            }
            if (rprReasonList.size() > 0) delete rprReasonList;
        }
        List<Repair_Quotation_reason__c> qrsnList = new List<Repair_Quotation_reason__c>();
        List<Repair_reason__c> rrsnList = new List<Repair_reason__c>();
        for (String rqName : quotationReasonsMap.keySet()) {
            List<Repair_Quotation_reason__c> quotationReasons = quotationReasonsMap.get(rqName);
            qrsnList.addAll(quotationReasons);
            for (Repair_Quotation_reason__c qrsn : quotationReasons) {
                qrsn.Repair_quotation__c = rqNameMap.get(rqName).Id;
            }
            if (repairReasonsMap != null) {
                List<Repair_reason__c> repairReasons = repairReasonsMap.get(rqNameMap.get(rqName).Repair__c);
                rrsnList.addAll(repairReasons);
                for (Repair_reason__c rrsn : repairReasons) {
                    rrsn.Repair_quotation__c = rqNameMap.get(rqName).Id;
                }
            }
        }
        System.debug('deleteInsertReasons qrsnList=' + qrsnList);
        if (rrsnList.size() > 0) insert rrsnList;
        if (qrsnList.size() > 0) insert qrsnList;
    }

}