public without sharing class AgencyHospitalLinkController {
    public String accountId { get; set; }

    public String area { get; set; }
    public String city { get; set; }

    public Integer hospitalInfoRecoedsviewCount { get; set; }
    //全部医院
    private List<HospitalInfo> hospitalInfoRecords  = new List<HospitalInfo>();
    //页面显示的医院数据
    public List<HospitalInfo> hospitalInfoRecordsview { get; set; }
    private List<Id> delAgencyLinkId = new List<Id>();
    //医院名
    public String category1 { get; set; }
    //区县
    public String category3 { get; set; }
    //public String alertMessage { get; set; }
    //public Integer delAgencyLinkSize { get; set; }
    public List<SelectOption> cityOpts { get; set; }
    private Map<Id, Agency_Hospital_Link__c> selectedIdMap = new Map<Id, Agency_Hospital_Link__c>();

    //page
    Public Integer pagesize{get; set;}
    Public Integer totalcount{get; set;}
    Public Integer pagecount{get; set;}
    Public Integer currentpage{get; set;}
    public Boolean hasPrevious{get; set;}
    public Boolean hasNext{get; set;}

    public Boolean allSave {get;set;}

    public AgencyHospitalLinkController() {
        accountId = ApexPages.currentPage().getParameters().get('userid');
        hospitalInfoRecordsview = new List<HospitalInfo>();
        hospitalInfoRecords = new List<HospitalInfo>();
        //delAgencyLinkId = new List<Id>();

        //page
        pagesize = Integer.valueof(system.label.orderdetLimitsize);
        currentpage = 0;
    }


    public void init(){
        delAgencyLinkId = new List<Id>();
        //经销商
        Account agencyInfo = [SELECT id, Name, State_Master__c, State_Master__r.Name FROM account WHERE id =:accountid];

        area = agencyInfo.State_Master__r.Name;

        selectedIdMap = new Map<Id, Agency_Hospital_Link__c>();
        List<HospitalInfo> reSet = new List<HospitalInfo>();

        //该经销商已选的医院
        List<Agency_Hospital_Link__c> ahlList = [select Id,
                //Name,
                Hospital__c,
                // 2019-08-19 韩部长 修改经销商医院页面 start
                AgencyHos_ET__c,
                AgencyHos_ENG__c,
                // 2019-08-19 韩部长 修改经销商医院页面 end
                //Hospital__r.Id,
                //Hospital__r.Name,
                //Hospital__r.Management_Code__c,
                //Hospital__r.State_Master__r.Name,
                //Hospital__r.City_Master__r.Name,
                //Hospital__r.OCM_Category__c,
                //Hospital_Name_readonly__c,
                Agency__c,
                Agency_Campaign_Obj__c
        from Agency_Hospital_Link__c
        WHERE Agency__c = :accountId
        order by Hospital__r.State_Master__r.Name];
        for(Integer i = 0; i < ahlList.size(); i++){
            selectedIdMap.put(ahlList[i].Hospital__c, ahlList[i]);

            //reSet.add(new HospitalInfo(ahlList[i]));
        }

        hospitalInfoRecords = new List<HospitalInfo>();
        //hospitalInfoRecords = reSet;

        String soql = this.makeSoql(area,city,category1,category3);

        List<Account> queryList = Database.query(soql);

        for(Account act : queryList){
            HospitalInfo hosp = new HospitalInfo(act);

            if(selectedIdMap.containsKey(act.Id)){
                hosp.check =true;
                hosp.oldCheck =true;
                hosp.esd = selectedIdMap.get(act.Id);
            }
            //else{
            //    hospitalInfoRecords.add(new HospitalInfo(act));
            //    if(hospitalInfoRecords.size() >= 3000) break;
            //}

            hospitalInfoRecords.add(hosp);
        }
     
        hospitalInfoRecords.sort();

        //总件数
        totalcount = hospitalInfoRecords.size();
        //页数
        pagecount=(totalcount  +  pagesize  - 1) / pagesize;
        //显示第一页
        moveToFirst();
        makepagerecords();
        area = '';
        cityOpts = new List<SelectOption>();
        cityOpts.add(new SelectOption('', '--无--'));

    }

    public void cityload() {
        AggregateResult[] cityList = [select Count(id), Name city from Address_Level2__c WHERE Level1_Name__c = :area group by Name];
        cityOpts = new List<SelectOption>();
        cityOpts.add(new SelectOption('', '--无--'));
        for(AggregateResult citySerach : cityList) {
            String citycnt = String.valueOf(citySerach.get('city'));
            cityOpts.add(new SelectOption(citycnt,citycnt));
        }

    }

    public void CheckHospitalInfo(){
        // 为什么要删除已经存在的其他经销商医院？？ 20191015 Gzw删除
        // delAgencyLinkId = new List<Id>();
        // Map<Id,Id> agencyedHospitalMap = new Map<Id,Id>();
        // //已经被经销商选择的医院
        // List<Agency_Hospital_Link__c> AgencyedHospitalList = [select Id,
        //                                                 Name,
        //                                                 Hospital__c,
        //                                                 Hospital__r.Id,
        //                                                 Hospital__r.Name,
        //                                                 Agency__c
        //                                                 // 2019-08-19 韩部长 修改经销商医院页面 start
        //                                                 ,AgencyHos_ET__c,
        //                                                 AgencyHos_ENG__c
        //                                                  // 2019-08-19 韩部长 修改经销商医院页面 end
        //                                         from Agency_Hospital_Link__c
        //                                         where Agency__c != :accountId];
        // for(Agency_Hospital_Link__c ahlc : AgencyedHospitalList){
        //     agencyedHospitalMap.put(ahlc.Hospital__c, ahlc.Id);
        // }

        // if(!allSave){
        //     for(HospitalInfo hosinfo:hospitalInfoRecordsview){
        //         if(hosinfo.check == true){
        //             if(agencyedHospitalMap.containsKey(hosinfo.acc1.Id)){
        //                 delAgencyLinkId.add(agencyedHospitalMap.get(hosinfo.acc1.Id));
        //             }
        //         }
        //     }
        // }else{
        //     for(HospitalInfo hosinfo:hospitalInfoRecords){
        //         if(agencyedHospitalMap.containsKey(hosinfo.acc1.Id)){
        //             delAgencyLinkId.add(agencyedHospitalMap.get(hosinfo.acc1.Id));
        //         }
        //     }
        // }
        // delAgencyLinkSize = delAgencyLinkId.size();
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '你所选择的' + delAgencyLinkSize));
    }

    public PageReference save() {
        List<Agency_Hospital_Link__c> Ins = new List<Agency_Hospital_Link__c>();
        //List<Agency_Hospital_Link__c> delAgencyLinks = New List<Agency_Hospital_Link__c>();
        List<Agency_Hospital_Link__c> dels = New List<Agency_Hospital_Link__c>();
        List<Id> delIds = new List<Id>();
        Savepoint sp = Database.setSavepoint();
        try{
            if(!allSave){
                //不是全部保存 只保存每页勾选的数据
                for(HospitalInfo hosinfo:hospitalInfoRecordsview){
                    if(hosinfo.check == true){
                        // if(hosinfo.oldCheck == false){
                        Agency_Hospital_Link__c ahl = new Agency_Hospital_Link__c();
                        ahl.Id = hosinfo.esd.Id;
                        ahl.Hospital__c = hosinfo.acc1.Id;
                        ahl.Agency__c = accountId;
                        ahl.AgencyHos_ET__c = hosinfo.esd.AgencyHos_ET__c;
                        ahl.AgencyHos_ENG__c = hosinfo.esd.AgencyHos_ENG__c;
                        ahl.Agency_Campaign_Obj__c = hosinfo.esd.Agency_Campaign_Obj__c;
                        Ins.add(ahl);
                        // }
                    }else{
                        System.debug('软删除+++');
                        // 20191015 修改为软删除 Agency_Campaign_Obj__c = false;
                        if(hosinfo.oldCheck == true){
                            Agency_Hospital_Link__c ahl = new Agency_Hospital_Link__c();
                            ahl.Id = hosinfo.esd.Id;
                            ahl.Hospital__c = hosinfo.acc1.Id;
                            ahl.Agency__c = accountId;
                            ahl.AgencyHos_ET__c = hosinfo.esd.AgencyHos_ET__c;
                            ahl.AgencyHos_ENG__c = hosinfo.esd.AgencyHos_ENG__c;
                            ahl.Agency_Campaign_Obj__c = hosinfo.esd.Agency_Campaign_Obj__c;
                            Ins.add(ahl);
                        }
                    }
                }

            }else{
                //  全部保存，保存所有搜索出来的数据
                for(HospitalInfo hosinfo:hospitalInfoRecords){
                    if(hosinfo.check == true){
                        Agency_Hospital_Link__c ahl = new Agency_Hospital_Link__c();
                        ahl.Id = hosinfo.esd.Id;
                        ahl.Hospital__c = hosinfo.acc1.Id;
                        ahl.Agency__c = accountId;
                        ahl.AgencyHos_ET__c = hosinfo.esd.AgencyHos_ET__c;
                        ahl.AgencyHos_ENG__c = hosinfo.esd.AgencyHos_ENG__c;
                        ahl.Agency_Campaign_Obj__c = hosinfo.esd.Agency_Campaign_Obj__c;
                        Ins.add(ahl);
                        hosinfo.check = true;
                        hosinfo.oldCheck = true;
                     }
                }
            }
            System.debug('Ins.size()'+Ins.size());

            // 为什么要删除已经存在的其他经销商医院？？ 20191015 Gzw删除
            // if(delAgencyLinkId.size() >0){
            //     delAgencyLinks = [SELECT Id FROM Agency_Hospital_Link__c WHERE Id in :delAgencyLinkId];
            // }

            // if(delIds.size() >0){
            //     dels = [SELECT Id FROM Agency_Hospital_Link__c WHERE Id in :delIds];
            // }

            // if(delAgencyLinks.size() >0){
            //     delete delAgencyLinks;
            // }
            // if (dels.size()>0){
            //     delete dels;
            // }
            if(Ins.size()>0){
                upsert Ins;
            }
            searchHospital();
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存完了。'));
            return  null;
            //return ToPage();
        }catch(Exception e){
            ApexPages.addMessages(e);
            Database.rollback(sp);
            return  null;
        }
        return ToPage();

    }

    public PageReference ToPage(){
        PageReference ref = new Pagereference('/apex/AgencyHospitalLink?userid='+accountId);

        ref.setRedirect(true);
        return ref;
    }


    // 检索
    public void searchHospital() {
        hospitalInfoRecords = new List<HospitalInfo>();
        selectedIdMap = new Map<Id, Agency_Hospital_Link__c>();

        String area2 = '%'+area+'%';

        //该经销商已选的医院
        List<Agency_Hospital_Link__c> ahlList = [select Id,
                //Name,
                Hospital__c,
                //Hospital__r.Id,
                //Hospital__r.Name,
                //Hospital__r.Management_Code__c,
                //Hospital__r.State_Master__r.Name,
                //Hospital__r.City_Master__r.Name,
                //Hospital__r.OCM_Category__c,
                //Hospital_Name_readonly__c,
                // 2019-08-19 韩部长 修改经销商医院页面 start
                AgencyHos_ET__c,
                AgencyHos_ENG__c,
                // 2019-08-19 韩部长 修改经销商医院页面 end
                Agency__c,
                Agency_Campaign_Obj__c
        from Agency_Hospital_Link__c
        WHERE Agency__c = :accountId];
    
        for(Integer i = 0; i < ahlList.size(); i++){
            selectedIdMap.put(ahlList[i].Hospital__c, ahlList[i]);
        }

        String soql = this.makeSoql(area,city,category1,category3);
        List<Account> queryList = Database.query(soql);

        for(Account act : queryList){

            HospitalInfo hosp = new HospitalInfo(act);
            if(selectedIdMap.containsKey(act.Id)){
                hosp.check =true;
                hosp.oldCheck =true;
                hosp.esd = selectedIdMap.get(act.Id);
            }

            hospitalInfoRecords.add(hosp);
        }

        hospitalInfoRecords.sort();

        //总件数
        totalcount = hospitalInfoRecords.size();
        //页数
        pagecount=(totalcount  +  pagesize  - 1) / pagesize;
        //显示第一页
        moveToFirst();
        makepagerecords();

    }

    //首页
    public void moveToFirst(){
        if(currentpage == 1) return;
        currentpage = 1;
        canMove();
    }

    //尾页
    public void moveToLast(){
        if(currentpage >= pagecount) return;
        currentpage = pagecount;
        canMove();
    }

    //上一页
    public void moveToPrevious(){
        if(currentpage == 1) return;
        currentpage = currentpage -1;
        canMove();
    }

    //下一页
    public void moveToNext(){
        if(currentpage >= pagecount) return;

        currentpage = currentpage + 1;
        canMove();
    }

    //判断是否可翻页
    public void canMove(){
        hasPrevious = false;
        hasNext = false;
        if(pagecount > 1 && currentpage > 1) hasPrevious = true;
        if(pagecount > 1 && currentpage < pagecount)  hasNext = true;
    }


    //刷新当前页
    public PageReference refreshPageSize() {
        makepagerecords();
        return null;
    }

    public void makepagerecords(){
        Integer startIdx;
        Integer endIdx;
        hospitalInfoRecordsview = new List<HospitalInfo>();

        startIdx = (currentpage-1) * pagesize;
        endIdx = (currentpage-1) * pagesize+ pagesize;
        if (endIdx > hospitalInfoRecords.size()){
            endIdx = hospitalInfoRecords.size();
        }

        for(Integer i=startIdx; i < endIdx ; i++){
            //if(selectedIdMap.containsKey(productInfoList.get(i).pro.Id)){
            //    continue;
            //}
            //else{
            hospitalInfoRecordsview.add(hospitalInfoRecords.get(i));
            //}
        }

        hospitalInfoRecoedsviewCount = hospitalInfoRecordsview.size();
    }


    public String makeSoql(String StateMaster,String CityMaster,String name,String town){
        String RecordTypeId = System.Label.Hospital_RecordType;
        String soql = 'SELECT Id,Name,Management_Code__c,State_Master__c,State_Master__r.Name,City_Master__c,City_Master__r.Name,OCM_Category__c,Town__c FROM account';
        soql += ' WHERE RecordTypeId = \'' +  RecordTypeId + '\'';
        soql += ' AND Is_Active__c = \'有効\'';

        if(!String.isBlank(StateMaster)){
            soql += ' AND State_Master__r.Name = \'' +  StateMaster + '\'';
        }if(!String.isBlank(CityMaster)){
            soql += ' AND City_Master__r.Name = \'' +  CityMaster + '\'';
        }if(!String.isBlank(name)){
            soql += ' AND Name like \'%' + String.escapeSingleQuotes(name.replaceAll('%', '\\%')) + '%\'';
        }if(!String.isBlank(town)){
            soql += ' AND Town__c like \'%' + String.escapeSingleQuotes(town.replaceAll('%', '\\%')) + '%\'';
        }
        soql += ' order by State_Master__r.Name';
        soql += ' limit 1000';
        return soql;
    }


    public static List<SelectOption> getOcmOpts(){
        List<SelectOption> ocmOpts = new List<SelectOption>();
        ocmOpts.add(new SelectOption('','--无--'));
        ocmOpts.add(new SelectOption('SLTV','SLTV'));
        ocmOpts.add(new SelectOption('LTV','LTV'));
        ocmOpts.add(new SelectOption('一般(M0)','一般(M0)'));
        ocmOpts.add(new SelectOption('一般(M1)','一般(M1)'));
        ocmOpts.add(new SelectOption('一般(M2)','一般(M2)'));
        ocmOpts.add(new SelectOption('一般(L)','一般(L)'));
        return ocmOpts;
    }


    public static List<SelectOption> getAreaOpts() {
        List<SelectOption> areaOpts = new List<SelectOption>();
        areaOpts.add(new SelectOption('','--无--'));
        areaOpts.add(new SelectOption('北京市','北京'));
        areaOpts.add(new SelectOption('安徽省','安徽'));
        areaOpts.add(new SelectOption('福建省','福建'));
        areaOpts.add(new SelectOption('甘肃省','甘肃'));
        areaOpts.add(new SelectOption('广东省','广东'));
        areaOpts.add(new SelectOption('海南省','海南'));
        areaOpts.add(new SelectOption('广西自治区','广西'));
        areaOpts.add(new SelectOption('贵州省','贵州'));
        areaOpts.add(new SelectOption('河北省','河北'));
        areaOpts.add(new SelectOption('河南省','河南'));
        areaOpts.add(new SelectOption('黑龙江','黑龙江'));
        areaOpts.add(new SelectOption('湖北省','湖北'));
        areaOpts.add(new SelectOption('湖南省','湖南'));
        areaOpts.add(new SelectOption('吉林省','吉林'));
        areaOpts.add(new SelectOption('江苏省','江苏'));
        areaOpts.add(new SelectOption('江西省','江西'));
        areaOpts.add(new SelectOption('辽宁省','辽宁'));
        areaOpts.add(new SelectOption('内蒙古自治区','内蒙古'));
        areaOpts.add(new SelectOption('宁夏回族自治区','宁夏'));
        areaOpts.add(new SelectOption('青海省','青海'));
        areaOpts.add(new SelectOption('山东省','山东'));
        areaOpts.add(new SelectOption('山西省','山西'));
        areaOpts.add(new SelectOption('陕西省','陕西'));
        areaOpts.add(new SelectOption('上海市','上海'));
        areaOpts.add(new SelectOption('四川省','四川'));
        areaOpts.add(new SelectOption('西藏自治区','西藏'));
        areaOpts.add(new SelectOption('天津市','天津'));
        areaOpts.add(new SelectOption('新疆维吾尔自治区','新疆'));
        areaOpts.add(new SelectOption('云南省','云南'));
        areaOpts.add(new SelectOption('浙江省','浙江'));
        areaOpts.add(new SelectOption('重庆市','重庆'));
        return areaOpts;
    }

    class HospitalInfo implements Comparable{
        public Boolean check { get; set; }
        public Boolean oldCheck { get; set; }
        public Boolean engCheck { get; set; }
        public Boolean etCheck { get; set; }
        public Boolean objCheck { get; set; }
        public Account acc1 { get; set; }
        public Agency_Hospital_Link__c esd { get; set; }

        //新医院
        public HospitalInfo(Account e) {
            check = false;
            oldCheck = false;
            acc1 = e;
            esd = new Agency_Hospital_Link__c();
        }

        /*
        public HospitalInfo(Agency_Hospital_Link__c e) {
            check = true;
            oldCheck = true;
            esd = e;
        }
        */
        public Integer compareTo(Object compareTo) {
            HospitalInfo compareToesd =(HospitalInfo)compareTo;
            Integer returnValue = 0;
            if(check == true){
                returnValue = -1;
            }else{

                returnValue = 1;
            }
            return returnValue;
        }
    }

}