public with sharing class ImportdataController {
    
    @AuraEnabled
    public static ReturnObj importSpecialPrice(String dataStr){
        Savepoint sp = Database.setSavepoint();
        ReturnObj obj = new ReturnObj();
        try {
            System.debug('dataArr***'+dataStr);
            String errorMsg = '';
            List<Object> dataArr = (List<Object>)JSON.deserializeUntyped(dataStr);
            List<SpecialPriceWrapper> wrapperList = new List<SpecialPriceWrapper>();
            List<String> acccodeList = new List<String>();
            List<String> pList = new List<String>();
            for(Object mapData:dataArr){
                SpecialPriceWrapper wrapper = new SpecialPriceWrapper();
                Map<String,Object> valueMap = (Map<String,Object>)JSON.deserializeUntyped(JSON.serialize(mapData));
                wrapper.ContractName = (String)valueMap.get('合同名称');
                wrapper.ArrangeNo = (String)valueMap.get('协议编号');
                wrapper.ProductNo = (String)valueMap.get('产品型号');
                wrapper.OTCode = (String)valueMap.get('OTcode');
                wrapper.Discount = (Decimal)valueMap.get('特殊折扣(%)');
                wrapper.Price = (Decimal)valueMap.get('特殊折扣(金额)');
                acccodeList.add(wrapper.ArrangeNo);
                pList.add(wrapper.OTCode);
                wrapperList.add(wrapper);
            }
            Map<String,String> accMap = new Map<String,String>();
            Map<String,String> productMap = new Map<String,String>();
            for(Account acc:[SELECT Id,Term_Contract_No__c FROM Account WHERE RecordType.DeveloperName='AgencyContract' AND Term_Contract_No__c =:acccodeList]){
                accMap.put(acc.Term_Contract_No__c,acc.Id);
            }
            for(Product2__c p:[SELECT Id,OT_CODE_Text__c FROM Product2__c WHERE IsActive__c=true AND OT_CODE_Text__c=:pList]){
                productMap.put(p.OT_CODE_Text__c,p.Id);
            }
            Map<String,List<DiscountProductApplicationDetail__c>> detailMap = new Map<String,List<DiscountProductApplicationDetail__c>>();
            String recordTypeId = [select Id from RecordType where IsActive = true and DeveloperName = 'ProductDiscount'].Id;
            Map<String,DiscountProductApplication__c> dpaMap = new Map<String,DiscountProductApplication__c>();
            Integer i = 1;
            for(SpecialPriceWrapper wrapper:wrapperList){
                if(wrapper.OTCode == null || !productMap.containsKey(wrapper.OTCode)){
                    errorMsg += '第' + i + '行产品在系统中不存在；/n';
                }
                if(wrapper.ArrangeNo == null || !accMap.containsKey(wrapper.ArrangeNo)){
                    errorMsg += '第' + i + '行合同在系统中不存在；/n';
                }
                DiscountProductApplicationDetail__c dpad = new DiscountProductApplicationDetail__c();
                if(wrapper.Discount != null){
                    dpad.Special_Discount__c = wrapper.Discount;
                }
                if(wrapper.Price != null){
                    dpad.ProductDiscount__c = wrapper.Price;
                }
                dpad.Product2__c = productMap.get(wrapper.OTCode);
                if(!detailMap.containsKey(wrapper.ArrangeNo)){
                    DiscountProductApplication__c dpa = new DiscountProductApplication__c();
                    dpa.Dealer_Contact__c = accMap.get(wrapper.ArrangeNo);
                    dpa.ApplicationStatus__c = '草案中';
                    dpa.RecordTypeId = recordTypeId;
                    dpaMap.put(wrapper.ArrangeNo,dpa);
                    detailMap.put(wrapper.ArrangeNo ,new List<DiscountProductApplicationDetail__c>{dpad});
                }else{
                    detailMap.get(wrapper.ArrangeNo ).add(dpad);
                }
                i++;
            }
            List<DiscountProductApplicationDetail__c> alldetail = new List<DiscountProductApplicationDetail__c>();
            if(errorMsg == ''){

                insert dpaMap.values();
                List<String> dpaIds = new List<String>();
                for(String key:dpaMap.keyset()){
                    DiscountProductApplication__c dpa = dpaMap.get(key);
                    System.debug(LoggingLevel.INFO, '*11** dpa: ' + dpa);
                    dpaIds.add(dpa.Id);
                    for(DiscountProductApplicationDetail__c dpad:detailMap.get(key)){
                        dpad.DiscountProductApplication__c = dpa.Id;
                        alldetail.add(dpad);
                    }
                }
                System.debug(LoggingLevel.INFO, '*11** alldetail: ' + alldetail);
                insert alldetail;
                obj.msg = 'Success';
                List<DpaWrapper> wrappers = new List<DpaWrapper>();
                for(DiscountProductApplication__c dpa: [SELECT Id, Name, Dealer_Contact__r.Name,ApplicationStatus__c,RecordType.Name FROM DiscountProductApplication__c WHERE Id IN:dpaIds]){
                    DpaWrapper wrapper = new DpaWrapper();
                    wrapper.Id = dpa.Id;
                    wrapper.name = dpa.Name;
                    wrapper.accountName = dpa.Dealer_Contact__r.Name;
                    wrapper.status = dpa.ApplicationStatus__c;
                    wrapper.type = dpa.RecordType.Name;
                    wrappers.add(wrapper);
                }
                obj.data = wrappers;
            }else{
                obj.msg = errorMsg;
            }
            
            
        } catch (Exception e) {
            Database.rollback(sp);
            obj.msg = e.getMessage();
        }
        return obj;
    }

    @AuraEnabled
    public static ReturnObj importDiscountProductApplication(String dataStr){
        Savepoint sp = Database.setSavepoint();
        ReturnObj obj = new ReturnObj();
        try {
            System.debug('dataArr***'+dataStr);
            String errorMsg = '';
            List<Object> dataArr = (List<Object>)JSON.deserializeUntyped(dataStr);
            List<DiscountProductAppWrapper> wrapperList = new List<DiscountProductAppWrapper>();
            List<String> acccodeList = new List<String>();
            List<String> hospitalList = new List<String>();
            List<String> pList = new List<String>();
            for(Object mapData:dataArr){
                DiscountProductAppWrapper wrapper = new DiscountProductAppWrapper();
                Map<String,Object> valueMap = (Map<String,Object>)JSON.deserializeUntyped(JSON.serialize(mapData));
                wrapper.AccountName = (String)valueMap.get('经销商名称');
                wrapper.AccountNo = (String)valueMap.get('经销商管理编码');
                wrapper.Type = (String)valueMap.get('特价类型');
                wrapper.HospitalName = (String)valueMap.get('医院名称');
                wrapper.HospitalNo = (String)valueMap.get('医院管理编码');
                wrapper.ProductNo = (String)valueMap.get('产品型号');
                wrapper.OTCode = (String)valueMap.get('OTcode');
                wrapper.Price = (Decimal)valueMap.get('产品特价');
                acccodeList.add(wrapper.AccountNo);
                hospitalList.add(wrapper.HospitalNo);
                pList.add(wrapper.OTCode);
                wrapperList.add(wrapper);
            }
            Map<String,String> accMap = new Map<String,String>();
            Map<String,String> hosMap = new Map<String,String>();
            Map<String,String> productMap = new Map<String,String>();
            Map<String,String> agencyMap = new Map<String,String>();
            for(Account acc:[SELECT Id,Management_Code__c FROM Account WHERE RecordType.DeveloperName='Agency' AND Management_Code__c =:acccodeList]){
                accMap.put(acc.AccountNumber,acc.Id);
            }
            for(Account acc:[SELECT Id,Management_Code__c FROM Account WHERE RecordType.DeveloperName='HP' AND Management_Code__c =:hospitalList]){
                hosMap.put(acc.AccountNumber,acc.Id);
            }
            for(Product2__c p:[SELECT Id,OT_CODE_Text__c FROM Product2__c WHERE IsActive__c=true AND OT_CODE_Text__c=:pList]){
                productMap.put(p.OT_CODE_Text__c,p.Id);
            }
            for(Agency_Hospital_Link__c ahl:[SELECT Id,Agency__r.Management_Code__c,Hospital__r.Management_Code__c FROM Agency_Hospital_Link__c WHERE Agency__r.Management_Code__c IN:acccodeList AND Hospital__r.Management_Code__c IN:hospitalList]){
                agencyMap.put(ahl.Agency__r.Management_Code__c+ahl.Hospital__r.Management_Code__c,ahl.Agency__r.Management_Code__c+ahl.Hospital__r.Management_Code__c);
            }
            Map<String,List<DiscountProductApplicationDetail__c>> detailMap = new Map<String,List<DiscountProductApplicationDetail__c>>();
            String recordTypeId = [select Id from RecordType where IsActive = true and DeveloperName = 'HospitalSpecials'].Id;
            Integer i = 1;
            Map<String,DiscountProductApplication__c> dpaMap = new Map<String,DiscountProductApplication__c>();
            for(DiscountProductAppWrapper wrapper:wrapperList){
                if(wrapper.OTCode == null || !productMap.containsKey(wrapper.OTCode)){
                    errorMsg += '第' + i + '行产品在系统中不存在；/n';
                }
                if(wrapper.AccountNo == null || !accMap.containsKey(wrapper.AccountNo)){
                    errorMsg += '第' + i + '行经销商在系统中不存在；/n';
                }
                if(wrapper.HospitalNo == null || !hosMap.containsKey(wrapper.HospitalNo)){
                    errorMsg += '第' + i + '行医院在系统中不存在；/n';
                }
                if(!agencyMap.containsKey(wrapper.AccountNo + wrapper.HospitalNo)){
                    errorMsg += '第' + i + '行经销商医院在系统中不存在；/n';
                }
                DiscountProductApplicationDetail__c dpad = new DiscountProductApplicationDetail__c();
                // if(wrapper.Discount != null){
                //     dpad.Special_Discount__c = wrapper.Discount;

                // }
                if(wrapper.Price != null){
                    dpad.ProductDiscount__c = wrapper.Price;
                }
                dpad.Product2__c = productMap.get(wrapper.OTCode);
                if(!detailMap.containsKey(wrapper.AccountNo + wrapper.HospitalNo)){
                    DiscountProductApplication__c dpa = new DiscountProductApplication__c();
                    dpa.Product_Type__c = 'ENG';
                    dpa.AimsAccount__c = hosMap.get(wrapper.HospitalNo);
                    dpa.RawAccount__c = accMap.get(wrapper.AccountNo);
                    dpa.ApplicationStatus__c = '草案中';
                    dpa.RecordTypeId = recordTypeId;
                    dpaMap.put(wrapper.AccountNo + wrapper.HospitalNo,dpa);
                    detailMap.put(wrapper.AccountNo + wrapper.HospitalNo,new List<DiscountProductApplicationDetail__c>{dpad});
                }else{
                    detailMap.get(wrapper.AccountNo + wrapper.HospitalNo).add(dpad);
                }
                i ++;
            }

            List<DiscountProductApplicationDetail__c> alldetail = new List<DiscountProductApplicationDetail__c>();
            if(errorMsg == ''){
                insert dpaMap.values();
                List<String> dpaIds = new List<String>();
                for(String key:dpaMap.keyset()){
                    DiscountProductApplication__c dpa = dpaMap.get(key);
                    dpaIds.add(dpa.Id);
                    for(DiscountProductApplicationDetail__c dpad:detailMap.get(key)){
                        dpad.DiscountProductApplication__c = dpa.Id;
                        alldetail.add(dpad);
                    }
                }
                insert alldetail;
                obj.msg = 'Success';
                List<DpaWrapper> wrappers = new List<DpaWrapper>();
                for(DiscountProductApplication__c dpa: [SELECT Id, Name,AimsAccount__r.Name, RawAccount__r.Name,ApplicationStatus__c,RecordType.Name FROM DiscountProductApplication__c WHERE Id IN:dpaIds]){
                    DpaWrapper wrapper = new DpaWrapper();
                    wrapper.Id = dpa.Id;
                    wrapper.name = dpa.Name;
                    wrapper.accountName = dpa.RawAccount__r.Name;
                    wrapper.hospitalName = dpa.AimsAccount__r.Name;
                    wrapper.status = dpa.ApplicationStatus__c;
                    wrapper.type = dpa.RecordType.Name;
                    wrappers.add(wrapper);
                }
                obj.data = wrappers;
            }else{
                obj.msg = errorMsg;
            }
        } catch (Exception e) {
            Database.rollback(sp);
            obj.msg = e.getMessage();
        }
        return obj;
    }

    @AuraEnabled
    public static String submitApproval(List<DpaWrapper> dpaList) {
        System.debug('tbc enter submitApproval');

        for (DpaWrapper dpa: dpaList) {
            System.debug(dpa.Id);
            System.debug(dpa.name);
        }
        List<Approval.ProcessSubmitRequest> requests = new List<Approval.ProcessSubmitRequest> ();
        for (DpaWrapper dpa: dpaList) {
            Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
            req1.setComments('Submitting request for approval ');  
            req1.setObjectId(dpa.id);
            requests.add(req1);

            System.debug(req1);
        }
        Approval.ProcessResult[] processResults = null;
        System.debug(requests);
        try {
            processResults = Approval.process(requests, true);
        }catch (System.DmlException e) {
            System.debug('Exception Is ' + e.getMessage());
            return e.getMessage();
        }
        return 'Success';
  }

    public class ReturnObj{
        @AuraEnabled
        public String msg;
        @AuraEnabled
        public List<DpaWrapper> data;
    }

    Public class DpaWrapper{
        @AuraEnabled
        public String Id;
        @AuraEnabled
        public String name;
        @AuraEnabled
        public String accountName;
        @AuraEnabled
        public String hospitalName;
        @AuraEnabled
        public String status;
        @AuraEnabled
        public String type;
    }

    public class SpecialPriceWrapper{
        public String ContractName;
        public String ArrangeNo;
        public String ProductNo;
        public String OTCode;
        public Decimal Discount;
        public Decimal Price;
    }
    public class DiscountProductAppWrapper{
        public String AccountName;
        public String AccountNo;
        public String HospitalName;
        public String HospitalNo;
        public String Type;
        public String ProductNo;
        public String OTCode;
        public Decimal Price;
    }

}