// by ljh
public with sharing class RentalApplySequenceController {
    // 搜索字段
    public String S_raName {get; set;}  //申请单号
    public String S_Fixture_Model_No {get; set;}    //型号
    public Rental_Apply__c S_Ra_Person {get; set;}  // 备品出借担当
    public String S_bieCunFangDi {get; set;}    //备品存放地
    public String S_bieBenBu {get; set;}    //所在地区本部
    public String S_ApplyBenBu{get;set;} // 申请者本部
    public String S_Agency {get; set;}  //办事处
    public String S_Product_category {get; set;}    //产品分类
    public String S_bieBeiPinFenLei {get; set;}     //备品分类
    
    
    public Boolean isEquipmentCenter {get; set;} 
    public Boolean is2B1 = true;
    public Set<String> benbuSet;
    public Set<String> agencySet;
    public Set<String> cunfangdiSet;
    // public Set<String> bpflSet;
    // public Set<String> productSet;

    public List<Rental_Apply_Equipment_Set_Detail__c> raesdList;

    public String checkEventId { get; set; }
    public String frameUrl {
        get {
            return frameUrl;
        }
        set;
    }

    // 分页用 start
    public Integer currPage { get; set; } // 当前页
    public Integer totalPage { get; set; } // 总页数
    public Integer selctRecordNum { get { return Integer.valueOf(selRecordOption); } } // 选择的每页记录数
    public Integer totalRecords { get; set; }  // 总记录数
    public String selRecordOption { get; set; }
    public static List<SelectOption> recordNum { get; private set; } // 选择每页记录数List
    // 翻页到首页
    public void firstPage() {
        currPage = 1;
    }

    // 向前翻页
    public void previousPage() {
        currPage --;
    }

    // 向后翻页
    public void nextPage() {
        currPage ++;
    }

    // 翻页到尾页
    public void endPage() {
        currPage = totalPage;
    }

    // 每页显示记录数变更
    public void recordNumChange() {
        currPage = 1;
        totalPage = (totalRecords / selctRecordNum) + (Math.mod(totalRecords, selctRecordNum) > 0 ? 1 : 0);
        setupRaesInfoList(raesInfoList);
    }

    static {
        recordNum = new List<SelectOption>();
        recordNum.add(new SelectOption('10', '10'));
        recordNum.add(new SelectOption('20', '20'));
        recordNum.add(new SelectOption('50', '50'));
        recordNum.add(new SelectOption('100', '100'));
        recordNum.add(new SelectOption('200', '200'));
    }
    private Integer Select_Limit = 600;
    // 分页用 end

    // 明细结果
    public List<RaesInfo> raesInfoList { get; set; }

    // 明细条数
    public Integer getRaesInfoListSize() {
        return raesInfoList.size();
    }
    // 分页end
    
    public List<List<RaesInfo>> raesInfoListList { get; set; }

    public RentalApplySequenceController() {
        isEquipmentCenter = true; // 是备品中心
        is2B1 = UserInfo.getProfileId() == System.Label.ProfileId_EquipmentCenter;
        cunfangdiSet = new Set<String>();
        benbuSet = new Set<String>();
        agencySet = new Set<String>();
        // bpflSet = new Set<String>();
        // productSet = new Set<String>();
        S_Ra_Person = new Rental_Apply__c();
        S_Ra_Person.Person_In_Charge__c = null;
        S_bieBenBu = '';
        S_bieCunFangDi = '';
        S_Agency = '';
        S_bieBeiPinFenLei = '';
        S_Product_category = '';

        currPage = 1;
        totalPage = 1;
        selRecordOption = '20';
        totalRecords = 0;
        raesInfoListList = new List<List<RaesInfo>>();

        // test
        checkEventId = '';
        frameUrl = '';

    }
    // 对明细行进行分页
    private void setupRaesInfoList(List<RaesInfo> raesInfoList) {
        list<List<RaesInfo>> tempraesInfoListList = new list<List<RaesInfo>>();
        List<RaesInfo> tempraesInfoList = new List<RaesInfo>();
        for (RaesInfo tempRaesInfo : raesInfoList) {
            if (tempraesInfoList.size() >= selctRecordNum) {
                tempraesInfoListList.add(tempraesInfoList);
                tempraesInfoList = new List<RaesInfo>();
            }
            tempraesInfoList.add(tempRaesInfo);
        }
        tempraesInfoListList.add(tempraesInfoList);
        totalPage = tempraesInfoListList.size();
        if (tempraesInfoList.size() == 0) {
            totalPage --;
        }
        totalRecords = raesInfoList.size();
        currPage = 1;
        raesInfoListList = tempraesInfoListList.clone();
    }
    // 画面初始化
    public void init() {
        // System.Label.ProfileId_EquCenAdmin 00e10000000xnodAAA,00e100000012CwKAAU 2B3_备品中心管理者
        // System.Label.ProfileId_EquCenAdminPic 00e100000012CwKAAU 2B3_备品中心管理者(照片)
        // System.Label.ProfileId_EquCenCheckAndDepot 00e10000000xnoYAAQ,00e100000012CwPAAU 2B2_备品中心检测&仓库管理、2B2_备品中心检测&仓库管理(照片)
        // System.Label.ProfileId_EquipmentCenter   00e10000000xnoTAAQ 2B1_备品中心受理窗口
        // 当前用户 在上述简档中 则认为是备品中心/管理员
        if(UserInfo.getProfileId() != System.Label.ProfileId_SystemAdmin
            && UserInfo.getProfileId() != System.Label.ProfileId_IThelp 
            && !System.Label.ProfileId_EquCenAdmin.contains(UserInfo.getProfileId())
            && UserInfo.getProfileId() != System.Label.ProfileId_EquipmentCenter 
            // && !System.Label.ProfileId_EquCenCheckAndDepot.contains(UserInfo.getProfileId())                 
        ){
            isEquipmentCenter = false; // 不是备品中心
        }
        
        /*String soql_Ra = 'SELECT Id , Person_In_Charge__c  FROM Rental_Apply__c WHERE ';
        if(isEquipmentCenter){
            soql_Ra += 'id = \''+System.label.Rental_Apply_id +'\''; 
        }else{
            soql_Ra += 'Person_In_Charge__c = \''+Userinfo.getUserId()+'\'';
        }
        soql_Ra += ' LIMIT 1';
        S_Ra_Person = Database.query(soql_Ra);
        S_Ra_Person.Person_In_Charge__c = null;*/
        // 2B2简档
        if(System.Label.ProfileId_EquCenCheckAndDepot.contains(UserInfo.getProfileId())){
            String soql_Ra = 'SELECT Id , Person_In_Charge__c  FROM Rental_Apply__c WHERE ';
            soql_Ra += 'id = \''+System.label.Rental_Apply_id +'\''; 
            soql_Ra += ' LIMIT 1';
            S_Ra_Person = Database.query(soql_Ra);
            S_Ra_Person.Person_In_Charge__c = null;
        }
        if(isEquipmentCenter){
        }else{
            // 判断用户所属备品中心 暂时先使用分公司判断吧
            User u = [SELECT Id,name,Branch__c FROM User WHERE Id = :UserInfo.getUserId()]; 
            S_bieCunFangDi = u.Branch__c+' 备品中心';
            raesdList = getData(S_raName,S_Fixture_Model_No,S_Ra_Person,S_bieBenBu,S_bieCunFangDi,benbuSet,agencySet,S_bieBeiPinFenLei,S_Product_category);
        }
        // raesInfoList = new List<RaesInfo>();
        
        // raesdList = getData(S_raName,S_Fixture_Model_No,S_Ra_Person,S_bieBenBu,S_bieCunFangDi,benbuSet,agencySet,bpflSet,productSet);
        raesdList = getData(S_raName,S_Fixture_Model_No,S_Ra_Person,S_bieBenBu,S_bieCunFangDi,benbuSet,agencySet,S_bieBeiPinFenLei,S_Product_category);
        // 作成明细行
        getRaesInfoList(raesdList);
    }
    public  void checkEvent() {
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, 'zheli:' + checkEventId));
        if(String.isNotBlank(checkEventId)){
            String iframeType = checkEventId.split(';')[0];
            String iframeId = checkEventId.split(';')[1];
            if(iframeType == '1'){
                frameUrl = '/apex/QueuePageByAssetId?parentId='+iframeId;
            }
            if(iframeType == '2'){
                frameUrl = '/apex/ReantalApplySeriesNo?raqId='+iframeId;
            }
        }        
    }
    // 检索按钮
    public PageReference searchBtn() {
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, S_ApplyBenBu));
        // 申请者本部
        benbuSet = new Set<String>();
        agencySet = new Set<String>();
        // bpflSet = new Set<String>();
        // productSet = new Set<String>();
        if(String.isNotBlank(S_ApplyBenBu)){
            List<String> benbuList = S_ApplyBenBu.split(',');
            benbuSet.addAll(benbuList);
        }
        // 办事处
        if(String.isNotBlank(S_Agency)){
            List<String> agencyList = S_Agency.split(',');
            agencySet.addAll(agencyList);
        }
        // 备品分类
        // if(String.isNotBlank(S_bieBeiPinFenLei)){
        //     List<String> tempList = S_bieBeiPinFenLei.split(';');
        //     bpflSet.addAll(tempList);
        // }
        // 产品分类
        // if(String.isNotBlank(S_Product_category)){
        //     List<String> tempList = S_Product_category.split(';');
        //     productSet.addAll(tempList);
        // }
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, 'zheli:' + S_Ra_Person));
        // raesdList = getData(S_raName,S_Fixture_Model_No,S_Ra_Person,S_bieBenBu,S_bieCunFangDi,benbuSet,agencySet,bpflSet,productSet);
        raesdList = getData(S_raName,S_Fixture_Model_No,S_Ra_Person,S_bieBenBu,S_bieCunFangDi,benbuSet,agencySet,S_bieBeiPinFenLei,S_Product_category);
        currPage = 1;
        getRaesInfoList(raesdList);
        frameUrl = '';        
        return null;
    }
    // 作成明细行
    private void getRaesInfoList(List<Rental_Apply_Equipment_Set_Detail__c> raesList) {
        Boolean overLimit = false;
        // 序列号
        Set<Id> raesdIdSet = new Set<Id>();
        // 其他明细作成
        for (Integer i = 0; i < raesList.size(); i++) {
            raesdIdSet.add(raesList[i].Id);
        }        
        // 遍历生成 序列号相关信息
        Map<String,List<Rental_Apply_Sequence__c>> MapKeyRaq = new Map<String,List<Rental_Apply_Sequence__c>>();
        Map<String,List<Rental_Apply_Sequence__c>> MapRaq = new Map<String,List<Rental_Apply_Sequence__c>>();
        List<Rental_Apply_Sequence__c> raqList = [Select Id,Apply_Set_Detail_ExternalKey__c,Apply_Set_Detail__c,Series_No__c,Fixture_Model_No__c,Internal_asset_location__c,Salesdepartment__c,Equipment_Type__c,Product_category__c,Invalid_Flag__c 
                From Rental_Apply_Sequence__c
                where Invalid_Flag__c = false
                and  Apply_Set_Detail__c In :raesdIdSet 
                // order by Apply_Set_Detail_ExternalKey__c,Series_No__c ASC nulls last];
                order by Apply_Set_Detail__c,Series_No__c ASC nulls last];
        for(Rental_Apply_Sequence__c raq:raqList){
            List<Rental_Apply_Sequence__c> tempList = new List<Rental_Apply_Sequence__c>();
            if (MapRaq.containsKey(raq.Apply_Set_Detail__c)) {
                tempList = MapRaq.get(raq.Apply_Set_Detail__c);
            }
            tempList.add(raq);
            MapRaq.put(raq.Apply_Set_Detail__c,tempList);
        }
        /*for(Rental_Apply_Sequence__c raq:raqList){
            List<Rental_Apply_Sequence__c> tempList = new List<Rental_Apply_Sequence__c>();
            String Serieskey = raq.Fixture_Model_No__c+raq.Internal_asset_location__c+raq.Internal_asset_location__c+raq.Salesdepartment__c+raq.Equipment_Type__c+raq.Product_category__c;
            if(String.isNotBlank(Serieskey)){
                if(MapKeyRaq.containsKey(Serieskey)){
                    tempList = MapKeyRaq.get(Serieskey);
                }
                tempList.add(raq);
                MapKeyRaq.put(Serieskey,tempList);
            }
        }
        for(String key:MapKeyRaq.keySet()){
            List<Rental_Apply_Sequence__c> raqKeyList = MapKeyRaq.get(key);
            for(Integer i=0;i < raqKeyList.size();i++){
                List<Rental_Apply_Sequence__c> tempList = new List<Rental_Apply_Sequence__c>();
                if(MapRaq.containsKey(raqKeyList[i].Apply_Set_Detail__c)){
                    tempList = MapRaq.get(raqKeyList[i].Apply_Set_Detail__c);
                }
                raqKeyList[i].Series_No__c = i+1;
                tempList.add(raqKeyList[i]);
                MapRaq.put(raqKeyList[i].Apply_Set_Detail__c,tempList);
            }
        }*/
        raesInfoList = new List<RaesInfo>();
        Integer selectCnt = raesInfoList.size();
        // 其他明细作成
        for (Integer i = 0; i < raesList.size(); i++) {
            // 201を超えた場合前200のみを出す
            if (selectCnt + i >= Select_Limit) {overLimit = true; break;}
            // 作成明细行
            List<Rental_Apply_Sequence__c> raqListT = new List<Rental_Apply_Sequence__c>();
            if(MapRaq.size() > 0){
                raqListT = MapRaq.get(raesList[i].Id);
            }
            RaesInfo raesinfo = new RaesInfo(raesList[i],raqListT);
            raesInfoList.add(raesinfo);
        }
        // 显示数据条数信息
        if (overLimit) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '数据超过' + Select_Limit + '条，只显示前' + Select_Limit + '条'));
        } else {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '共有' + getRaesInfoListSize() + '条数据'));
        }
        setupRaesInfoList(raesInfoList);
    }
    // private List<Rental_Apply_Equipment_Set_Detail__c> getData(String SraName,String SFixture_Model_No,Rental_Apply__c SRa_Person,String pdBenBu,String pdCunFangDi,Set<String> benbuApplySet,Set<String> applyAgencySet,Set<String> pdBeiPinFenLei,Set<String> pdProduct_category) {
    private List<Rental_Apply_Equipment_Set_Detail__c> getData(String SraName,String SFixture_Model_No,Rental_Apply__c SRa_Person,String pdBenBu,String pdCunFangDi,Set<String> benbuApplySet,Set<String> applyAgencySet,String pdBeiPinFenLei,String pdProduct_category) {
        String soql = '';
        soql += 'select Id,Name,Rental_Apply__c,Fixture_Model_No__c,Rental_Apply_Equipment_Set__c, ';
        soql += ' Salesdepartment_before__c,Equipment_Type_text__c,Product_category_text__c ,';
        soql += ' Rental_Apply_Equipment_Set__r.QueueShippmentDateNew__c,';
        soql += ' Rental_Apply__r.Salesdepartment_text__c,Rental_Apply__r.Internal_asset_location_F__c,Internal_asset_location_before__c, ';
        soql += ' Rental_Apply__r.WorkPlace__c,Rental_Apply__r.Person_In_Charge__c ,Queue_Number__c';
        soql += '  from Rental_Apply_Equipment_Set_Detail__c ';
        soql += ' where Cancel_Select__c = false  and  Queue_Number__c > 0 ';
        if(String.isNotBlank(SraName)){
            soql += ' and Rental_Apply__r.Name like \'%'+SraName+'%\'';
        }
        if(String.isNotBlank(SFixture_Model_No)){
            // soql += ' and Fixture_Model_No__c = :SFixture_Model_No';
            soql += ' and Fixture_Model_No__c like \'%'+SFixture_Model_No+'%\'';
        }
        //Rental_Apply__c SRa_Person,
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, 'zheli00:' + SRa_Person));
        if(SRa_Person.Person_In_Charge__c != null){
            String tempId = SRa_Person.Person_In_Charge__c;
            soql += ' and Rental_Apply__r.Person_In_Charge__c = :tempId';
        }
        // String pdBenBu
        if(String.isNotBlank(pdBenBu)){
            soql += ' and Salesdepartment_before__c = :pdBenBu';
        }
        // String pdCunFangDi
        if(String.isNotBlank(pdCunFangDi) && pdCunFangDi != 'All'){
            soql += ' and Internal_asset_location_before__c = :pdCunFangDi';

        }
        // Set<String> benbuApplySet
        if(benbuApplySet.size() > 0){
            soql += ' and Rental_Apply__r.Salesdepartment_text__c IN :benbuApplySet';
        }
        // Set<String> applyAgencySet
        if(applyAgencySet.size() > 0){
            soql += ' and Rental_Apply__r.WorkPlace__c IN :applyAgencySet';
        }
        // Set<String> pdBeiPinFenLei
        // if(pdBeiPinFenLei.size() > 0){
        //  soql += ' and Equipment_Type_text__c IN :pdBeiPinFenLei';
        // }
        // String pdBeiPinFenLei
        if(String.isNotBlank(pdBeiPinFenLei)){
            soql += ' and Equipment_Type_text__c =:pdBeiPinFenLei';
        }
        // Set<String> pdProduct_category
        // if(pdProduct_category.size() > 0){
        //  soql += ' and Product_category_text__c IN :pdProduct_category';
        // }
        // String pdProduct_category
        if(String.isNotBlank(pdProduct_category)){
            soql += ' and Product_category_text__c =:pdProduct_category';
        }
        soql += ' limit ' + (Select_Limit + 1);
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, 'zhesoql:' +SraName+'~'+pdCunFangDi+'~' +benbuApplySet +'~'+soql));
        system.debug('====soql:' + soql);
        return Database.query(soql);
    }
    //别存放地 SelectOption
    public List<SelectOption> getbieCunFangDiOps() {
        cunfangdiSet = new Set<String>();
        List<SelectOption> opList;
        if (UserInfo.getProfileId() == System.Label.ProfileId_SystemAdmin
                || System.Label.ProfileId_EquCenAdmin.contains(UserInfo.getProfileId())
                || is2B1) {
            opList = FixtureUtil.bieCunFangDiOpsMap.get('备品管理中心');
        } else {
            opList = new List<SelectOption>{
                new SelectOption(S_bieCunFangDi, S_bieCunFangDi)
            };
        }

        for (SelectOption op : opList) {
            if (String.isNotBlank(op.getValue())) {
                cunfangdiSet.add(op.getValue());
            }
        }
        return opList;
    }
    // 申请人本部
    public List<CustomData> getSApplyBenBu() {
        //所在地区(本部) 现在
        String tempS = S_bieCunFangDi;
        tempS = String.isNotBlank(tempS)?tempS:'All';
        List<SelectOption> opList = FixtureUtil.bieBenBuOpsMap.get(tempS);
        List<CustomData> ApplyBenBu = new List<CustomData>();
        // if(String.isNotBlank(S_bieCunFangDi)){
            for (SelectOption op : opList) {
                if (String.isNotBlank(op.getValue())) {
                    ApplyBenBu.add(new CustomData(op.getValue(),op.getValue()));
                }
            }
        // }
        return ApplyBenBu;
    }

    // 申请者办事处 
    public List<CustomData> getSApplyAgency() {
        List<CustomData> ApplyAgency = new List<CustomData>();
        List<SelectOption>  options = FixtureUtil.getPlickList('User', 'Work_Location__c');
        for (SelectOption op : options) {
            if (String.isNotBlank(op.getValue())) {
                ApplyAgency.add(new CustomData(op.getValue(),op.getValue()));
            }
        }
        return ApplyAgency;
    }

    //产品分类 SelectOption
    public List<SelectOption> getbieChanPinFenLeiOps() {
        //产品分类(GI/SP) F Product_category_F__c
        // return FixtureUtil.bieChanPinFenLeiOpsMap.get(sonObj.Product_category_F__c);
        List<SelectOption> pickListValuesList = FixtureUtil.bieChanPinFenLeiOpsMap.get('GISP');
        pickListValuesList.add(new SelectOption('GI,SP', 'GI,SP'));
        return pickListValuesList;
    }
    //别备品分类 SelectOption
    public List<SelectOption> getbieBeiPinFenLeiOps() {
        //备品分类(现在) Equipment_Type__c
        // return FixtureUtil.bieBeiPinFenLeiOpsMap.get(sonObj.Equipment_Type__c);
        List<SelectOption> pickListValuesList = FixtureUtil.bieBeiPinFenLeiOpsMap.get('备品分类');
        pickListValuesList.add(new SelectOption('产品试用,学会展会', '产品试用,学会展会'));
        pickListValuesList.add(new SelectOption('维修代用（一般维修）,维修代用（保修合同）','维修代用（一般维修）,维修代用（保修合同）'));
        return pickListValuesList;
    }
    /**
     * 多选选项列表
     */
    class CustomData {
        //id
        public String parameterId { get; private set; }
        //name
        public String parameterName { get; private set; }  

        public CustomData(String accountId,String accountName){
            parameterId = accountId;
            parameterName = accountName;
        }    
    }
    class RaesInfo  {
        public Rental_Apply_Equipment_Set_Detail__c raesd {get; set;}
        public List<Rental_Apply_Sequence__c> raqList {get; set;}
        public RaesInfo(Rental_Apply_Equipment_Set_Detail__c r,List<Rental_Apply_Sequence__c> qL) {
            raesd = r;
            raqList = qL;
        }
    }
}