public with sharing class DataLoadAccountController {

	public List<String> StringList {get; set;}

	public String  campaignId {get; set;}

	public List<CampaignRelationship__c> CRList {get; set;}

	public List<AccountContactInfo> ACInfoList {get; set;}
	public Blob contentFile { get; set; }
	public String nameFile { get; set; }

	public Boolean errorFlag { get; set; }
	public String errorMessage {get; set;}

    public Map<String, List<Contact>> upsertContactMap;
    public Map<String, Account> upsertAccountMap;
    public Map<String,Account> accountMap;
    public Map<String,String> accountIsUpdateMap;
    public Map<String,String> accountInDealerMap;


    private Integer line_Account_ProductSegment = 0;//分野
    private Integer line_Account_accountName = 1;//客户名
    private Integer line_Account_DivisionName_D = 2;//部门
    private Integer line_Account_approver = 3;//审批人
    private Integer line_Account_Province = 4;//省
    private Integer line_Account_CityD = 5;//市
    private Integer line_Account_Address1D = 6;//客户地址
    private Integer line_Account_PostCodeD = 7;//客户邮编
    private Integer line_Account_Sub_UseD = 8;//客户Sub_Use;
    private Integer line_Account_EnglishNameD = 9;//客户英文名称(IE)
    private Integer line_Account_CustomerSource = 10;//客户来源
    private Integer line_Account_UserType = 11;//用户属性
    private Integer line_Account_TargetCustomer = 12;//客户类型
    private Integer line_Account_Remark = 13;//客户备注
    private Integer line_Contact_LastName = 14;//联系人姓名
    private Integer line_Contact_Address1D = 15;//联系人地址
    private Integer line_Contact_MobilePhoneD = 16;//联系人手机
    private Integer line_Contact_PostcodeD = 17;//联系人邮编
    private Integer line_Contact_Remark = 18;//联系人备注
    private Integer line_nineteen;

    public String baseUrl { get; set; }

	public DataLoadAccountController() {

        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0, path.indexOf('/apex'));
        }
		campaignId = System.currentPageReference().getParameters().get('campaignId');
		ACInfoList = new List<AccountContactInfo>();
	}

	public PageReference init() {
		ACInfoList = new List<AccountContactInfo>();
		return null;
	}

	public PageReference csvRead() {

		String strFile = '';
		List<String> listFile = new List<String>();
		errorFlag = false;
		errormessage = null;

        List<String> errormessageList = new List<String>();
        Map<String, List<String>> errormessageMap = new Map<String, List<String>>();
		try {
			if (contentFile != null) {
				strFile = contentFile.toString();
				listFile = strFile.split('\n');
			} else {
				errorFlag = true;
				errormessage = '读取内容为空。';
                errormessageList.add(errormessage);
                errormessageMap.put('导入文件异常', errormessageList);
                Pageerrormessage(errormessageMap);
				return null;
			}
		} catch (Exception ex) {
			errorFlag = true;
            errormessage = '读取的文件不是CSV文件或CSV文件的编码不是UTF-8';
            errormessageList.add(errormessage);
            errormessageMap.put('导入文件异常', errormessageList);
            Pageerrormessage(errormessageMap);
			return null;
		}

		List<String[]> arrayFile = new List<String[]>();
		String firstline = listFile[0];
		if (firstline.indexOf('客户分野') < 0) {
			errorFlag = true;
			errormessage = '读取内容格式不正确。';
            errormessageList.add(errormessage);
            errormessageMap.put('导入文件异常', errormessageList);
            Pageerrormessage(errormessageMap);
			return null;
		} else {
			String strReplace = '';
			List<String> temp = strFile.split('"');
			for (Integer i = 0; i < temp.size(); i++) {
				if (math.mod(i, 2) == 1) {
					temp[i] = temp[i].replace(',', '#%&');
				}
				strReplace += temp[i];
			}
			// system.debug('=====strReplace:' + strReplace);
			List<String> listReplace = strReplace.split('\n');
			for (String replace : listReplace) {
				system.debug('=====replace:' + replace);
				if (replace != '\r' && replace.length() > 0) {
					replace = replace.replace('\r', '');
					String[] a = replace.split(',', -1);
					for (Integer i = 0; i < a.size(); i++) {
						if (a[i].indexOf('#%&') > 0) {
							a[i] = a[i].replace('#%&', ',');
						}
					}
					// 验证导入的模板有多少列
					if (a.size() != 19) {
						errorFlag = true;
						errormessage = '读取内容格式不正确。Line：' + arrayFile.size();
                        errormessageList.add(errormessage);
                        errormessageMap.put('导入文件异常', errormessageList);
                        Pageerrormessage(errormessageMap);
						return null;
					}
					
					arrayFile.add(a);
				}
			}
		}

		if (arrayFile.size() > 1) {

			checkFields(arrayFile);
		}
        
		return null;
	}

    public PageReference save() {
        system.debug('upsertAccountMap-----><----' + upsertAccountMap);

        Savepoint sp = Database.setSavepoint();
        // try {
            List<CampaignRelationship__c> insertCampaignRelationshipList = new List<CampaignRelationship__c>();
            if (upsertAccountMap != null && upsertAccountMap.size() > 0) {

                // 保存客户
                upsert upsertAccountMap.values();
                List<Contact> upsertContactList = new List<Contact>();
                Map<String,Contact> insertContactMap = new Map<String,Contact>();
                for (String accountkey : upsertAccountMap.keySet()) {
                    String productSegment = upsertAccountMap.get(accountkey).ProductSegment__c;
                    String accountId = upsertAccountMap.get(accountkey).Id;
                    if (upsertContactMap != null && upsertContactMap.size() > 0) {
                        if (upsertContactMap.containsKey(accountkey)) {
                            // 给联系人赋值客户Id
                            for (Contact contact : upsertContactMap.get(accountkey)) {
                                if (String.isNotBlank(contact.LastName)) {
                                    contact.CampaignUpsertContact__c = true;
                                    if (String.isBlank(contact.Id)) {
                                        contact.AccountId = accountId;
                                        upsertContactList.add(contact);
                                    } else {
                                        insertContactMap.put(contact.Id, contact);
                                    }
                                    
                                    // upsertContactList.add(contact); 
                                }
                                
                            }
                        }
                    }

                    String accountName = upsertAccountMap.get(accountkey).FacilityNameD__c;
                    String divisionName = upsertAccountMap.get(accountkey).DivisionName_D__c;
                    String accountAssemblyName = accountName + divisionName;
                    // 若客户已存在，创建客户-市场活动关系，若客户不存在，那么客户创建完成之后，会在trigger里创建客户-市场活动关系
                    if ( accountMap != null && accountMap.containsKey(accountAssemblyName)) {
                        
                        CampaignRelationship__c campaignRelationship = campaignRelationshipAssembly(accountId,productSegment);
                        
                        insertCampaignRelationshipList.add(campaignRelationship);
                    }
                    
                }
                

                // 保存联系人
                // if (upsertContactMap != null && upsertContactMap.size() > 0) {
                //     // upsert upsertContactMap.values();
                //     Integer Error01 = Integer.valueOf('TEST--->'+upsertContactMap);
                // }
                if (upsertContactList.size() > 0) {
                    upsert upsertContactList;
                }

                if (insertContactMap != null && insertContactMap.size() >0) {
                    update insertContactMap.values();
                }
            
            } 
            // 若客户已在代理商下，那么创建客户-市场活动关系
            if (accountInDealerMap != null && accountInDealerMap.size() > 0) {

                for (String accountId : accountInDealerMap.keySet()) {
                    CampaignRelationship__c campaignRelationship = campaignRelationshipAssembly(accountId,accountInDealerMap.get(accountId));
                    insertCampaignRelationshipList.add(campaignRelationship);
                }
            }

            // 保存客户-市场活动关系
            if (insertCampaignRelationshipList.size() > 0) {
                insert insertCampaignRelationshipList;
            }
        // } catch (Exception e) {
        //     errorFlag = true;
        //     ApexPages.addMessages(e);
        //     Database.rollback(sp);
        //     return  null;
        // }
        return null;
    }
    // 客户-市场活动关系 赋值
    public CampaignRelationship__c campaignRelationshipAssembly(String accountId,String productSegment){
        CampaignRelationship__c result = new CampaignRelationship__c();
        result.RelationshipAccount__c = accountId;
        result.RelationshipCampaign__c = campaignId;
        result.RelationshipProductSegment__c = productSegment;
        return result;
    }
    // 数据验证及数据拼装
	public void checkFields(List<String[]> arrayFile) {
		Integer no = 1;
		AccountContactInfo ifno = new AccountContactInfo(no);
        // 查找审批人
		Map<String,User> userMap = getUser(arrayFile);

        accountMap = new Map<String,Account>();
        // 根据导入文件的客户名称与部门名称以及分野，去系统中查找市场部创建的客户
        accountMap = getAccountMap(arrayFile);
        accountIsUpdateMap = new Map<String,String>();
        // 查找客户下的客户团队是否有代理商用户，借此判断客户是否在代理商下
        accountIsUpdateMap = getAccountTeamMemberList(accountMap);
        // 查找联系人
        Map<String,Contact> contactMap = getContactMap(accountMap);
        // 客户在代理商下
        accountInDealerMap = new Map<String,String>();


		
		String tem = '';

        upsertContactMap = new Map<String, List<Contact>>();
        upsertAccountMap = new Map<String, Account>();
		Map<String, List<String>> errormessageMap = new Map<String, List<String>>();
		for (Integer line = 1; line < arrayFile.size(); line++) {
			List<Contact> countList = new List<Contact>();
			Account account = new Account();
			Contact contact = new Contact();
			// 客户分野不为空
            if (String.isNotBlank(arrayFile[line][line_Account_ProductSegment])) {

				tem = arrayFile[line][line_Account_ProductSegment];
                String accountName= arrayFile[line][line_Account_accountName];
                String divisionName= arrayFile[line][line_Account_DivisionName_D];
				if (String.isNotBlank(accountName) && String.isNotBlank(divisionName)) {
					tem += ':' + accountName + divisionName;
				} else {
                    Integer fileNo = line+1;
					List<String> errormessageList = new List<String>();
					errormessageList.add( '导入文件第 [ ' + fileNo + ' ] 行 客户名称或部门名称为空，请确认，此条客户与联系人跳过');
                    tem += '-' + fileNo;
					errormessageMap.put(tem,errormessageList);
					continue;
				}
                // 验证客户是否符合规则
				if (accountFieldCheck(arrayFile[line], errormessageMap, tem,userMap)) {

					account = accountAssembly(arrayFile[line],userMap);
                    String managementCode  = '';
                    
                    if (accountMap != null && accountMap.size() > 0 ) {
                        String accountId = getAccountId(accountMap,arrayFile[line], errormessageMap, tem);
                        if (String.isNotBlank(accountId)) {
                            account.Id = accountId;
                            
                            String key = accountName + divisionName;
                            managementCode = accountMap.get(key).ManagementCode_F__c;
                        }
                    }

                    // 此处需要处理重名客户
					if (!upsertAccountMap.containsKey(tem)) {
                        // 判断客户是否已在代理商下，在代理商下不更新客户
                        if (accountIsUpdateMap != null && accountIsUpdateMap.size() > 0) {
                            // 客户更新
                            if (String.isNotBlank(account.Id)) {
                                // 判断客户是否已在代理商下，若不在代理商下更新客户基本信息
                                if (!accountIsUpdateMap.containsKey(account.Id)) {
                                    upsertAccountMap.put(tem, account);
                                } else {
                                    
                                    accountInDealerMap.put(account.Id, tem.split(':')[0]);
                                    List<String> errormessageList = new List<String>();
                                    errormessage = '客户名：' + tem.split(':')[1] +divisionName+ ' 客户编码 [ '+managementCode+' ] 已在代理商下；此条客户与联系人不会被更新，仅创建 客户-市场活动关系';
                                    errormessageList.add(errormessage);
                                    errormessageMap.put(tem, errormessageList);
                                    // 若客户在代理商下 ，客户导入页面会显示该客户的信息，但是不会更新客户
                                    // continue;
                                }
                            } else {
                                // 客户新增
                                upsertAccountMap.put(tem, account);
                            }
                            
                        } else {
                            // 客户新增
                            upsertAccountMap.put(tem, account);
                        }
                        
                    } else {
                        List<String> errormessageList = new List<String>();
                        errormessage = '分野：'+ tem.split(':')[0] + '，客户名：' + tem.split(':')[1] + ' 重名，此条客户与联系人跳过';
                        errormessageList.add(errormessage);
                        tem += 'Error';
                        errormessageMap.put(tem, errormessageList);
                        system.debug('tem------>' + tem);
                        continue;
                        
                    }
                    // 判断与客户同一行的联系人字段是否都为空值
					if (FirstContactIsNull(arrayFile[line])) {
	                    ifno = new AccountContactInfo(no, account);
	                    ACInfoList.add(ifno);
	                    no++;
					} else {
                        // 检查联系人字段是否有异常
	                    if (contactFieldCheck(arrayFile[line], errormessageMap, tem)) {
	                        contact = contactAssembly(arrayFile[line], tem);
                            // 若客户在代理商下 客户导入页面会显示联系人信息，但是不会更新联系人信息
                            if (accountInDealerMap != null && accountInDealerMap.size() > 0 && accountInDealerMap.containsKey(account.Id)) {
                                ifno = new AccountContactInfo(no, account, contact);
                                ACInfoList.add(ifno);
                                no++;
                                continue;
                            }
                            if (contactMap != null && contactMap.size() >0) {
                                String contactId = getContactId(account,contactMap,arrayFile[line], errormessageMap, tem);
                                if (String.isNotBlank(contactId)) {
                                    contact.Id = contactId;
                                }
                            }
	                        countList.add(contact);
	                        upsertContactMap.put(tem, countList);
	                        ifno = new AccountContactInfo(no, account, contact);
	                        ACInfoList.add(ifno);
	                        no++;
	                    } else {
							errormessageMap.putAll(errormessageMap);
						}
					}
				} else {
					errormessageMap.putAll(errormessageMap);
				}

				system.debug('tem---->' + tem);
			} else {
                if (upsertAccountMap.containsKey(tem)) {
                    if (contactFieldCheck(arrayFile[line], errormessageMap, tem)) {
                        // 将同一客户下的联系人放到同一个联系人集合中
                        if (upsertContactMap.containsKey(tem)) {
                            contact = contactAssembly(arrayFile[line], tem);
                            account = upsertAccountMap.get(tem);
                            if (contactMap != null && contactMap.size() >0) {
                                String contactId = getContactId(account,contactMap,arrayFile[line], errormessageMap, tem);
                                if (String.isNotBlank(contactId)) {
                                    contact.Id = contactId;
                                }
                            }
                            List<Contact> contacts = upsertContactMap.get(tem);
                            contacts.add(contact);
                            upsertContactMap.put(tem, contacts);
                            
                            ifno = new AccountContactInfo(no, account, contact);
                            ACInfoList.add(ifno);
                            no++;
                        } else {
                            // 同一客户下的前面的联系人都为空或验证不通过。将剩余符合规则的放入联系人集合中。
                            contact = contactAssembly(arrayFile[line], tem);
                            if (contactMap != null && contactMap.size() >0) {
                                String contactId = getContactId(account,contactMap,arrayFile[line], errormessageMap, tem);
                                if (String.isNotBlank(contactId)) {
                                    contact.Id = contactId;
                                }
                            }
                            countList.add(contact);
                            upsertContactMap.put(tem, countList);
                            account = upsertAccountMap.get(tem);
                            ifno = new AccountContactInfo(no, account, contact);
                            ACInfoList.add(ifno);
                            no++;
                        }

                    } else {
                        errormessageMap.putAll(errormessageMap);
                    }
                }
				

			}
		}
        // 异常信息页面展示
		if (errormessageMap != null && errormessageMap.size() > 0) {
            Pageerrormessage(errormessageMap);
		
		}
	}
    // 异常信息
    public void Pageerrormessage(Map<String, List<String>> errormessageMap) {

        errorFlag = true;
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '以下数据含有异常信息，请确认！！！'));
        for (String key :errormessageMap.keySet()) {
            if (key.indexOf(':') > 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '客户 '+ key.split(':')[1] + '：'));
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '客户 '+ key + '：'));
            }
            for (String errorm :errormessageMap.get(key)){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '--->'  + errorm)); 
            }
            
        }

    }
    // 验证与客户同一行的联系人字段是否都为空
    public Boolean FirstContactIsNull(String[] strList){
        Boolean contactNameflag = String.isBlank(strList[line_Contact_LastName]);
        Boolean contactAddrflag = String.isBlank(strList[line_Contact_Address1D]);
        Boolean contactPhoneflag = String.isBlank(strList[line_Contact_MobilePhoneD]);
        Boolean contactPostflag = String.isBlank(strList[line_Contact_PostcodeD]);

        if (contactNameflag && contactAddrflag && contactPhoneflag && contactPostflag) {
            return true;
        }
        return false;
    }


    // 为联系人字段赋值
	public Contact contactAssembly(String[] strList,String tem) {

		Contact result = new Contact();
		result.LastName = strList[line_Contact_LastName];
		result.FirstName = null;
		result.Address1D__c = strList[line_Contact_Address1D];
		result.MobilePhoneD__c = strList[line_Contact_MobilePhoneD];
		result.PostcodeD__c = strList[line_Contact_PostcodeD];
        result.Remark__c = strList[line_Contact_Remark];
		result.ContactStatusD__c = 'Active';
        //result.StatusD__c = 'Pass';
		if (tem.split(':')[0] == 'IE') {
			result.ProductSegmentIE__c = true;
		} else if (tem.split(':')[0] == 'RVI') {	
			result.ProductSegmentRVI__c = true;
		} else if (tem.split(':')[0] == 'NDT') {
			result.ProductSegmentNDT__c = true;
		} else if (tem.split(':')[0] == 'ANI') {
			result.ProductSegmentANI__c = true;
		}  
		
		return result;
	}
    // 为客户字段赋值
	public Account accountAssembly(String[] strList,Map<String,User> userMap) {

		Account result = new Account();
        String productSegment = strList[line_Account_ProductSegment];
		result.ProductSegment__c = productSegment;
		result.FacilityNameD__c = strList[line_Account_accountName];
        result.FacilityName__c = strList[line_Account_accountName];
		result.Name = '*';
		result.DivisionName_D__c = strList[line_Account_DivisionName_D];
		String approver = strList[line_Account_approver].replaceAll(' ', '');
		result.DealerSelectOwner__c = userMap.get(approver).Id;
		result.Province__c = strList[line_Account_Province];
		result.CityD__c = strList[line_Account_CityD];
		result.Address1D__c = strList[line_Account_Address1D];
		result.PostCodeD__c = strList[line_Account_PostCodeD];
		String subUse = '';
        if ((productSegment != 'IE') && '汽车'.equals(strList[line_Account_Sub_UseD])) {
            subUse = 'Automotive';
        } else if ('其他'.equals(strList[line_Account_Sub_UseD])){
            subUse = 'Others';
        } else {
            subUse = strList[line_Account_Sub_UseD];
        }
		result.Sub_UseD__c = subUse;

		result.AccountCampaign__c = campaignId;
		if ('IE'.equals(productSegment)) {
			result.EnglishNameD__c = strList[line_Account_EnglishNameD];
			result.CustomerSource__c = strList[line_Account_CustomerSource];
			result.UserType__c = strList[line_Account_UserType];
			result.TargetCustomer__c = strList[line_Account_TargetCustomer];
            result.Sub_UseA__c = subUse;
            if(subUse.startsWith('Compo')){
                result.compo_Acc__c = 'COMPO客户';
            }else{
                result.compo_Acc__c = '非COMPO客户';
            }
		}
		
        result.Remark__c = strList[line_Account_Remark];

        result.AccountStatusD__c = 'Active';

        if (productSegment == 'IE') {
            result.recordTypeId = '01228000000TdF6';
        } else if (productSegment == 'RVI') {
            result.recordTypeId = '01228000000TdFB';
        } else if (productSegment == 'NDT') {
            result.recordTypeId = '01228000000TdFG';
        } else if (productSegment == 'ANI') {
            result.recordTypeId = '01228000000TdFL';
        }
		return result;
	}
    // 获取审批人
	public Map<String,User> getUser(List<String[]> arrayFile){
		Map<String,User> result = new Map<String,User>();
		List<String> approverList = new List<String>();
		//查找审批人是否存在
		for (Integer line = 1; line < arrayFile.size(); line++) {
		    //客户分野
		    Boolean productSegment = String.isBlank(arrayFile[line][line_Account_ProductSegment]);
		    //审批人
		    Boolean approver = String.isBlank(arrayFile[line][line_Account_approver]);
		    if (!productSegment && !approver) {
		        approverList.add(arrayFile[line][line_Account_approver]);
		    }
		}

		if (approverList.size() > 0) {

			List<User> userList = [SELECT id,Name,LastName,FirstName 
								   FROM User ];

			if (userList.size() > 0) {
				for (User user :userList) {
					String firstName = String.isBlank(user.FirstName) ? '' :user.FirstName;
					String name = user.LastName + firstName;
					result.put(name,user);
				}
			}
		}

		return result;
	}
    // 导入文件客户字段验证
	public Boolean accountFieldCheck(String[] strList, Map<String, List<String>> errormessageMap, String tem,Map<String,User> userMap) {
		//客户名称
		Boolean dealerNameflag = String.isBlank(strList[line_Account_accountName]);

		//部门名称
		Boolean deptNameflag = String.isBlank(strList[line_Account_DivisionName_D]);
		//审批人
		Boolean approverflag = String.isBlank(strList[line_Account_approver]);
		//省
		Boolean provinceflag = String.isBlank(strList[line_Account_Province]);
		//城市
		Boolean cityflag = String.isBlank(strList[line_Account_CityD]);
		//客户地址
		Boolean addressflag = String.isBlank(strList[line_Account_Address1D]);
		//邮编
		Boolean postflag = String.isBlank(strList[line_Account_PostCodeD]);
		//Sub Use
		Boolean sub_Useflag = String.isBlank(strList[line_Account_Sub_UseD]);
		//客户英文名称(IE验证)
		Boolean accountEnglishNameflag = String.isBlank(strList[line_Account_EnglishNameD]);
		//客户来源(IE验证)
		Boolean customerSourceflag = String.isBlank(strList[line_Account_CustomerSource]);
		//用户属性(IE验证)
		Boolean useRattributeflag = String.isBlank(strList[line_Account_UserType]);
        //客户类型(IE验证)
		Boolean targetCustomerflag = String.isBlank(strList[line_Account_TargetCustomer]);

		Boolean temflag = true;
		String errormessage = '';
		if (tem.indexOf(':') > 0) {
			errormessage = tem.split(':')[1] + '：';
		} else {
			errormessage = tem;
		}

		List<String> errormessageList = new List<String>();

		if (approverflag) {
			errormessage += ' 客户审批人不能为空，请确认；\n';
			temflag = false;
		} else {
			//验证审批人是否存在
			String approver = strList[line_Account_approver].replaceAll(' ', '');

			if (!userMap.containsKey(approver)){
				errormessage += ' 客户审批人 ['+strList[line_Account_approver]+'] 不存在，请确认；\n';
				temflag = false;
			} 
		}
		if (provinceflag) {
			errormessage += ' 客户省不能为空，请确认；\n';
			temflag = false;
		} else {
			
			Schema.DescribeFieldResult fieldResult = Account.Province__c.getDescribe();

			Map<String,String> accountProvinceMap =  getPickListValuesMap(fieldResult);
			String accountProvince = strList[line_Account_Province];
			if (!accountProvinceMap.containsKey(accountProvince)) {
				errormessage += ' 客户省的值异常，[ '+accountProvince+' ]请确认；\n';
				temflag = false;
			}
		}
		if (cityflag) {
			errormessage += ' 客户城市不能为空，请确认；\n';
			temflag = false;
		}
		if (addressflag) {
			errormessage += ' 客户地址不能为空，请确认；\n';
			temflag = false;
		}
		if (postflag) {
			errormessage += ' 客户邮政编码不能为空，请确认；\n';
			temflag = false;
		} else {
            Pattern pt = Pattern.compile('[0-9]\\d{5}(?!\\d)');
            Matcher mc = pt.matcher(strList[line_Account_PostCodeD]);
            if(!mc.matches()) {
                errormessage += ' 客户邮政编码不是6位数字，[ '+strList[line_Account_PostCodeD]+' ]请确认；\n';
                temflag = false;
            }
		}
		if (sub_Useflag) {
			errormessage += ' Sub Use不能为空，请确认；\n';
			temflag = false;
		} else {
            
            // 判断Sub Use是否符合分野所选值
            String segment = strList[line_Account_ProductSegment];
            String subUse = strList[line_Account_Sub_UseD];
            String key = segment + ':' + subUse;
            if (!SegmentSubUseMap.containsKey(key)) {
                String accountName = strList[line_Account_accountName];
                errormessage += accountName +'- Sub Use [ '+subUse + ' ] 的值无效，请确认；\n';
                temflag = false;
            }
        }
		if (strList[line_Account_ProductSegment] == 'IE') {
			if (accountEnglishNameflag) {
				errormessage += ' 客户的英文名称不能为空，请确认；\n';
				temflag = false;
			}
			if (customerSourceflag) {
				errormessage += ' 客户的客户来源不能为空，请确认；\n';
				temflag = false;
			} else {
				Schema.DescribeFieldResult fieldResult = Account.CustomerSource__c.getDescribe();

				Map<String,String> sourceMap =  getPickListValuesMap(fieldResult);
				String customerSource = strList[line_Account_CustomerSource];
				if (!sourceMap.containsKey(customerSource)) {
					errormessage += ' 客户的客户来源值异常，[ '+customerSource+' ]请确认；\n';
					temflag = false;
				}
			}
			if (useRattributeflag) {
				errormessage += ' 客户的用户属性不能为空，请确认；\n';
				temflag = false;
			} else {
				Schema.DescribeFieldResult fieldResult = Account.UserType__c.getDescribe();

				Map<String,String> userTypeMap =  getPickListValuesMap(fieldResult);
				String userType = strList[line_Account_UserType];
				if (!userTypeMap.containsKey(userType)) {
					errormessage += ' 客户的用户属性值异常，[ '+userType+' ]请确认；\n';
					temflag = false;
				}
			}

			if (targetCustomerflag) {
				errormessage += ' 客户的客户类型不能为空，请确认；\n';
				temflag = false;
			} else {
				Schema.DescribeFieldResult fieldResult = Account.TargetCustomer__c.getDescribe();

				Map<String,String> targetCustomerMap =  getPickListValuesMap(fieldResult);
				String targetCustomer = strList[line_Account_TargetCustomer];
				if (!targetCustomerMap.containsKey(targetCustomer)) {
					errormessage += ' 客户的客户类型值异常，[ '+targetCustomer+' ]请确认；\n';
					temflag = false;
				}
			}

		}
		if (temflag) {
			return true;

		} else {
			errormessageList.add(errormessage);
			errormessageMap.put(tem, errormessageList);
			return temflag;
		}


	}
    // 获取客户Id
    public String getAccountId(Map<String,Account> accountMap,String[] strList,Map<String, List<String>> errormessageMap, String tem) {
        List<String> errormessageList = new List<String>();
        if (errormessageMap != null && errormessageMap.size() >0 && errormessageMap.containsKey(tem)) {
            errormessageList = errormessageMap.get(tem);
        }

        String result = '';
        String accountName = strList[line_Account_accountName];
        String divisionName = strList[line_Account_DivisionName_D];
        String name = accountName + divisionName;

        if (accountMap.containsKey(name)) {
            result = accountMap.get(name).Id;
            String managementCode  = accountMap.get(name).ManagementCode_F__c;
            String errormessage = '客户：'+name+' 系统中已存在，客户编码 [ '+managementCode+' ]，将更新此客户，请注意；\n';
            errormessageList.add(errormessage);
            errormessageMap.put(tem,errormessageList);
        }


        
        return result;

    }
    // 获取联系人Id
    public String getContactId(Account account, Map<String,Contact> contactMap,String[] strList,Map<String, List<String>> errormessageMap, String tem) {
        List<String> errormessageList = new List<String>();
        if (errormessageMap != null && errormessageMap.size() >0 &&  errormessageMap.containsKey(tem)) {
            errormessageList = errormessageMap.get(tem);
        }
        String result = '';
        String accountName = account.FacilityNameD__c;
        String divisionName = account.DivisionName_D__c;
        String accountAssemblyName = accountName + divisionName;

        String contactlastName = strList[line_Contact_LastName].replaceAll(' ', '');

        String key = accountAssemblyName + contactlastName;
        if (contactMap.containsKey(key)) {
            result = contactMap.get(key).Id;
            String managementCode  = contactMap.get(key).ManagementCode_F__c;
            String errormessage = '联系人：'+contactlastName+' 系统中已存在，联系人编码 [ '+managementCode+' ]，将更新此联系人，请注意；\n';
            errormessageList.add(errormessage);
            errormessageMap.put(tem,errormessageList);
        }
        return result;
    }
    // 获取市场战略部创建的客户
    public Map<String,Account> getAccountMap( List<String[]> arrayFile) {

        Map<String,Account> result = new Map<String,Account>();
        List<String> accountNameList = new List<String>();
        String productSegment = '';
        for (Integer line = 1; line < arrayFile.size(); line++) {
            if (String.isNotBlank(arrayFile[line][line_Account_ProductSegment])) {
                productSegment = arrayFile[line][line_Account_ProductSegment];
                String accountName = arrayFile[line][line_Account_accountName];
                String divisionName = arrayFile[line][line_Account_DivisionName_D];
                if (String.isNotBlank(accountName) && String.isNotBlank(divisionName)) {
                    String name = accountName + divisionName;
                    accountNameList.add(name);
                }
            }
        }

        if (accountNameList != null && accountNameList.size() > 0) {
            
             List<Account> accountList =    [SELECT id,Name,DivisionName_D__c,ProductSegment__c,createddate,OwnerId ,ManagementCode_F__c from Account where MarketingStrategyCreated__c = true AND Name = :accountNameList AND ProductSegment__c = :productSegment];

            if ( accountList.size() > 0) {
                for (Account account :accountList) {
                    result.put(account.Name, account);
                }
            }
        }

        return result;
    }
    // 查找市场战略部创建的客户下的联系人
    public Map<String,Contact> getContactMap(Map<String,Account> accountMap) {

        if (accountMap != null && accountMap.size() > 0) {

            Map<String,Contact> result = new Map<String,Contact>();
            List<String> accountIdList = new List<String>(); 
            for (String name : accountMap.keySet()) {

                String accountId = accountMap.get(name).Id;
                accountId = accountId.subString(0,15);
                accountIdList.add(accountId);
            }

            List<Contact> contactList = [ SELECT Id,ManagementCode_F__c,Name__c,AccountId__c,Account.Name from Contact where AccountId__c In :accountIdList Order by AccountId__c,Id];

            if (contactList.size() > 0) {

                for (Contact contact :contactList) {
                    String accountNameAndContactName = contact.Account.Name + contact.Name__c;
                    result.put(accountNameAndContactName,contact);
                }
            }
            return result;
        }

        return null;
        
    }

    // 查找客户下的客户团队中，是否有代理商用户
    public Map<String,String> getAccountTeamMemberList(Map<String,Account> accountMap) {
        
        if (accountMap != null && accountMap.size() > 0) {
            Map<String,String> result = new Map<String,String>();
            List<String> accountIdList = new List<String>(); 
            for (String name : accountMap.keySet()) {

                String accountId = accountMap.get(name).Id;
                accountIdList.add(accountId);
            }

            List<AccountTeamMember> accountTeamMemberList = [ SELECT Id, AccountId,Account.Name, UserId,User.User_Type__c FROM AccountTeamMember where User.User_Type__c = 'PowerPartner' AND AccountId in :accountIdList];
            if (accountTeamMemberList.size() > 0) {
                for (AccountTeamMember accountTeamMember :accountTeamMemberList) {
                    result.put(accountTeamMember.AccountId,accountTeamMember.UserId);
                }
                
            }
            return result;
        }

        return null;
    }

    // 验证导入文件的联系人数据
	public Boolean contactFieldCheck(String[] strList, Map<String, List<String>> errormessageMap, String tem) {

		Boolean contactNameflag = String.isBlank(strList[line_Contact_LastName]);
		Boolean contactAddrflag = String.isBlank(strList[line_Contact_Address1D]);
		Boolean contactPhoneflag = String.isBlank(strList[line_Contact_MobilePhoneD]);
		Boolean contactPostflag = String.isBlank(strList[line_Contact_PostcodeD]);
		
		List<String> errormessageList = new List<String>();
		if (errormessageMap != null && errormessageMap.size() > 0 && errormessageMap.containsKey(tem)) {
            errormessageList = errormessageMap.get(tem);
        }
		if (contactNameflag && ( !contactAddrflag || !contactPhoneflag || !contactPostflag)) {
			String errormessage = '联系人的姓氏不能为空，请确认；\n';
			errormessageList.add(errormessage);
			errormessageMap.put(tem, errormessageList);
			return false;
		} else if (!contactNameflag) {
			Boolean temflag = true;
			String contactName = strList[line_Contact_LastName];
			String errormessage = contactName + '：';
			if (contactAddrflag) {
				errormessage += ' 联系人地址不能为空，请确认；\n';
				temflag = false;
			}
			if (contactPhoneflag) {
				errormessage += ' 联系人手机不能为空，请确认；\n';
				temflag = false;
			}
			if (contactPostflag) {
				errormessage += ' 联系人邮政编码不能为空，请确认；\n';
				temflag = false;
			} else {
                Pattern pt = Pattern.compile('[0-9]\\d{5}(?!\\d)');
                Matcher mc = pt.matcher(strList[line_Contact_PostcodeD]);
                if(!mc.matches()) {
                    errormessage += ' 联系人邮政编码不是6位数字，[ '+strList[line_Contact_PostcodeD]+' ]请确认；\n';
                    temflag = false;
                }
            }

			if (temflag) {
				return true;
			} else {
				errormessageList.add(errormessage);
				errormessageMap.put(tem, errormessageList);
				return temflag;
			}

		} else {
			return false;
		}

	}

	class AccountContactInfo {
		public Integer lineNo { get; set; }
		public Account accountpage {get; set;}

		public Contact contactpage {get; set;}

		public AccountContactInfo(Integer line) {

		}
        // 客户数据正常但与客户同一行的联系人数据异常
        public AccountContactInfo(Integer line, Account account) {
            lineNo = line;
            accountpage = account;
        }
        // 客户数据与客户同一行的联系人数据都正常
		public AccountContactInfo(Integer line, Account account, Contact contact) {
			lineNo = line;
			accountpage = account;
			contactpage = contact;
		}
	}
	/**
     * 获取一个对象某个选项列表的全部值
     * @Author   XHL
     * @DateTime 2019-09-18
     * @param    fieldResult Schema.DescribeFieldResult fieldResult = Account.Use__c.getDescribe();
     *                       例：获取客户Use字段选项列表的值
     * @return               [description]
     */
    public  Map<String,String> getPickListValuesMap(Schema.DescribeFieldResult fieldResult){
        Map<String,String> pickListValuesMap= new Map<String,String>();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple)
        {
            pickListValuesMap.put(pickListVal.getValue(),pickListVal.getLabel());
        }
        return pickListValuesMap;
    }

    // 验证各个分野的sub Use是否符合要求
    private  Map<String, String> SegmentSubUseMap = new Map<String, String> {
        // IE
        'IE:LED' => 'LED',
        'IE:FPD' => 'FPD',
        'IE:半导体' => '半导体',
        'IE:电子部品' => '电子部品',
        'IE:太阳能' => '太阳能',
        'IE:电子类_其他' => '电子类_其他',
        'IE:金属' => '金属',
        'IE:汽车' => '汽车',
        'IE:石油地质' => '石油地质',
        'IE:五金模具' => '五金模具',
        'IE:重工设备' => '重工设备',
        'IE:材料类_其他' => '材料类_其他',
        // ANI
        'ANI:其他' => '其他',
        'ANI:废旧金属' => '废旧金属',
        'ANI:炼钢厂' => '炼钢厂',
        'ANI:PMI-石化行业' => 'PMI-石化行业',
        'ANI:PMI-管道制造' => 'PMI-管道制造',
        'ANI:PMI-金属制造' => 'PMI-金属制造',
        'ANI:PMI-电力' => 'PMI-电力',
        'ANI:RoHS' => 'RoHS',
        'ANI:ELV' => 'ELV',
        'ANI:玩具&皮革' => '玩具&皮革',
        'ANI:贵金属-制造' => '贵金属-制造',
        'ANI:贵金属-回收' => '贵金属-回收',
        'ANI:勘探-政府' => '勘探-政府',
        'ANI:勘探-矿业公司' => '勘探-矿业公司',
        'ANI:Mining-冶炼' => 'Mining-冶炼',
        'ANI:Mining-开采' => 'Mining-开采',
        'ANI:EPA' => 'EPA',
        'ANI:土壤修复' => '土壤修复',
        'ANI:土壤研究' => '土壤研究',
        'ANI:考古&文物' => '考古&文物',
        'ANI:录井' => '录井',
        'ANI:制药' => '制药',
        'ANI:三元催化剂' => '三元催化剂',
        'ANI:Thermal Power' => 'Thermal Power',
        'ANI:Nuclear Power' => 'Nuclear Power',
        'ANI:Wind Power' => 'Wind Power',
        'ANI:Power(other)' => 'Power(other)',
        // NDT
        'NDT:汽车' => '汽车',
        'NDT:Civil Aviation' => 'Civil Aviation',
        'NDT:Security/Defense' => 'Security/Defense',
        'NDT:Oil,Gas&Chemical' => 'Oil,Gas&Chemical',
        'NDT:General Manufacturing' => 'General Manufacturing',
        'NDT:Inspection/Service/Rental' => 'Inspection/Service/Rental',
        'NDT:其他' => '其他',
        'NDT:Thermal Power' => 'Thermal Power',
        'NDT:Nuclear Power' => 'Nuclear Power',
        'NDT:Wind Power' => 'Wind Power',
        'NDT:Power(other)' => 'Power(other)',
        // RVI
        'RVI:汽车' => '汽车',
        'RVI:Civil Aviation' => 'Civil Aviation',
        'RVI:Security/Defense' => 'Security/Defense',
        'RVI:Oil,Gas&Chemical' => 'Oil,Gas&Chemical',
        'RVI:General Manufacturing' => 'General Manufacturing',
        'RVI:Inspection/Service/Rental' => 'Inspection/Service/Rental',
        'RVI:其他' => '其他',
        'RVI:Thermal Power' => 'Thermal Power',
        'RVI:Nuclear Power' => 'Nuclear Power',
        'RVI:Wind Power' => 'Wind Power',
        'RVI:Power(other)' => 'Power(other)'
    };

}