/**
     * [FrameNumUploadController 进口单证上传]
     * @Author   lijinhuan
     * @DateTime 2022-11-04T18:31:03+0800
     * @return   [进口单证上传]
*/
public with sharing class FrameNumUploadController {
    public Integer detailCountLimit{get;private set;}
    public FrameNumUploadController() {
        detailCountLimit = 10000;
    }
    public void importCSVFile() {
        String csvData = ApexPages.currentPage().getParameters().get('csvData');
        List<List<String>> tempCsvBody = CSVReader.readIETFRFC4180CSVFile(Blob.valueof(csvData));  // 全部CSV数据
        List<String> importLabelList = tempCsvBody[0];  // CSV读入的标题行
        // List<FrameNumManage__c> fnmList = new List<FrameNumManage__c>();
        Map<String,FrameNumManage__c> fnmMap = new Map<String,FrameNumManage__c>();
        Integer importLine = 0;
        List<String> warningList = new List<String>(); 
        Map<String, String> labelToApiMap = createLabelApiMap();
        Map<String, SObjectField> queryFrameNumFieldMap = FrameNumManage__c.getSObjectType().getDescribe().fields.getMap();
        
        for (Integer i = 1; i < tempCsvBody.size(); i++) {
            FrameNumManage__c tempFnm = new FrameNumManage__c();
            for (Integer j = 0; j < importLabelList.size(); j++) {
                String api = labelToApiMap.get(importLabelList[j]);
                if (queryFrameNumFieldMap.containsKey(api) == false) {
                    throw new ControllerUtil.myException('字段:【' + importLabelList[j] + '】在' + FrameNumManage__c.getSObjectType().getDescribe().getLabel() + '里不存在, 请确认。');
                }
                DescribeFieldResult queryAssetFieldResult = queryFrameNumFieldMap.get(api).getDescribe();
                if (String.isNotBlank(tempCsvBody[i][j])){
                    String value = String.valueOf(tempCsvBody[i][j]).trim();
                    if (queryAssetFieldResult.getType() == Schema.DisplayType.Date) {
                        value = value.replace('/', '-');
                        tempFnm.put(api, Date.valueOf(value));
                    } else if (queryAssetFieldResult.getType() == Schema.DisplayType.Boolean) {
                        tempFnm.put(api, Boolean.valueOf(value));
                    } else if (queryAssetFieldResult.getType() == Schema.DisplayType.Double) {
                        tempFnm.put(api, Decimal.valueOf(value));
                    } else {
                        tempFnm.put(api, value);
                    }
                }
            }

            String managementCode = tempFnm.ManagementCode__c;
            String key = tempFnm.SerialNumber__c+'('+tempFnm.ManagementCode__c+')';
            tempFnm.SerialNumberS__c = key;
            tempFnm.name = tempFnm.ManagementCode__c;
            if(String.isBlank(managementCode)){
                throw new ControllerUtil.myException('【' + queryFrameNumFieldMap.get('ManagementCode__c').getDescribe().getLabel() + '】不可为空' + tempFnm);
            }else if(fnmMap.containsKey(key)){
                throw new ControllerUtil.myException('【' + queryFrameNumFieldMap.get('ManagementCode__c').getDescribe().getLabel() + '】存在多条数据' + tempFnm);
            } else{
                fnmMap.put(key,tempFnm);
            }
        }
        // 执行插入/更新
        if(fnmMap.size() > 0){
            /*List<FrameNumManage__c> tempList = [SELECT Id,SerialNumberS__c FROM FrameNumManage__c WHERE SerialNumberS__c IN :fnmMap.keySet()];
            IF(tempList.size() > 0){
                for(FrameNumManage__c temp:tempList){
                    FrameNumManage__c fnm = new FrameNumManage__c();
                    fnm = fnmMap.get(temp.SerialNumberS__c);
                    fnm.put('Id',temp.Id);
                    fnmMap.put(temp.SerialNumberS__c,fnm);
                }
            }
            Database.UpsertResult[] urList = Database.upsert(fnmMap.values(),FrameNumManage__c.Id,false);
            */
            Database.UpsertResult[] urList = Database.upsert(fnmMap.values(),FrameNumManage__c.SerialNumberS__c,false);
            for (Integer tIdx = 0; tIdx < urList.size(); tIdx++) {
                Database.UpsertResult sr = urList[tIdx];
                if (!sr.isSuccess()) {
                    String errStr = '';
                    Database.Error emsg = sr.getErrors()[0];
                    errStr = emsg.getMessage();
                    warningList.add(errStr);
                }else{
                    importLine++;
                }
            }
             
            for(Integer i = 0; i < Math.min(5, warningList.size()); i++){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.WARNING, warningList[i]));
            }
            if (warningList.size() > 0) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.WARNING, warningList.size() + '条记录插入/更新失败'));
            }
            if(importLine == 0) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.WARNING, '未导入任何数据，请检查CSV文件'));
            }
            else {
                String importSuccessfulMsg = '导入CSV文件完成，成功导入' + importLine + '条数据。';
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.INFO, importSuccessfulMsg));
                // 调用batch
                Database.executeBatch(new SetFrameNumManageBatch(), 100);
            }
        }
    }
    private Map<String, String> createLabelApiMap(){
        Map<String,String> apiMap = new Map<String,String>();
        Map<String,Schema.SObjectField> mfields = FrameNumManage__c.sObjectType.getDescribe().fields.getMap();
        for(String strField:mfields.keySet()) {
            SObjectField fl = mfields.get(strField);
            apiMap.put(fl.getDescribe().getlabel(), strField);
        }
        return apiMap;
    }
}