public without sharing class CampaignMemberServiceController {
    public String campaignId { get; set; }
    public String campaignName { get; set; }
    public boolean hasError { get; set; }
    public Campaign cam { get; set; }
    public List<LineInfo> lineInfoList { get; set; }
    public User localuser { get; set; }

    public Integer lineNo { get; set; }
    public String saveflg { get; set; }

    public String errorStr { get; set; }

    public CampaignMemberServiceController() {
        campaignId = ApexPages.currentPage().getParameters().get('id');
    }

    public Integer getLineInfoListSize() {
        return lineInfoList == null ? 0 : lineInfoList.size();
    }

    public void init() {
        hasError = false;

        List<Campaign> camList = [select id, Name, Lesson_Type__c, TrainingType__c
                                  , RecordType.DeveloperName
                                  from Campaign where id = :campaignId];
        if (camList.size() == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '学会不存在。'));
            hasError = true;
            return;
        }
        cam = camList[0];
        campaignName = cam.Name;

        localuser = [select id, State_Hospital__c from User where id = :UserInfo.getUserId()];

        List<CampaignMember__c> cmList = [
                                             select id, Name, Campaign__c, Department__c, Department_ID__c, Opportunity__c, Opportunity_ID__c,
                                             Contact__c, Contact_ID__c, Type__c, Contact_ID__r.Strategic_dept_Class__r.Name
                                             , State__c, City__c // 2018/11/19 HWAG-B399RW 获取参会人员所在省和市
                                             from CampaignMember__c
                                             where Campaign__c = :campaignId];

        lineInfoList = new List<LineInfo>();
        Integer line = 0;
        for (CampaignMember__c cm : cmList) {
            line += 1;
            LineInfo info = new LineInfo(line, cm);
            lineInfoList.add(info);
        }

        if (cmList.size() < 5) {
            for (Integer i = cmList.size(); i < 5; i++) {
                line += 1;
                LineInfo temp = new LineInfo(line);
                temp.cm.Campaign__c = cam.Id;
                lineInfoList.add(temp);
            }
        }

        line += 1;
        LineInfo temp = new LineInfo(line);
        temp.cm.Campaign__c = cam.Id;
        lineInfoList.add(temp);
    }

    public PageReference addLine() {
        Integer nowLine = getLineInfoListSize();
        system.debug('=====before addline:' + lineInfoList.size());
        LineInfo newopi = new LineInfo(nowLine + 1);
        newopi.cm.Campaign__c = cam.Id;

        List<LineInfo> temp = new List<LineInfo>();
        for (LineInfo li : lineInfoList) {
            temp.add(li);
        }
        temp.add(newopi);
        lineInfoList = temp.clone();
        system.debug('=====after addline:' + lineInfoList.size());
        return null;
    }

    public PageReference checkLine() {
        List<LineInfo> temp = new List<LineInfo>();
        for (LineInfo li : lineInfoList) {
            temp.add(li);
        }
        lineInfoList = temp.clone();
        system.debug('=====after checkLine:' + lineInfoList.size());

        if (saveflg == '1') {
            if (errorStr != '') {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, errorStr));
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '保存完了。'));
            }
            hasError = true;
        }
        return null;
    }

    public PageReference deleteLine() {
        Integer rownum = 0;
        List<LineInfo> temp = new List<LineInfo>();
        for (LineInfo li : lineInfoList) {
            if (li.line != lineNo) {
                rownum += 1;
                LineInfo tmp = new LineInfo(rownum, li.cm);
                temp.add(tmp);
            }
        }
        lineInfoList = temp.clone();

        return null;
    }

    public PageReference saveLine() {
        hasError = false;
        List<CampaignMember__c> cmList =
            [ select id,Contact_ID__c
              from CampaignMember__c
              where Campaign__c = :campaignId];

        list<ID> oldcontactIDList = new list<ID>();
        for(CampaignMember__c temCM: cmList)
        {
            oldcontactIDList.add(temCM.Contact_ID__c);
        }
        list<BMEFollowup__c> BMEFlist =
            [ select id
              from BMEFollowup__c
              where Campaign__c = :campaignId];

        List<CampaignMember__c> insertList = new List<CampaignMember__c>();
        List<BMEFollowup__c> insertBMEFList = new List<BMEFollowup__c>();
        map<ID, string> ContactIDtoNameMap =  new map<ID, string>();
        List<Contact> insertContactList = new List<Contact>();
        for (LineInfo li : lineInfoList) {
            if (li.cm.Department__c != null && li.cm.Department_ID__c != null && li.cm.Contact__c != null && li.cm.Contact_ID__c != null) {
                li.cm.Id = null;
                li.cm.Contact_IDService__c = li.cm.Contact_ID__c;
                insertList.add(new CampaignMember__c(Campaign__c = li.cm.Campaign__c,
                    Department__c = li.cm.Department__c,
                    Department_ID__c = li.cm.Department_ID__c,
                    Contact__c = li.cm.Contact__c,
                    Contact_ID__c = li.cm.Contact_ID__c,
                    Contact_IDService__c = li.cm.Contact_IDService__c));
                insertBMEFList.add(new BMEFollowup__c(Campaign__c = campaignId, ContactID__c =  li.cm.Contact_ID__c));
                ContactIDtoNameMap.put(li.cm.Contact_ID__c, li.cm.Contact__c);

            }
        }

        if (ContactIDtoNameMap.size() > 0) {
            insertContactList = ControllerUtil.selectContactForCampaignMember(ContactIDtoNameMap.keySet());
        }

        errorStr = '';
        Savepoint sp = Database.setSavepoint();
        try {
            // 检查同一个人之前是否参加过这一培训类型
            for (Contact temcontact : insertContactList) {
                system.debug('temcontact.campaign__r.Lesson_Type__c:'+temcontact.campaign__r.Lesson_Type__c);
                system.debug('cam.Lesson_Type__c:'+cam.Lesson_Type__c);
                system.debug('temcontact.campaign__r.TrainingType__c:'+temcontact.campaign__r.TrainingType__c);
                system.debug('cam.TrainingType__c:'+cam.TrainingType__c);
                system.debug('temcontact.id:'+temcontact.id);
                system.debug('Contact:'+ContactIDtoNameMap.get(temcontact.id));
                if (temcontact.campaign__c !=null
                        && temcontact.campaign__c != cam.id
                        ) {
                    errorStr += ContactIDtoNameMap.get(temcontact.id) +' ';
                    hasError = true;
                    system.debug('Anydatatype_msg');
                    

                }
            }

            if(hasError) {
                errorStr += '不能重复参加同一培训类型和课程类型的培训。'; 
                return null;
            }
            system.debug('1');
            delete cmList;
            delete BMEFlist;
            //system.debug('=====insertList.size:' + insertList.size());
            system.debug('2');
            system.debug('insertList:'+insertList);
            if (insertList.size() > 0) {
                insert insertList;
            }
            system.debug('3');
            if (insertBMEFList.size() > 0) {
                insert insertBMEFList;
            }
            system.debug('4');
        } catch (System.Exception e) {
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '' + e.getMessage()));
            errorStr = e.getMessage();
            hasError = true;
            return null;
        }
        init();
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '保存完了。'));
        hasError = true;

        return null;
    }

    public class LineInfo {
        public Integer line { get; set; }
        public CampaignMember__c cm { get; set; }

        public LineInfo(Integer in_line) {
            line = in_line;
            cm = new CampaignMember__c();
        }

        public LineInfo(Integer in_line, CampaignMember__c in_cm) {
            line = in_line;
            cm = in_cm;
        }
    }
}