public with sharing class OPDSortManageController {
    public transient Integer year;
    public transient Integer nextyear;
    public transient Integer month;
    public List<OPDPlanInfo> checkedOPDPlan { get; set;}
    public List<OPDPlanInfo> unCheckedOPDPlan { get; set;}
    public String sortTableFlagNtime {get; set;} //2020-12-03  mzy  asc是升序 desc是降序   add
    public String sortTableFlagSort {get; set;} //2020-12-02  mzy  asc是升序 desc是降序   add
    public String sortTableFlagNDetail {get; set;} //2020-12-02  mzy  asc是升序 desc是降序   add
    public String sortKey {get;set;} //2020-12-02 mzy Ntime是(待排序)OPD计划实施日 Sort是优先度 NDetail是(待排序)备品   add 
    public Integer unCheckedOPDPlanCount { 
        get {
            return unCheckedOPDPlan == null ? 0 : unCheckedOPDPlan.size();
        }
    }
    public Integer checkedOPDPlanCount { 
        get {
            return checkedOPDPlan == null ? 0 : checkedOPDPlan.size();
        }
    }
    //检索
    //public String AccountType { get; set; } // 客户类型    2020-11-16  mzy update 检索项  客户类型,客户名(不需要) start
    //public String AccountName { get; set; } //客户名       2020-11-16  mzy update 检索项  客户类型,客户名(不需要) end
    public String Salesdepartment { get; set; } //销售本部
    public String ManProvince { get; set; } //OCMS管理省      // 2020-11-03  mzy  add  添加省份筛选条件
    public String OPDMonth { get; set; } // opd计划月
    //public static List<SelectOption> AccountTypeOption { get; private set; } // 客户类型下拉表
    public transient static List<SelectOption> SalesdepartmentOption { get; private set; } //销售本部下拉表         mzy  update  Lis<SelectOption>
    public transient static List<SelectOption> OPDMonthOption { get; private set; } // opd计划月下拉表
    public transient static List<SelectOption> ManProvinceOption { get; private set; } // OCMS管理省下拉表    mzy update List<SelectOption>
    public transient String rFlag { get; set;}
    /*static {      2020-11-16  mzy update 检索项  客户类型,客户名(不需要) start  
        AccountTypeOption = new List<SelectOption>();
        AccountTypeOption.add(new SelectOption('','-无-'));
        AccountTypeOption.add(new SelectOption('医院','医院'));
        AccountTypeOption.add(new SelectOption('学会会议','学会会议'));
    }           2020-11-16  mzy update 检索项  客户类型,客户名(不需要) end
    */
    // 2020-12-09  mzy  add 用来获取省份对应的公共小组后缀  start
    public transient static Map<String,String> groupsuffixMap {get;private set;} // 用来获取省份对应的公共小组后缀
    static {
        groupsuffixMap = new Map<String,String>();
        groupsuffixMap.put('贵州','X00guizhou');
        groupsuffixMap.put('云南','X00yunnan');
        groupsuffixMap.put('重庆','X00chongqing');
        groupsuffixMap.put('河南','X00henan');
        groupsuffixMap.put('宁夏','X00yinchuan');
        groupsuffixMap.put('青海','X00xining');
        groupsuffixMap.put('陕西','X00shanxixian');
        groupsuffixMap.put('新疆','X00xinjiang');
        groupsuffixMap.put('山西','X00shanxi');
        groupsuffixMap.put('黑龙江','X00heilongjiang');
        groupsuffixMap.put('大连','X00dalian');
        groupsuffixMap.put('吉林','X00jilin');
        groupsuffixMap.put('内蒙','X00neimeng');
        groupsuffixMap.put('青岛','X00qingdao');
        groupsuffixMap.put('山东','X00jinan');
        groupsuffixMap.put('河北','X00hebei');
        groupsuffixMap.put('天津','X00tianjin');
        groupsuffixMap.put('安徽','X00ANHUI');
        groupsuffixMap.put('浙江','X00ZHEJIANG');
        groupsuffixMap.put('江西','X00JIANGXI');
        groupsuffixMap.put('福建','X00FUJIAN');
        groupsuffixMap.put('江苏','X00_LOSH');
        groupsuffixMap.put('四川/西藏','X00_LOOPDXNchuanzang');
        groupsuffixMap.put('上海','X00_LOHD');
        groupsuffixMap.put('沈阳','X00_LODB');
        groupsuffixMap.put('北京','X00_LOHBbeijing');
        groupsuffixMap.put('甘肃','X00_LOXBlanzhou');
        groupsuffixMap.put('湖南','X00hunan');
        groupsuffixMap.put('湖北','X00hubei');
        groupsuffixMap.put('深圳','X00shenzhen');
        groupsuffixMap.put('广西','X00guangxi');
        groupsuffixMap.put('广东','X00_LOHN');
        groupsuffixMap.put('外科事业本部','X00_LOSP');
        groupsuffixMap.put('医疗产品培训本部','X00_LOYLCPPX');
        groupsuffixMap.put('医疗服务本部','X00_LOYLFW');
        groupsuffixMap.put('MA本部','X00_LOMA');
        groupsuffixMap.put('消化·呼吸内镜事业本部','X00_LOGIR');
        //2021-07-23 mzy  SWAG-C548V6 市场企划部 开通OPD排序相关权限 start
        groupsuffixMap.put('市场企划本部','X00_LOSCQH');
        groupsuffixMap.put('消化·呼吸领域解决方案本部','X00_LOXHHXLYJJFA');
        //2021-07-23 mzy  SWAG-C548V6 市场企划部 开通OPD排序相关权限 end
    }

    // 2020-12-09  mzy  add 用来获取省份对应的公共小组后缀  start

    // 2020-11-09 mzy update start  从正式环境获取数据
   /* static {
        SalesdepartmentOption = new List<SelectOption>();
        SalesdepartmentOption.add(new SelectOption('全部','全部'));
        SalesdepartmentOption.add(new SelectOption('1.华北','1.华北'));
        SalesdepartmentOption.add(new SelectOption('2.东北','2.东北'));
        SalesdepartmentOption.add(new SelectOption('3.西北','3.西北'));
        SalesdepartmentOption.add(new SelectOption('4.西南','4.西南'));
        SalesdepartmentOption.add(new SelectOption('5.华东','5.华东'));
        SalesdepartmentOption.add(new SelectOption('6.华南','6.华南'));
        SalesdepartmentOption.add(new SelectOption('医疗产品培训本部','医疗产品培训本部'));
        SalesdepartmentOption.add(new SelectOption('医疗事业推进本部','医疗事业推进本部'));
        SalesdepartmentOption.add(new SelectOption('外科事业本部','外科事业本部')); 
        SalesdepartmentOption.add(new SelectOption('消化·呼吸内镜事业本部','消化·呼吸内镜事业本部')); 
        SalesdepartmentOption.add(new SelectOption('MA本部','MA本部')); 
    }*/
    // 2020-11-09 mzy update  end
    // 2021-03-24  mzy SWAG-BZCAK6 add OPD插队管理  start
    //用来保存是否有权插队
    public transient Boolean JumpCheck {get; set;}
    // 2021-03-24  mzy SWAG-BZCAK6 add OPD插队管理  start


    static {
        OPDMonthOption = new List<SelectOption>();
        OPDMonthOption.add(new SelectOption('1','1'));
        OPDMonthOption.add(new SelectOption('2','2'));
        OPDMonthOption.add(new SelectOption('3','3'));
        OPDMonthOption.add(new SelectOption('4','4'));
        OPDMonthOption.add(new SelectOption('5','5'));
        OPDMonthOption.add(new SelectOption('6','6'));
        OPDMonthOption.add(new SelectOption('7','7'));
        OPDMonthOption.add(new SelectOption('8','8'));
        OPDMonthOption.add(new SelectOption('9','9'));
        OPDMonthOption.add(new SelectOption('10','10'));
        OPDMonthOption.add(new SelectOption('11','11'));
        OPDMonthOption.add(new SelectOption('12','12'));
    }
    // 2020-11-09  mzy add 省份筛选条件更改为 下拉选项
    static {
         //2020-11-11  mzy  add  检索条件下拉列表由后台显示  start
        //OCSM省
         ManProvinceOption = new List<SelectOption>();
         Schema.DescribeFieldResult fieldResult = OPDPlan__c.OCSMManProvinceOption__c.getDescribe();
            List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
            for( Schema.PicklistEntry f : ple)
             {
                 ManProvinceOption.add(new SelectOption(f.getLabel(),f.getLabel()));
            }    
        //销售本部
        SalesdepartmentOption = new List<SelectOption>();
        Schema.DescribeFieldResult fieldResult2 = OPDPlan__c.SalesdepartmentOption__c.getDescribe();
        List<Schema.PicklistEntry> ple2 = fieldResult2.getPicklistValues();
        for( Schema.PicklistEntry f : ple2)
         {
             SalesdepartmentOption.add(new SelectOption(f.getLabel(),f.getLabel()));
        } 
        //2020-11-11  mzy  add  检索条件下拉列表由后台显示  end
    }
    /*static {
        ManProvinceOption = new List<SelectOption>();
        ManProvinceOption.add(new SelectOption('全部','全部'));
        ManProvinceOption.add(new SelectOption('山东','山东'));
        ManProvinceOption.add(new SelectOption('黑龙江','黑龙江'));
        ManProvinceOption.add(new SelectOption('吉林','吉林'));
        ManProvinceOption.add(new SelectOption('江苏','江苏'));
        ManProvinceOption.add(new SelectOption('深圳','深圳'));
        ManProvinceOption.add(new SelectOption('上海','上海'));
        ManProvinceOption.add(new SelectOption('浙江','浙江'));
        ManProvinceOption.add(new SelectOption('福建','福建'));
        ManProvinceOption.add(new SelectOption('广东','广东'));
        ManProvinceOption.add(new SelectOption('广西','广西'));
        ManProvinceOption.add(new SelectOption('大连','大连'));
        ManProvinceOption.add(new SelectOption('安徽','安徽'));
        ManProvinceOption.add(new SelectOption('甘肃','甘肃'));
        ManProvinceOption.add(new SelectOption('沈阳','沈阳'));
        ManProvinceOption.add(new SelectOption('江西','江西'));
        ManProvinceOption.add(new SelectOption('山西','山西'));
        ManProvinceOption.add(new SelectOption('新疆','新疆'));
        ManProvinceOption.add(new SelectOption('湖南','湖南'));
        ManProvinceOption.add(new SelectOption('天津','天津'));
        ManProvinceOption.add(new SelectOption('河南','河南'));
        ManProvinceOption.add(new SelectOption('SP本部','SP本部'));
        ManProvinceOption.add(new SelectOption('云南','云南'));
        ManProvinceOption.add(new SelectOption('湖北','湖北'));
        ManProvinceOption.add(new SelectOption('北京','北京'));
        ManProvinceOption.add(new SelectOption('四川','四川'));
        ManProvinceOption.add(new SelectOption('内蒙古','内蒙古'));
        ManProvinceOption.add(new SelectOption('陕西','陕西'));
        ManProvinceOption.add(new SelectOption('河北','河北'));
        ManProvinceOption.add(new SelectOption('GIR本部','GIR本部'));
        ManProvinceOption.add(new SelectOption('贵州','贵州'));
        ManProvinceOption.add(new SelectOption('重庆','重庆'));
        ManProvinceOption.add(new SelectOption('青海','青海'));
    }*/
    public String opdDelId { get; set; }
    public OPDSortManageController() {
        rFlag  = ApexPages.currentPage().getParameters().get('rFlag');
        Salesdepartment = ApexPages.currentPage().getParameters().get('Salesdepartment');
        ManProvince = ApexPages.currentPage().getParameters().get('ManProvince');
        OPDMonth = ApexPages.currentPage().getParameters().get('OPDMonth');
        sortTableFlagSort = '0';  //2020-12-02 mzy  点击OPD计划实施日/备品优先度/计划出借备品  可以进行排序 add
        sortTableFlagNDetail = '0';  //2020-12-02 mzy  点击OPD计划实施日/备品优先度/计划出借备品 可以进行排序 add
        sortTableFlagNtime = '0'; //2020-12-03 mzy  点击OPD计划实施日 进行排序 add
        sortKey = ''; //2020-12-02 mzy 点击OPD计划实施日/备品优先度可以进行排序 add
        Date dateNow = Date.today();
        this.year = dateNow.year();
        this.month = dateNow.month();
         //2020-12-01  mzy  如果是12月则检索今年一整年+明年1月份的所有OPD计划 add
        if(this.month==12){
            this.month=1;
            this.nextyear = this.year+1;   // 2020-12-01  mzy  如果是12月则检索今年一整年+明年1月份的所有OPD计划 update
        }else{
            this.month +=1;   
        }    
        unCheckedOPDPlan = new List<OPDPlanInfo>();
        checkedOPDPlan = new List<OPDPlanInfo>();
        OPDMonth = this.month.format();
        // 2021-03-24  mzy SWAG-BZCAK6 add OPD插队管理  start
        //插队权限校验
        JumpCheck = false;
        //从OPD计划营业插队小组中查出小组成员,操作人只有是小组成员可以插队
        //1. 公共小组
        //用来存放用户的id
        Map<String,String> IdMap = new Map<String,String>();
        //查询公用小组成员
        List<Group> gList = [ SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = 'OPD营业插队组'];
        if (gList != null && gList.size() > 0) {
            for (Group g : gList) {
                for (GroupMember gm : g.groupMembers) {
                    IdMap.put(gm.userOrGroupId,gm.userOrGroupId);
                }
            }
        }

        //2. 判断有无权限插队
        if(IdMap.get(userInfo.getUserId()) == null){
            JumpCheck = true;
        }
        // 2021-03-24  mzy SWAG-BZCAK6 add OPD插队管理  start

        
    } 
    public void init(){
        if(!String.isBlank(rFlag)){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, rFlag));
            rFlag = null;
        }
        
        //2020-12-09  mzy  update  保存以后,本部需要保持原状 start
        //尝试获取页面上的销售本部参数
        String searchSalesdepartment = ApexPages.currentPage().getParameters().get('Salesdepartment');
        System.debug('页面初始化时--销售本部--未赋值 :'+searchSalesdepartment);
        if(!String.isBlank(searchSalesdepartment)){
             //保存完成后
            Salesdepartment = searchSalesdepartment;
        }else {
            //初始化
            User loginUser = [SELECT Id, Salesdepartment__c FROM User WHERE Id = :userInfo.getUserId()];
             // 2020-11-24  mzy  add  页面初始化时,检索当前登录用户的销售本部,同时检索条件也显示当前用户的销售本部 
            Salesdepartment = loginUser.Salesdepartment__c ;
             System.debug('页面初始化时--销售本部--赋值 :'+loginUser.Salesdepartment__c);
        }
        System.debug('页面初始化时--销售本部--已赋值 :'+Salesdepartment);
        //计划中并且 OPD计划实施日期在下个月 并且  销售本部是 当前登录用户的本部
        //2020-12-09 mzy  update  保存以后,本部需要保持原状 end

        List<OPDPlan__c> OPDPlanList = new List<OPDPlan__c>();
        Map<String, OPDPlanInfo> MidMap = new Map<String, OPDPlanInfo>();
        //2020-12-01 mzy  如果是12月则检索今年一整年+明年1月份的所有OPD计划 update   start
        Date dateNow = Date.today();
        this.year = dateNow.year();
        this.month = dateNow.month();
        //2020-12-01  mzy  如果是12月则检索今年一整年+明年1月份的所有OPD计划 add
        if(this.month==12){
            this.month=1;
            this.nextyear = this.year+1;   // 2020-12-01  mzy  如果是12月则检索今年一整年+明年1月份的所有OPD计划 update
        }else{
            this.month +=1;   
        }
         // 拼凑soql语句
        String soql = 'select Id,Name,OPDPlanSalesdepartment__c,OPDPlanOCM_man_province_Rental__c,AccountOrCampaignName__c,if_OPDTarget__c,Cnt_OPD_ThisYear__c,Cnt_OPD_LastYear__c,Rental_Apply1__c,Rental_Apply2__c,Rental_Apply3__c,Rental_Apply4__c,Rental_Apply5__c,';
        soql += 'Rental_Apply1__r.Name,Rental_Apply1__r.Status__c,Rental_Apply2__r.Name,Rental_Apply2__r.Status__c,Rental_Apply3__r.Name,Rental_Apply3__r.Status__c,Rental_Apply4__r.Name,Rental_Apply4__r.Status__c,Rental_Apply5__r.Name,Rental_Apply5__r.Status__c,';
        soql += 'if_Newest_HaveOpportunity__c,if_HaveOpportunity__c,if_HaveEquipment__c,PlanProdDetail__c,Cnt_Rentals__c,WorkshopPlace__c,Owner.Name,OPDLendSort__c,OPDLendSortDraft__c,OPDPlan_ImplementDate__c,Status__c,IsJump__c,OrderStatusNum__c,JumpCause__c,Campaign__c,AccountType__c,Account_Laboratory__r.Name,IsSaveOrSubmit__c,OPDLendSortBefore__c';
        soql += ' FROM OPDPlan__c where  Status__c = \'计划中\' '; // 2020-12-09  mzy  update 保存完成后,本部维持原状 AND  OPDPlanSalesdepartment__c = \''+loginUser.Salesdepartment__c+'\'
        if(dateNow.month() != 12){
            soql += 'AND CALENDAR_YEAR(OPDPlan_ImplementDate__c)='+year ;
            soql += 'AND CALENDAR_MONTH(OPDPlan_ImplementDate__c) <='+month ;  //2020-11-16  mzy update 检索月  修改例如,11及11月以前
        }else if(dateNow.month() == 12){
            soql += 'AND(' ;
            soql += ' CALENDAR_YEAR(OPDPlan_ImplementDate__c) ='+year ;               //2020-11-16  mzy update 检索月  修改例如,11及11月以前
            soql += ' OR( CALENDAR_YEAR(OPDPlan_ImplementDate__c) ='+nextyear + 'AND CALENDAR_MONTH(OPDPlan_ImplementDate__c) <='+month +')' ;
            soql += ')';
        }
        //2020-12-09  mzy  update 保存完成后销售本部 , 显示原来的查询条件
        if(Salesdepartment !=null &&!String.isBlank(Salesdepartment)&& !Salesdepartment.equals('全部')){
            soql += ' AND (OPDPlanSalesdepartment__c like \'%'+ String.escapeSingleQuotes(Salesdepartment.replaceAll('%', '\\%')) + '%\')';
        }
        //2020-12-09  mzy  update  保存完成后OCSM管理省 , 显示原来的查询条件
        if(ManProvince !=null&&!String.isBlank(ManProvince)&& !ManProvince.equals('全部')){
            soql += ' AND (OPDPlanOCM_man_province_Rental__c like \'%'+ String.escapeSingleQuotes(ManProvince.replaceAll('%', '\\%')) + '%\')';
        }
        //2020-12-10  mzy update 检索时排序顺序的改变  排序状态>优先度>学会>实施日  start
        soql += ' order by IsSaveOrSubmit__c, OPDLendSortDraft__c,Campaign__c ,OPDPlan_ImplementDate__c  limit 800';  
        //2020-12-10  mzy update 检索时排序顺序的改变  排序状态>优先度>学会>实施日  end

        /* 
        OPDPlanList = [select Id,Name,OPDPlanSalesdepartment__c,OPDPlanOCM_man_province_Rental__c,AccountOrCampaignName__c,if_OPDTarget__c,Cnt_OPD_ThisYear__c,Cnt_OPD_LastYear__c,Rental_Apply1__c,Rental_Apply2__c,Rental_Apply3__c,Rental_Apply4__c,Rental_Apply5__c,
        Rental_Apply1__r.Name,Rental_Apply1__r.Status__c,Rental_Apply2__r.Name,Rental_Apply2__r.Status__c,Rental_Apply3__r.Name,Rental_Apply3__r.Status__c,Rental_Apply4__r.Name,Rental_Apply4__r.Status__c,Rental_Apply5__r.Name,Rental_Apply5__r.Status__c,
        if_HaveOpportunity__c,if_HaveEquipment__c,PlanProdDetail__c,Cnt_Rentals__c,WorkshopPlace__c,Owner.Name,OPDLendSort__c,OPDLendSortDraft__c,OPDPlan_ImplementDate__c,Status__c,IsJump__c,JumpCause__c,Campaign__c,AccountType__c,Account_Laboratory__r.Name,IsSaveOrSubmit__c 
         FROM OPDPlan__c where     
        Status__c = '计划中' AND  OPDPlanSalesdepartment__c = :loginUser.Salesdepartment__c          // 2020-11-24 mzy add 页面初始化时 根据当前登录用户的销售本部进行查询                              
        AND  CALENDAR_YEAR(OPDPlan_ImplementDate__c)= :year and CALENDAR_MONTH(OPDPlan_ImplementDate__c) <= :month order by IsSaveOrSubmit__c, OPDLendSortDraft__c,PlanProdDetail__c ,OPDPlan_ImplementDate__c  limit 800 //2020-11-16 mzy  update 检索月  改为例如,11及11月以前 
        ]; */
        OPDPlanList = Database.query(soql);
        //2020-12-01 mzy  如果是12月则检索今年一整年+明年1月份的所有OPD计划 update   end
        for (Integer i = 0; i < OPDPlanList.size(); i++) {
            MidMap.put(OPDPlanList[i].Id, new OPDPlanInfo(OPDPlanList[i]));
        }
        //2020-12-10  mzy  update  检索时,学会类型的在上面,医院的排下面  start
        //存放 排序后 学会类型的OPD计划
        List<OPDPlanInfo> SortCampaignOPDList = new List<OPDPlanInfo>();
        //存放 排序后  医院类型的OPD计划
        List<OPDPlanInfo> SortHospitalOPDPList= new List<OPDPlanInfo>();
        //存放 未排序 学会类型的OPD计划
        List<OPDPlanInfo> NSortCampaignOPDList = new List<OPDPlanInfo>();
        //存放 未排序  医院类型的OPD计划
        List<OPDPlanInfo> NSortHospitalOPDPList= new List<OPDPlanInfo>();

        for (OPDPlanInfo op : MidMap.values()) {
            if(op.op.OPDLendSortDraft__c != null || (op.op.IsJump__c==true&&(!String.isBlank(op.op.JumpCause__c)) ) ){  //2020-11-10  mzy add 插队不需要排序 || op.op.IsJump__c==true&&!String.valueOf(op.op.JumpCause__c)
                //已经排序的
                    if(op.op.Campaign__c != null){
                    //1. 学会类型的
                      SortCampaignOPDList.add(op);
                    }else {
                    //2. 医院类型的
                      SortHospitalOPDPList.add(op);
                    }
            }else{
                //未选择的
                    if(op.op.Campaign__c != null){
                    //1. 学会类型的
                      NSortCampaignOPDList.add(op);
                    }else {
                    //2. 医院类型的
                      NSortHospitalOPDPList.add(op);
                    }
            } 
        }
        //整合
        //已排序的
        //学会类型
        checkedOPDPlan.addAll(SortCampaignOPDList);
        //医院类型
        checkedOPDPlan.addAll(SortHospitalOPDPList);
        //system.debug('checkedOPDPlan111:'+checkedOPDPlan.size());
        //未排序的
        //学会类型
        unCheckedOPDPlan.addAll(NSortCampaignOPDList);
             //医院类型
        unCheckedOPDPlan.addAll(NSortHospitalOPDPList);

        //2020-12-10  mzy update  检索时,学会类型的在上面,医院的排下面  end
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,  'aaa'));

    }
    // 2020-12-02  mzy 点击OPD计划实施日可以进行排序 start
    public void sortTable(){
        //soql
        String soql = 'SELECT Id,Name,OPDPlanSalesdepartment__c,OPDPlanOCM_man_province_Rental__c,AccountOrCampaignName__c,if_OPDTarget__c,Cnt_OPD_ThisYear__c,Cnt_OPD_LastYear__c,if_HaveOpportunity__c,if_HaveEquipment__c,PlanProdDetail__c,Cnt_Rentals__c,Owner.Name,WorkshopPlace__c,OPDLendSort__c,OPDLendSortDraft__c,OPDPlan_ImplementDate__c,Status__c,Rental_Apply1__c,Rental_Apply2__c,Rental_Apply3__c,Rental_Apply4__c,Rental_Apply5__c,Rental_Apply1__r.Name,Rental_Apply1__r.Status__c,Rental_Apply2__r.Name,Rental_Apply2__r.Status__c,Rental_Apply3__r.Name,Rental_Apply3__r.Status__c,Rental_Apply4__r.Name,Rental_Apply4__r.Status__c,Rental_Apply5__r.Name,Rental_Apply5__r.Status__c';
                soql += ', IsJump__c,OrderStatusNum__c,JumpCause__c,Campaign__c,AccountType__c,Account_Laboratory__r.Name,IsSaveOrSubmit__c ,OPDLendSortBefore__c,if_Newest_HaveOpportunity__c ';
                soql += ' FROM OPDPlan__c ';
       /* //判断
        */
        if(this.sortKey.equals('Sort')){
            //说明是按照优先度排序            
            //0.最后封装
            List<OPDPlanInfo> tempInfoList = new List<OPDPlanInfo>();
            //3. 排序方式
            String tempFlag = '';
            if(this.sortTableFlagSort.equals('0')){
                tempFlag = 'asc';
            }else if (this.sortTableFlagSort.equals('asc')){
                tempFlag = 'desc';
            }else if (this.sortTableFlagSort.equals('desc')){
                tempFlag = 'asc';
            }
            //赋值
            this.sortTableFlagSort = tempFlag;
            //判断非空
            if(checkedOPDPlan.size()<=0){
                return;
            }
            //1.插队的不需要比较优先度  
            //提交的插队的
            List<OPDPlanInfo> commitJumpList = new List<OPDPlanInfo>();
            //保存的插队的
            List<OPDPlanInfo> saveJumpList = new List<OPDPlanInfo>();
            //2.需要排优先度
            String ids = '';
            Map<String,OPDPlanInfo> tempMap = new Map<String,OPDPlanInfo>();
            List<OPDPlanInfo> sortOPDList = new List<OPDPlanInfo>();
            for(Integer i=0;i<checkedOPDPlan.size();i++){
                OPDPlanInfo tempInfo = checkedOPDPlan[i];
                if(( tempInfo.op.IsJump__c==true&&(!String.isBlank(tempInfo.op.JumpCause__c)))){
                    //插队的
                    if(tempInfo.op.IsSaveOrSubmit__c.equals('已提交')){
                        // 已提交
                        commitJumpList.add(tempInfo);
                    }else if(tempInfo.op.IsSaveOrSubmit__c.equals('已保存')){
                        // 已保存
                        saveJumpList.add(tempInfo);
                    } 
                }else {
                    sortOPDList.add(tempInfo);

                    if(ids == ''){
                      ids +='\''+tempInfo.op.id+'\'';
                    }else{
                       ids +=',\''+tempInfo.op.id+'\'' ;
                    }
                    tempMap.put(tempInfo.op.id ,tempInfo); 
                }
                   
            }
              
            //4.查询
            //4.0 拼接SQL
            if(!String.isBlank(ids)){
             soql += '  where id in ('+ids +')'; 
            }
            soql += ' order by OPDLendSortDraft__c '+this.sortTableFlagSort+',IsSaveOrSubmit__c,OPDPlan_ImplementDate__c, PlanProdDetail__c';
            System.debug('NoSQL:' + soql);
            //4.1 定义变量保存查询结果
            List<OPDPlan__c> tempList = new List<OPDPlan__c>();
            tempList = Database.query(soql);
            //提交的排序的
            List<OPDPlanInfo> commitSortList = new List<OPDPlanInfo>();
            //保存的排序的
            List<OPDPlanInfo> saveSortList = new List<OPDPlanInfo>();
            for(OPDPlan__c topd : tempList ){
                OPDPlanInfo tempInfo = tempMap.get(topd.id);
                //排序的
                if(tempInfo.op.IsSaveOrSubmit__c.equals('已提交')){
                    // 已提交
                    commitSortList.add(tempInfo);
                }else if(tempInfo.op.IsSaveOrSubmit__c.equals('已保存')){
                    // 已保存
                    saveSortList.add(tempInfo);
                } 
            }
            //4.2整合
            //已提交的插队的
            tempInfoList.addAll(commitJumpList);
            //已提交的排序的
            tempInfoList.addAll(commitSortList);
            //已保存的插队的
            tempInfoList.addAll(saveJumpList);
            //已保存的排序的
            tempInfoList.addAll(saveSortList);
            //5.赋值
            checkedOPDPlan = tempInfoList;
        }else if(this.sortKey.equals('NDetail')){
            //说明是 待排序栏 按照备品信息排序
            //清空计划日排序
            this.sortTableFlagNTime = '0';
            //0. 排序方式
            String tempFlag = '';
            if(this.sortTableFlagNDetail.equals('0')){
                tempFlag = 'asc';
            }else if (this.sortTableFlagNDetail.equals('asc')){
                tempFlag = 'desc';
            }else if (this.sortTableFlagNDetail.equals('desc')){
                tempFlag = 'asc';
            }
            //赋值
            this.sortTableFlagNDetail = tempFlag;
            //判断非空
            if(unCheckedOPDPlan.size()<=0){
                return;
            }
            //保存查询结果
            List<OPDPlan__c> tempList = new List<OPDPlan__c>();
            String ids = '';
            Map<String,OPDPlanInfo> tempMap = new Map<String,OPDPlanInfo>();
            //最后封装
            List<OPDPlanInfo> tempInfoList = new List<OPDPlanInfo>();
            //获取已排序的OPD计划的id
            for(Integer i=0;i<unCheckedOPDPlan.size();i++){
               OPDPlanInfo tempInfo = unCheckedOPDPlan[i];
               if(ids == ''){
                    ids +='\''+tempInfo.op.id+'\'';
                }else{
                    ids +=',\''+tempInfo.op.id+'\'' ;
                }
               tempMap.put(tempInfo.op.id ,tempInfo);
            }
            //4.查询
            //4.0 拼接SQL
            soql += '  where id in ('+ids; 
            soql += ') ';  
            soql += 'order by PlanProdDetail__c '+this.sortTableFlagNDetail+',IsSaveOrSubmit__c,OPDPlan_ImplementDate__c,OPDLendSortDraft__c';
            //4.1 保存查询结果
            tempList = Database.query(soql);
            for(OPDPlan__c topd : tempList ){
                OPDPlanInfo tempInfo = tempMap.get(topd.id);
                tempInfoList.add(tempInfo);
            }
            //4.2整合
            //5.赋值
            unCheckedOPDPlan = tempInfoList;
        }else if(this.sortKey.equals('Ntime')){
            //说明是 待排序栏 按照计划实施日排序
            //清空备品信息排序
            this.sortTableFlagNDetail = '0';
            //0. 排序方式
            String tempFlag = '';
            if(this.sortTableFlagNtime.equals('0')){
                tempFlag = 'asc';
            }else if (this.sortTableFlagNtime.equals('asc')){
                tempFlag = 'desc';
            }else if (this.sortTableFlagNtime.equals('desc')){
                tempFlag = 'asc';
            }
            //赋值
            this.sortTableFlagNtime = tempFlag;
            //判断非空
            if(unCheckedOPDPlan.size()<=0){
                return;
            }    
             //保存查询结果
            List<OPDPlan__c> tempList = new List<OPDPlan__c>();
            String ids = '';
            Map<String,OPDPlanInfo> tempMap = new Map<String,OPDPlanInfo>();
            //最后封装
            List<OPDPlanInfo> tempInfoList = new List<OPDPlanInfo>();
            //获取未排序的OPD计划的id
            for(Integer i=0;i<unCheckedOPDPlan.size();i++){
                OPDPlanInfo tempInfo = unCheckedOPDPlan[i];
                if(ids == ''){
                      ids +='\''+tempInfo.op.id+'\'';
                }else{
                       ids +=',\''+tempInfo.op.id+'\'' ;
                }
               tempMap.put(tempInfo.op.id ,tempInfo);
            }
            //查询
            soql += '  where id in ('+ids; 
            soql += ') order by OPDPlan_ImplementDate__c '+this.sortTableFlagNtime+',IsSaveOrSubmit__c,OPDLendSortDraft__c, PlanProdDetail__c'; 
            tempList = Database.query(soql);
            for(OPDPlan__c topd : tempList ){
                OPDPlanInfo tempInfo = tempMap.get(topd.id);
                tempInfoList.add(tempInfo);
            }
            //赋值
            unCheckedOPDPlan = tempInfoList;
        }
    }
    // 2020-12-02  mzy 点击OPD计划实施日可以进行排序 end
    // 检索按钮
    public PageReference searchBtn() {
        sortTableFlagSort = '0';  //2020-12-02 mzy  点击OPD计划实施日/备品优先度/计划出借备品  可以进行排序 add
        sortTableFlagNDetail = '0';  //2020-12-02 mzy  点击OPD计划实施日/备品优先度/计划出借备品 可以进行排序 add
        sortTableFlagNtime = '0'; //2020-12-03 mzy  点击OPD计划实施日 进行排序 add
        sortKey = ''; //2020-12-02 mzy 点击OPD计划实施日/备品优先度可以进行排序 add
        checkedOPDPlan = new List<OPDPlanInfo>();
        unCheckedOPDPlan = new List<OPDPlanInfo>();
        Boolean isDisabled = false;
        //System.debug('==11:'+month+'==22:'+OPDMonth);
        Date dateNow = Date.today();
        this.month = dateNow.month();
        this.year = dateNow.year();
        //2020-12-01  mzy  如果检索的是1月则检索今年一整年+明年1月份的所有OPD计划 add
        if(this.month==12){
            this.month=1;
            this.nextyear = this.year+1;  // 2020-12-01  mzy  如果检索的是1月 则检索今年一整年+明年1月份的所有OPD计划 update  
        }else{
            this.month +=1;
        }
        //System.debug('年份是 : '+this.year);
        Integer MonthSearch = Integer.valueOf(OPDMonth);
        if(month != MonthSearch){ 
            month = MonthSearch;   
            if (MonthSearch == 1){
              this.nextyear = dateNow.year() + 1;
            }
            isDisabled = true;
        }   
        List<OPDPlan__c> OPDPlanList = new List<OPDPlan__c>();
        Map<String, OPDPlanInfo> MidMap = new Map<String, OPDPlanInfo>();
        String soql = 'SELECT Id,Name,OPDPlanSalesdepartment__c,OPDPlanOCM_man_province_Rental__c,AccountOrCampaignName__c,if_OPDTarget__c,Cnt_OPD_ThisYear__c,Cnt_OPD_LastYear__c,if_HaveOpportunity__c,if_HaveEquipment__c,PlanProdDetail__c,Cnt_Rentals__c,Owner.Name,WorkshopPlace__c,OPDLendSort__c,OPDLendSortDraft__c,OPDPlan_ImplementDate__c,Status__c,Rental_Apply1__c,Rental_Apply2__c,Rental_Apply3__c,Rental_Apply4__c,Rental_Apply5__c,Rental_Apply1__r.Name,Rental_Apply1__r.Status__c,Rental_Apply2__r.Name,Rental_Apply2__r.Status__c,Rental_Apply3__r.Name,Rental_Apply3__r.Status__c,Rental_Apply4__r.Name,Rental_Apply4__r.Status__c,Rental_Apply5__r.Name,Rental_Apply5__r.Status__c';
        soql += ', IsJump__c,OrderStatusNum__c,JumpCause__c,Campaign__c,AccountType__c,Account_Laboratory__r.Name,IsSaveOrSubmit__c ,OPDLendSortBefore__c,if_Newest_HaveOpportunity__c ';
        soql +=' FROM OPDPlan__c where Status__c=\'计划中\'';  
        // 2020-12-01  mzy  如果是12月则检索今年一整年+明年1月份的所有OPD计划 update start
        if(this.month != 1){
          soql += ' AND CALENDAR_YEAR(OPDPlan_ImplementDate__c)='+year ;
          soql += ' AND CALENDAR_MONTH(OPDPlan_ImplementDate__c) <='+month ;   //2020-11-16  mzy update 检索月  修改例如,11及11月以前
        }else if(this.month == 1){
          soql += 'AND(' ;
          soql += ' CALENDAR_YEAR(OPDPlan_ImplementDate__c) ='+year ;           //2020-11-16  mzy update 检索月  修改例如,11及11月以前
          soql += ' OR( CALENDAR_YEAR(OPDPlan_ImplementDate__c) ='+nextyear + ' AND CALENDAR_MONTH(OPDPlan_ImplementDate__c) <='+month +')' ;
          soql += ')';
        } 

        //2020-12-01  mzy  如果是12月则检索今年一整年+明年1月份的所有OPD计划 update end

         // 2020-11-16  mzy  update  检索项  客户类型,客户名(不需要) start
        /*if(!String.isBlank(AccountName)){
            soql += ' AND (Account_Laboratory__r.Name like \'%'+ String.escapeSingleQuotes(AccountName.replaceAll('%', '\\%')) + '%\')';
        }
        if(!String.isBlank(AccountType)){
            if(AccountType.equals('医院')){
                soql += ' AND Campaign__c = null';  
            }
            if(AccountType.equals('学会会议')){
                soql += ' AND Campaign__c != null ';
            }
        }*/
         // 2020-11-16  mzy  update  检索项  客户类型,客户名(不需要) end
        
        if(Salesdepartment !=null &&!String.isBlank(Salesdepartment)&& !Salesdepartment.equals('全部')){
            soql += ' AND (OPDPlanSalesdepartment__c like \'%'+ String.escapeSingleQuotes(Salesdepartment.replaceAll('%', '\\%')) + '%\')';
        }
        // 2020-11-03  mzy  add  添加省份筛选条件 start
        if(ManProvince !=null&&!String.isBlank(ManProvince)&& !ManProvince.equals('全部')){
            soql += ' AND (OPDPlanOCM_man_province_Rental__c like \'%'+ String.escapeSingleQuotes(ManProvince.replaceAll('%', '\\%')) + '%\')';
        }
        //2020-12-10  mzy update 检索时排序顺序的改变  排序状态>优先度>学会>实施日  start
        soql += ' order by IsSaveOrSubmit__c, OPDLendSortDraft__c,Campaign__c ,OPDPlan_ImplementDate__c';  
        //2020-12-10  mzy update 检索时排序顺序的改变  排序状态>优先度>学会>实施日  end
        //分页
        soql += ' limit 800';

        //System.debug('===111==='+soql);
        //System.debug('SQL : ' + soql);
        OPDPlanList = Database.query(soql);
        for (Integer i = 0; i < OPDPlanList.size(); i++) {
            MidMap.put(OPDPlanList[i].Id, new OPDPlanInfo(OPDPlanList[i]));
        }

        //2020-12-10  mzy update 检索时,学会类型的在上面,医院类型的在下面  start
        //存放 排序后 学会类型的OPD计划
        List<OPDPlanInfo> SortCampaignOPDList = new List<OPDPlanInfo>();
        //存放 排序后  医院类型的OPD计划
        List<OPDPlanInfo> SortHospitalOPDPList= new List<OPDPlanInfo>();
        //存放 未排序 学会类型的OPD计划
        List<OPDPlanInfo> NSortCampaignOPDList = new List<OPDPlanInfo>();
        //存放 未排序  医院类型的OPD计划
        List<OPDPlanInfo> NSortHospitalOPDPList= new List<OPDPlanInfo>();

        for (OPDPlanInfo op : MidMap.values()) {
            if(op.op.OPDLendSortDraft__c != null || (op.op.IsJump__c==true&&(!String.isBlank(op.op.JumpCause__c)) ) ){ //2020-11-10  mzy add 插队不需要排序 || op.op.IsJump__c==true&&!String.valueOf(op.op.JumpCause__c)
                //已经排序的
                if(op.op.Campaign__c != null){
                    //1.学会类型
                    SortCampaignOPDList.add(op);
                }else {
                    //2.医院类型
                    SortHospitalOPDPList.add(op);
                }
            }else{
                //未选择的
                op.disabled = isDisabled;
                  
                if(op.op.Campaign__c != null){
                    //1.学会类型
                    NSortCampaignOPDList.add(op);  
                }else {
                    //2.医院类型
                    NSortHospitalOPDPList.add(op);  
                }
            } 
        }
        //20210317 ljh SWAG-BYPADS add start
        unCheckedOPDPlan = new List<OPDPlanInfo>();
        checkedOPDPlan = new List<OPDPlanInfo>();
        //20210317 ljh SWAG-BYPADS add end
        //整合
        //已排序的
        //学会类型
        checkedOPDPlan.addAll(SortCampaignOPDList);
        //医院类型
        checkedOPDPlan.addAll(SortHospitalOPDPList);
        //未排序的
        //学会类型
        unCheckedOPDPlan.addAll(NSortCampaignOPDList);
        //医院类型
        unCheckedOPDPlan.addAll(NSortHospitalOPDPList);

        //2020-12-10  mzy update 检索时,学会类型的在上面,医院类型的在下面  end
        return null;
    }
    public PageReference saveAdd() {
        //System.debug('saveAdd start');
        List<OPDPlanInfo> tmpChecked = new List<OPDPlanInfo>();
        List<OPDPlanInfo> tmpUnChecked = new List<OPDPlanInfo>();
        tmpChecked.addAll(checkedOPDPlan);
        for(OPDPlanInfo opd : unCheckedOPDPlan){
            if (opd.check) {
                tmpChecked.add(opd);
            } else {
                tmpUnChecked.add(opd);
            }   
        }
        checkedOPDPlan = new List<OPDPlanInfo>();
        for (OPDPlanInfo tempOPD : tmpChecked) {
            checkedOPDPlan.add(tempOPD);
        }
        unCheckedOPDPlan = new List<OPDPlanInfo>();
        unCheckedOPDPlan.addAll(tmpUnChecked);
        return null;
    }
    public PageReference save() {
         
        List<OPDPlan__c> saveChecked = new List<OPDPlan__c>();
        Boolean flagJump = false;
        Boolean flagSortNull = false;
        Boolean flagSort = false;
        Boolean flagIsDa = false;
        Boolean flagShouldNum = false;
        Boolean Rentalflag = false;   //2020-12-08 mzy 如果有备品申请则不可以勾选插队  start
        String  message;
        Integer MaxSort;//最大的已提交的排序
        Map<String,String> SortMap = new  Map<String,String>();
        List<String> opdIdL = new List<String>();       
        //System.debug('===111===:'+checkedOPDPlan);
        for(OPDPlanInfo opd0 : checkedOPDPlan){
            //已提交的数组
            if(opd0.op.IsSaveOrSubmit__c.equals('已提交') && opd0.op.OPDLendSort__c!=0){
                MaxSort = MaxSort>=opd0.op.OPDLendSortDraft__c?MaxSort:opd0.op.OPDLendSortDraft__c.intValue();
            }
            if(!opd0.op.IsSaveOrSubmit__c.equals('已提交') || (opd0.op.OrderStatusNum__c == 3 && opd0.op.IsJump__c)){
                opdIdL.add(opd0.op.Id);
            }
        }
        
        for(OPDPlanInfo opd : checkedOPDPlan){
            //后台判断1.如果勾选了插入 则必须填写插入原因
            if(opd.op.IsJump__c&&!String.isBlank(opd.RentalApplyStr)){
                Rentalflag = true;break;
            }
            if(opd.op.IsJump__c&&String.isBlank(opd.op.JumpCause__c)){
                flagJump = true;break;
            }
            //后台判断2.排序不为空
            if(opd.op.OPDLendSortDraft__c == null&&flagJump==false&&String.isBlank(opd.op.JumpCause__c)){  //2020-11-09 mzy add 1 没插队需要排序 &&flagJump==false&&String.isBlank(opd.op.JumpCause__c)
                flagSortNull = true;break;
            }else{
                //后台判断3.排序不重复问题
                if(flagJump==false&&String.isBlank(opd.op.JumpCause__c)){   //2020-11-09 mzy add  2 没插队需要排序  if(flagJump==false&&String.isBlank(opd.op.JumpCause__c)){  
                    String tempOPDLendSortDraft = opd.op.OPDLendSortDraft__c.format();
                    if(SortMap.containsKey(tempOPDLendSortDraft)){
                        flagSort = true;break;
                    }else{
                        //后台判断4.默认往下排序
                        if(MaxSort > opd.op.OPDLendSortDraft__c && opd.op.IsSaveOrSubmit__c!='已提交'){ 
                            flagIsDa = true;break;
                        }
                        if(opd.op.IsSaveOrSubmit__c!='已提交'){
                            SortMap.put(tempOPDLendSortDraft,tempOPDLendSortDraft);
                        }
                    }
                }                                    
                
            }           
        }

        //后台判断0.如果有备品申请,则不可以插队
        if(Rentalflag){
            message = '如果有备品申请则不可以勾选插队';
        }
        //后台判断1.如果勾选了插入 则必须填写插入原因
        if(flagJump){
            message = '如果勾选了插入 则必须填写插入原因';
        }
        //后台判断2.排序不空问题
        if(flagSortNull){
            message = '排序不能为空，请填写正确的排序!';
        }
        //后台判断3.排序不重复问题
        if(flagSort){
            message = '排序有重复请重新排序!';
        }
        //后台判断4.新添加进来的备品出借优先度，默认往下排序
        if(flagIsDa){
            message = '新添加进来的备品出借优先度，默认往下排序!';
        }
        //System.debug('flagJump :'+ flagJump +' flagSortNull :'+flagSortNull+' flagSort: '+flagSort+' flagIsDa:'+flagIsDa);
        if(!flagJump && !flagSortNull && !flagSort && !flagIsDa){
            //system.debug('checkedOPDPlan:'+checkedOPDPlan[0]);
            for(OPDPlanInfo opd : checkedOPDPlan){
                if(!opd.op.IsSaveOrSubmit__c.equals('已提交') || (opd.op.OrderStatusNum__c == 3 && opd.op.IsJump__c)){//20210301 ljh update end
                    OPDPlan__c opdUpdate = new OPDPlan__c();
                    opdUpdate.Id = opd.op.Id;
                    opdUpdate.IsJump__c = opd.op.IsJump__c;
                    //20210304 ljh add 优化 start
                    if(opd.op.IsJump__c){
                        opdUpdate.JumpCause__c = opd.op.JumpCause__c;
                    }else{
                        opdUpdate.JumpCause__c = null;
                    }
                    //20210304 ljh add 优化 end
                    //清除旧历史(插队没写优先度的后来取消插队)
                    if(opd.op.IsJump__c == false && opd.op.OPDLendSort__c == 0){
                      opdUpdate.OPDLendSort__c = null;
                    }
                    opdUpdate.OPDLendSortDraft__c = opd.op.OPDLendSortDraft__c;
                    //如果状态是未排序,插队没写优先度则优先度为空
                    if(opd.op.IsSaveOrSubmit__c.equals('已保存') && opd.op.IsJump__c == true){
                      opdUpdate.OPDLendSortDraft__c = null;
                    }
                    saveChecked.add(opdUpdate);
                }//20210301 ljh update end
            }
            system.debug('saveChecked.size()'+saveChecked.size());

            update saveChecked;
            rFlag = '保存成功!';
            return returnFresh();
        }else{
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,  message));
            return null;
        }
        //return returnFresh();
    }
    public PageReference del(){
        //System.debug('===111===:'+opdDelId);
        List<OPDPlan__c> updateOPDPlan = [select Id,OPDLendSortDraft__c,IsJump__c,if_Newest_HaveOpportunity__c,JumpCause__c,IsSaveOrSubmit__c,OrderStatusNum__c  FROM OPDPlan__c WHERE Id = :opdDelId];
        if(updateOPDPlan.size()>0 && (updateOPDPlan[0].OPDLendSortDraft__c != null || updateOPDPlan[0].IsJump__c==true)){   
            //更新这条记录  清空 排序、插入、插入原因字段
            updateOPDPlan[0].OPDLendSortDraft__c = null;
            updateOPDPlan[0].SystemSort__c = null;
            updateOPDPlan[0].IsJump__c = false;
            updateOPDPlan[0].JumpCause__c = null;
            update updateOPDPlan;
        }
        updateOPDPlan = [select Id,Name,OPDPlanSalesdepartment__c,OPDPlanOCM_man_province_Rental__c,AccountOrCampaignName__c,if_OPDTarget__c,Cnt_OPD_ThisYear__c,Cnt_OPD_LastYear__c,Rental_Apply1__c,Rental_Apply2__c,Rental_Apply3__c,Rental_Apply4__c,Rental_Apply5__c,if_Newest_HaveOpportunity__c,
                        Rental_Apply1__r.Name,Rental_Apply1__r.Status__c,Rental_Apply2__r.Name,Rental_Apply2__r.Status__c,Rental_Apply3__r.Name,Rental_Apply3__r.Status__c,Rental_Apply4__r.Name,Rental_Apply4__r.Status__c,Rental_Apply5__r.Name,Rental_Apply5__r.Status__c,
                        if_HaveOpportunity__c,if_HaveEquipment__c,PlanProdDetail__c,Cnt_Rentals__c,WorkshopPlace__c,Owner.Name,OPDLendSort__c,OPDLendSortDraft__c,OPDPlan_ImplementDate__c,Status__c,IsJump__c,OrderStatusNum__c,JumpCause__c,Campaign__c,AccountType__c,
                        Account_Laboratory__r.Name,IsSaveOrSubmit__c,OPDLendSortBefore__c,SystemSort__c 
                        FROM OPDPlan__c WHERE Id = :opdDelId];
        //重新遍历
        List<OPDPlanInfo> tmpChecked = new List<OPDPlanInfo>();
        List<OPDPlanInfo> tmpUnChecked = new List<OPDPlanInfo>();
        //System.debug('===111===:'+unCheckedOPDPlan);
        tmpUnChecked.addAll(unCheckedOPDPlan);
        for (OPDPlanInfo tempOPD : checkedOPDPlan) {
            if(tempOPD.op.Id.equals(updateOPDPlan[0].Id)){
                tmpUnChecked.add(new OPDPlanInfo(updateOPDPlan[0]));
            }else{
                tmpChecked.add(tempOPD);
            }
        }
        checkedOPDPlan = new List<OPDPlanInfo>();
        checkedOPDPlan.addAll(tmpChecked);
        unCheckedOPDPlan = new List<OPDPlanInfo>();
        unCheckedOPDPlan.addAll(tmpUnChecked);
        return  null;
    }
    //提交  判断是否可以提交 更新字段 发送邮件 
    public PageReference submitBtn(){
        //判断是否可以提交
        Boolean submitFlag = false;
        Boolean jumpflag = false;
        String message;
        List<String> sortStatusList = new  List<String>();
        List<String> opdIdL = new List<String>();
        for(OPDPlanInfo opd : checkedOPDPlan){
            //后台判断 没有空 或者全部是已提交
            String IsSaveOrSubmit = opd.op.IsSaveOrSubmit__c;
            if(IsSaveOrSubmit.equals('未排序')){
                message = '请先保存排序在提交!';
                submitFlag= true;break;
            }
            if(opd.op.IsSaveOrSubmit__c.equals('已保存') || (opd.op.OrderStatusNum__c == 3 && opd.op.IsJump__c)){
                opdIdL.add(opd.op.Id);
            }
        }
        Boolean changeFlg = false;
        Map<String,OPDPlan__c> opdMap =  new Map<String,OPDPlan__c>(); 
        for (OPDPlan__c opd1 : [Select Id,OPDLendSortDraft__c,LastModifiedDate FROM OPDPlan__c Where Id = :opdIdL for Update]) {
            opdMap.put(opd1.Id, opd1);
        }
        //5.要更新的数据有更新则刷新重新保存
        for(OPDPlanInfo opd : checkedOPDPlan){
            if (opdMap.containsKey(opd.op.Id) 
                    && opdMap.get(opd.op.Id).OPDLendSortDraft__c != null 
                    && opd.op.OPDLendSortDraft__c != null
                    && opd.op.OPDLendSortDraft__c != opdMap.get(opd.op.Id).OPDLendSortDraft__c
                ){
                changeFlg = true;break;
            }
        }
        if(changeFlg){
           message =  'OPD计划备品出借优先度有被更新过,请刷新画面重试';
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, message)); 
           return null;
        }
        if(submitFlag){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, message));
            return null;
        }else{
            //更新字段
            List<String> CommitIdList = new List<String>();
            List<OPDPlan__c> updateOPDList = new List<OPDPlan__c>();

            //存放所有提交的公共小组
            //插队
            Set<String> JumppublicGroupSet = new Set<String>();
            //排序
            //存放所有提交的公共小组
            Set<String> SortpublicGroupSet = new Set<String>();
            //用来存放插队的OPD
            List<OPDPlan__c> jumpList = new List<OPDPlan__c>();
            //用来存放排序的OPD
            List<OPDPlan__c> sortList = new List<OPDPlan__c>();
            for(OPDPlanInfo opd : checkedOPDPlan){
                // OCSM管理省
                String ProvinceTxt = opd.op.OPDPlanOCM_man_province_Rental__c;
                //获取公共小组小组名
                String groupDeveloperName = groupsuffixMap.get(ProvinceTxt);
                OPDPlan__c opdN =  new OPDPlan__c();
                opdN.Id = opd.op.Id;
                if(opd.op.IsSaveOrSubmit__c.equals('已保存')){
                    opdN.OPDLendSort__c = opd.op.OPDLendSortDraft__c;
                    opdN.SortDate__c = Date.today();// 2020-11-11  mzy add  提交时赋值排序日期字段
                    opdN.SortOperator__c = userInfo.getUserId(); //提交时赋值排序操作人字段
                    if(opd.op.IsJump__c){
                        opdN.OPDLendSort__c = 0;//如果是插队的话则OPDLendSort__c = 0 
                        jumpList.add(opd.op);//20210304 ljh add
                        JumppublicGroupSet.add(groupDeveloperName);
                    }else{
                        sortList.add(opd.op);
                        SortpublicGroupSet.add(groupDeveloperName);
                    } 
                    updateOPDList.add(opdN);
                }
                //if(opd.op.IsSaveOrSubmit__c.equals('已提交')){
                //已提交&插队&未清空排序
                if(opd.op.OrderStatusNum__c == 4){//20210301 ljh update end
                    opdN.OPDLendSortDraft__c = null; //20210303 ljh add 
                    opdN.OPDLendSort__c = 0;//20210303 ljh add
                    updateOPDList.add(opdN);
                    //添加到CommitIdList集合中
                    jumpList.add(opd.op);
                    JumppublicGroupSet.add(groupDeveloperName);
                } 
                if(opd.op.OrderStatusNum__c == 3 && opd.op.IsJump__c){//20210301 ljh update end
                    opdN.IsJump__c = opd.op.IsJump__c;
                    opdN.JumpCause__c = opd.op.JumpCause__c;
                    opdN.OPDLendSortDraft__c = null; //20210303 ljh add 
                    opdN.OPDLendSort__c = 0;//20210303 ljh add
                    updateOPDList.add(opdN);
                    //添加到CommitIdList集合中
                    jumpList.add(opd.op);
                    JumppublicGroupSet.add(groupDeveloperName);
                }   
            }


            //发送邮件
            List<Messaging.SingleEmailMessage> sendMails = new List<Messaging.SingleEmailMessage>();
            //用来存放需要发送邮件的用户邮箱
            //插队
            List<String> JumpMailsList = new List<String>();
            //排序
            List<String>  SortMailsList = new List<String>();
            // 2020-11-17  mzy  add  给公共小组发邮件  start
            if(updateOPDList !=null && updateOPDList.size()>0){
                update updateOPDList;
                rFlag = '提交成功！';
                //2020-12-24 mzy  插队发送插队邮件,排序发送排序邮件 start
                //排序
                //用来存放用户的id
                List<String> SortIdList = new List<String>();
                //查询各个销售本部对应的公共小组
                List<Group> SortgList = [ SELECT (select userOrGroupId from groupMembers) FROM group WHERE DeveloperName in :SortpublicGroupSet];
                if(SortgList != null && SortgList.size()>0){
                    for (Group g : SortgList) {
                        for (GroupMember gm : g.groupMembers) {
                             SortIdList.add(gm.userOrGroupId);
                         }
                    }
                }
                 //根据用户id查询用户信息
                List<User> SortUsrList = [SELECT email FROM user WHERE id in :SortIdList]; 
                //获取各个用户的email
                for (User u : SortUsrList){
                    SortMailsList.add(u.email);
                }

                 //插队
                  //用来存放用户的id
                List<String> JumpIdList = new List<String>();
                //查询各个销售本部对应的公共小组
                List<Group> JumpgList = [ SELECT (select userOrGroupId from groupMembers) FROM group WHERE DeveloperName in :JumppublicGroupSet];
                if(JumpgList != null && JumpgList.size()>0){
                    for (Group g : JumpgList) {
                        for (GroupMember gm : g.groupMembers) {
                             JumpIdList.add(gm.userOrGroupId);
                         }
                    }
                }
                 
                 //根据用户id查询用户信息
                List<User> JumpUsrList = [SELECT email FROM user WHERE id in :JumpIdList]; 
                 //获取各个用户的email
                for (User u : JumpUsrList){
                    JumpMailsList.add(u.email);
                }
                //排序的邮件
                if (SortMailsList!=null&&SortMailsList.size()>0){
                    String OCMProvince = sortList.get(0).OPDPlanOCM_man_province_Rental__c;

                    String title = '';
                    String body = '';
                    title = OCMProvince + ' : 下月OPD计划的备品出借排序已完成，请查阅';
                    body += '各位领导:<br/>';
                    body += '下月的OPD/会议计划，已经完成备品出借排序，请查阅：报表链接<br/>';              
                    //body += System.Label.OPD_Report;
                    body += '<a href="' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + System.Label.OPD_Report + '">'
                            + URL.getSalesforceBaseUrl().toExternalForm() + '/'+ System.Label.OPD_Report +'</a><br/>'; 
                    body += '谢谢！';
          
                    Messaging.SingleEmailMessage messageNEW = new Messaging.SingleEmailMessage();
                    messageNEW.setSubject(title);
                    messageNEW.setHtmlBody(body);
                    messageNEW.setCharset('UTF-8');
                    messageNEW.setToAddresses(SortMailsList); 
        
                    sendMails.add(messageNEW);

                }
                //插队的邮件
                if (JumpMailsList!=null&&JumpMailsList.size()>0){
                    String OPDNoStr = '';
                    for(OPDPlan__c opd : jumpList){
                        if(OPDNoStr.equals('')){
                           OPDNoStr +=  opd.Name;
                        }else {
                           OPDNoStr += ',' +opd.Name; 
                        }
                    }
                    String OCMProvince = jumpList.get(0).OPDPlanOCM_man_province_Rental__c;
                    String title = '';
                    String body = '';
                    title = OCMProvince + ' : OPD计划已插队成功，请查阅';
                    body += '各位领导:<br/>';
                    body += 'OPD计划 '+OPDNoStr+' 已插队成功，请查阅：报表链接<br/>';              
                    //body += System.Label.OPD_Report;
                    body += '<a href="' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + System.Label.OPD_Report_Jump + '">'
                            + URL.getSalesforceBaseUrl().toExternalForm() + '/'+ System.Label.OPD_Report_Jump +'</a><br/>'; 
                    body += '谢谢！';
          
                    Messaging.SingleEmailMessage messageNEW = new Messaging.SingleEmailMessage();
                    messageNEW.setSubject(title);
                    messageNEW.setHtmlBody(body);
                    messageNEW.setCharset('UTF-8');
                    messageNEW.setToAddresses(JumpMailsList); 
        
                    sendMails.add(messageNEW);
                }
                       
                    
                boolean rs = true;
                if (sendMails.size() > 0) {
                    Messaging.Email[] allMails = new Messaging.Email[]{};
                    for(Integer j = 0; j < sendMails.size(); j++) {
                        allMails.add(sendMails.get(j));
                    }
                    //system.debug('222===:'+allMails);
                
                    Messaging.SendEmailResult[] results = Messaging.sendEmail(allMails);
                    //System.debug('results 结果 :'+results);
                    for (Integer i = 0; i < results.size(); i++) {
                        if (results[i].success == false) {
                            system.debug('=====send mail error:' + results[i].errors[0].message);
                            rs = false;
                        }   
                    }
                }
                //2020-12-07 mzy  如果没有用户则不发邮件  
                // 2020-11-17  mzy  add  给公共小组发邮件   end
                //toMailsList.add(System.Label.OPD_EMReceiver);
                
            }  
            //2020-12-24 mzy  插队发送插队邮件,排序发送排序邮件 end 
        }

        return returnFresh();
    }
    public PageReference returnFresh(){
        String url = '/apex/OPDSortManage';
        if(!String.isBlank(rFlag)){
            url += '?rFlag='+rFlag;
            url += '&&Salesdepartment='+Salesdepartment;
            url += '&&ManProvince='+ManProvince;
            url += '&&OPDMonth='+OPDMonth;
        }
        PageReference ref =  new Pagereference(url);
        ref.setRedirect(true);
        return ref;
    }
    //自动排序
    public PageReference autoSort(){
        if(checkedOPDPlan.size() == 0){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '排序栏无数据'));
            return null;    
        }
        //获取未排序的OPD计划的id
        String ids = '';
        Integer orderNum = 0;
        Set<String> IdSet = new Set<String>();
        List<OPDPlan__c> saveChecked = new List<OPDPlan__c>();
        List<String> opdIdL = new List<String>();
        for(OPDPlanInfo opd : checkedOPDPlan){
            if(opd.op.IsSaveOrSubmit__c.equals('未排序') && opd.op.OPDLendSortDraft__c == null && !opd.op.IsJump__c){
                if(ids == ''){
                    ids +='\''+opd.op.id+'\'';
                }else{
                    ids +=',\''+opd.op.id+'\'' ;
                }
            }
            OPDPlan__c opdUpdate = new OPDPlan__c();
            opdUpdate.Id = opd.op.Id;
            if(opd.op.IsSaveOrSubmit__c.equals('未排序') && (opd.op.OPDLendSortDraft__c != null || opd.op.IsJump__c)){
                opdUpdate.IsJump__c = opd.op.IsJump__c;
                if(opd.op.IsJump__c){
                    opdUpdate.JumpCause__c = opd.op.JumpCause__c;
                }else{
                    opdUpdate.JumpCause__c = null;
                }
                opdUpdate.OPDLendSortDraft__c = opd.op.OPDLendSortDraft__c;
                saveChecked.add(opdUpdate);    
            }
            
            if(opd.op.IsSaveOrSubmit__c.equals('已保存')){
                opdUpdate.IsJump__c = opd.op.IsJump__c;
                if(opd.op.IsJump__c){
                    opdUpdate.OPDLendSortDraft__c = null;
                    opdUpdate.JumpCause__c = opd.op.JumpCause__c;
                }else{
                    opdUpdate.JumpCause__c = null;
                }
                if(opd.op.IsJump__c == false && opd.op.OPDLendSort__c == 0){
                  opdUpdate.OPDLendSort__c = null;
                }
                opdUpdate.OPDLendSortDraft__c = opd.op.OPDLendSortDraft__c;
                saveChecked.add(opdUpdate);  
            }
            IdSet.add(opd.op.Id);
            if(!opd.op.IsSaveOrSubmit__c.equals('已提交') || (opd.op.OrderStatusNum__c == 3 && opd.op.IsJump__c)){
                opdIdL.add(opd.op.Id);
            }
        }
        Boolean changeFlg = false;
        Map<String,OPDPlan__c> opdMap =  new Map<String,OPDPlan__c>(); 
        for (OPDPlan__c opd1 : [Select Id,OPDLendSortDraft__c,LastModifiedDate FROM OPDPlan__c Where Id = :opdIdL for Update]) {
            opdMap.put(opd1.Id, opd1);
        }
        //要更新的数据有更新则刷新重新保存
        for(OPDPlanInfo opd : checkedOPDPlan){
            if (opdMap.containsKey(opd.op.Id) && opdMap.get(opd.op.Id).OPDLendSortDraft__c != null && opd.op.OPDLendSortDraft__c == null ) {
                changeFlg = true;break;
            }
        }
        if(changeFlg){
           String message =  'OPD计划备品出借优先度有被更新过,请刷新画面重试';
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, message));
           return null; 
        }
        if(saveChecked.size() > 0){
            update saveChecked;
        }
        if(ids.length() == 0){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '排序栏无待排序数据。如需再次自动排序，则清空排序后再操作。'));
            return null;    
        } 
        String soql = 'SELECT Id,Name,OPDPlanSalesdepartment__c,OPDPlanOCM_man_province_Rental__c,AccountOrCampaignName__c,if_OPDTarget__c,Cnt_OPD_ThisYear__c,Cnt_OPD_LastYear__c,if_HaveOpportunity__c,if_HaveEquipment__c,PlanProdDetail__c,Cnt_Rentals__c,Owner.Name,WorkshopPlace__c,OPDLendSort__c,OPDLendSortDraft__c,OPDPlan_ImplementDate__c,Status__c,Rental_Apply1__c,Rental_Apply2__c,Rental_Apply3__c,Rental_Apply4__c,Rental_Apply5__c,Rental_Apply1__r.Name,Rental_Apply1__r.Status__c,Rental_Apply2__r.Name,Rental_Apply2__r.Status__c,Rental_Apply3__r.Name,Rental_Apply3__r.Status__c,Rental_Apply4__r.Name,Rental_Apply4__r.Status__c,Rental_Apply5__r.Name,Rental_Apply5__r.Status__c';
        soql += ', IsJump__c,OrderStatusNum__c,JumpCause__c,Campaign__c,AccountType__c,Account_Laboratory__r.Name,IsSaveOrSubmit__c ,OPDLendSortBefore__c,if_Newest_HaveOpportunity__c ';
        soql += ' FROM OPDPlan__c ';
        //拼接SQL  AccountType__c不一样 两种排序规则
        String soql01 = '  WHERE id in ('+ids; 
        soql01 += ') and AccountType__c = \'学会会议\' ';  
        soql01 += 'order by OPDPlan_ImplementDate__c ASC,CreatedDate ASC';

        String soql02 = '  WHERE id in ('+ids; 
        soql02 += ') and AccountType__c = \'医院\' ';  
        // soql02 += ' order by SystemDelayMark__c DESC nulls last,OPDLendSortBefore__c  ASC nulls last,OPDPlan_ImplementDate__c ASC, ';
        // ***SWAG-BZCAHL***XHL***20210331***START*********
        // 通过再申请生成的OPD计划 优先度最高，排在最前面
        soql02 += ' order by Reapply__c DESC nulls last,SystemDelayMark__c DESC nulls last,OPDLendSortBefore__c  ASC nulls last,OPDPlan_ImplementDate__c ASC, ';
        // ***SWAG-BZCAHL***XHL***20210331***END*********
        soql02 += ' if_Newest_HaveOpportunity__c ASC,if_HaveOpportunity__c DESC nulls last,if_OPDTarget__c DESC nulls last,if_HaveSalestarget__c   DESC nulls last';
        //分别查询结果后拼接 在遍历排序赋值
        List<OPDPlan__c> tempList01 = Database.query(soql+soql01);
        List<OPDPlan__c> tempList02 = Database.query(soql+soql02);
        system.debug('sql:'+soql+soql02);
        List<OPDPlan__c> opdList  = new  List<OPDPlan__c>();
        tempList01.addAll(tempList02);
        List<OPDPlan__c> orderNumL = [SELECT Id,Name,OPDLendSortDraft__c FROM OPDPlan__c WHERE id in :IdSet AND IsJump__c = false ORDER BY   OPDLendSortDraft__c DESC nulls last  Limit 1];
        if(orderNumL.size() > 0 && Integer.valueOf(orderNumL[0].OPDLendSortDraft__c) > orderNum){
            orderNum = Integer.valueOf(orderNumL[0].OPDLendSortDraft__c);
        }
        for(OPDPlan__c opd:tempList01){
            OPDPlan__c opdUpdate = new OPDPlan__c();
            opdUpdate.Id = opd.Id;
            system.debug('orderNum:'+orderNum);
            opdUpdate.OPDLendSortDraft__c = orderNum+1;
            opdUpdate.SystemSort__c = orderNum+1;  
            opdList.add(opdUpdate);
            orderNum++;
        }
        update opdList;
        rFlag = '自动排序完毕！';
        return returnFresh();
    }
    //清空
    public PageReference clearOpd(){
        List<OPDPlan__c> clearList = new List<OPDPlan__c>();
        Map<String,String> IdMap = new Map<String,String>();
        for(OPDPlanInfo opd : checkedOPDPlan){
            if(!opd.op.IsSaveOrSubmit__c.equals('已提交')){  
                //更新这条记录  清空 排序、插入、插入原因字段
                OPDPlan__c opdUpdate = new OPDPlan__c();
                opdUpdate.Id = opd.op.Id;
                opdUpdate.OPDLendSortDraft__c = null;
                opdUpdate.SystemSort__c = null;
                opdUpdate.IsJump__c = false;
                opdUpdate.JumpCause__c = null;
                clearList.add(opdUpdate);
                IdMap.put(opd.op.Id,opd.op.Id);
            }

        }
        update clearList;
        searchBtn();
        List<OPDPlanInfo> tmpChecked = new List<OPDPlanInfo>();
        List<OPDPlanInfo> tmpUnChecked = new List<OPDPlanInfo>();
        system.debug('checkedOPDPlan:'+checkedOPDPlan.size());
        tmpChecked.addAll(checkedOPDPlan);
        for(OPDPlanInfo opd : unCheckedOPDPlan){
            if (IdMap.containsKey(opd.op.Id)) {
                tmpChecked.add(opd);
            } else {
                tmpUnChecked.add(opd);
            }   
        }
        checkedOPDPlan = new List<OPDPlanInfo>();
        for (OPDPlanInfo tempOPD : tmpChecked) {
            checkedOPDPlan.add(tempOPD);
        }
        unCheckedOPDPlan = new List<OPDPlanInfo>();
        unCheckedOPDPlan.addAll(tmpUnChecked);
        rFlag = '清空完毕，请重新排序！';
        return null;
    }
    
    class OPDPlanInfo{
        public Boolean check { get; set; }
        public Boolean disabled { get; set; }
        public OPDPlan__c op {get; set;}
        public String RentalApplyStr {get; set; }
        public String RentalApplyStatusStr {get; set; }
        public OPDPlanInfo(OPDPlan__c e) {
             op = e;      
             // 2020-11-20  mzy  add  有两个字段，一个是所有单号拼一起，另一个是所有状态拼一起。 start
            RentalApplyStr = '';
            RentalApplyStatusStr = '';
            if(e.Rental_Apply1__c != null){
               RentalApplyStr += String.valueOf(e.Rental_Apply1__r.Name) ;
               RentalApplyStatusStr += String.valueOf(e.Rental_Apply1__r.Status__c) ;
            }
            if(e.Rental_Apply2__c != null){
                if(e.Rental_Apply1__c != null){
                    RentalApplyStr += ',';
                    RentalApplyStatusStr += ',';
                }
               RentalApplyStr += String.valueOf(e.Rental_Apply2__r.Name);
               RentalApplyStatusStr += String.valueOf(e.Rental_Apply2__r.Status__c);
            }
            if(e.Rental_Apply3__c != null){
                if(e.Rental_Apply2__c != null){
                    RentalApplyStr += ',';
                    RentalApplyStatusStr += ',';
                }
               RentalApplyStr += String.valueOf(e.Rental_Apply3__r.Name);
               RentalApplyStatusStr += String.valueOf(e.Rental_Apply3__r.Status__c);
            }
            if(e.Rental_Apply4__c != null){
                if(e.Rental_Apply3__c != null){
                    RentalApplyStr += ',';
                    RentalApplyStatusStr += ',';
                }
               RentalApplyStr += String.valueOf(e.Rental_Apply4__r.Name);
               RentalApplyStatusStr += String.valueOf(e.Rental_Apply4__r.Status__c);
            }
            if(e.Rental_Apply5__c != null){
                if(e.Rental_Apply4__c != null){
                    RentalApplyStr += ',';
                    RentalApplyStatusStr += ',';
                }
               RentalApplyStr += String.valueOf(e.Rental_Apply5__r.Name);
               RentalApplyStatusStr += String.valueOf(e.Rental_Apply5__r.Status__c);
            }

            // 2020-11-20  mzy  add  有两个字段，一个是所有单号拼一起，另一个是所有状态拼一起。 end
            check = false;
            disabled = false;
        }
    }
}