public without sharing class EquipmentLoanerApplyController {
	// 样机借出申请ID
    private String loanerApplyId;
    public Asset rec { get; set; }
    public String assName { get; set; }
    public String assECcode { get; set; }

    public string userType {get;private set; }

    /*****************排序用******************/
    public String sortKey { get; set; }
    public String setId { get; set; }
    public String preSortKey { get; private set; }
    public Boolean sortOrderAsc { get; private set; }
    public Boolean isManager { get; private set; }
    //public Boolean isCancel { get; private set; }
    public String[] sortOrder { get; private set; }
    private String[] columus = new String[]{ 'SerialNumber', 'OT_Code__c', 'EC_Code__c','loaner_place__c', 'Status'};

    public Boolean getcanSave() {
        return ((loanerApply.Status__c != '草案中' && loanerApply.Status__c != '驳回' && isManager == false));
        }
    public Boolean getcanSearch() {
        return loanerApply.Loaner_LendOrder__c;
    }

    //准备天数
    private Integer prepareDay;
    private Integer dayCount = 0;
    // 显示数据条数限制
    private Integer Select_Limit = 200;
    private Boolean Over_Limit = false;

    /*****************画面表示Bean******************/
    public loaner_application__c loanerApply { get; set; }
    //显示明细
    public List<EquipmentSetInfo> equipmentSetRecords { get; set; }

    // 样机Set
    public List<EquipmentSetInfo> loanerSetRecords { get; set; }

    List<loaner_application_detail__c> del = New List<loaner_application_detail__c>();

    // 样机Set
    private List<String> ecCodeList;

    // 已选择样机
    private List<String> loanerAssetSelected = new List<String>();

    public Integer pageRecordNo { 
        get {
            return equipmentSetRecords == null ? 0 : equipmentSetRecords.size();
        }
    }

    public Integer loanerSetNo {
        get {
            return loanerSetRecords == null ? 0 : loanerSetRecords.size();
        }
    }

	public EquipmentLoanerApplyController() {
		// 获得传入参数
        loanerApplyId = ApexPages.currentPage().getParameters().get('loid');
        equipmentSetRecords = new List<EquipmentSetInfo>();
	}

	// 画面初始化
    public void init() {
        userType = UserInfo.getUserType();
        // 默认排序
        this.sortKey = '0';
        this.preSortKey = '0';
        this.sortOrderAsc = true;
        //this.isCancel = false;
        this.sortOrder = new String[4];
        this.sortOrder = new String[]{ '　', '　', '　', '　', '　','↑'};
        prepareDay = 0;
        Over_Limit = false;
        isManager = false;
        List<String> profileIdList = new List<String>();
        Map<String,String> profileIdMap = new Map<String,String>();
        List<String> lend_DetName = new List<String>();
        // String profileId = UserInfo.getProfileId().subString(0, 15);

        //新的获取简档ID  calendarUtil.getMemberProfileID  这里用到的人员ID 和获取到的简档ID都是15位的
        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));

        profileIdList = System.label.LoanerManager.split(',');
        if(profileIdList.size() > 0){
            for(String str : profileIdList){
                profileIdMap.put(str, str);
            }
        }

        if(profileIdMap.containsKey(new_profileId.subString(0,15))){
            isManager = true;
        }

        /*User userInfo = [SELECT Id,Is_Cancel_Jurisdiction__c FROM User WHERE Id = :UserInfo.getUserId()];
        if(userInfo.Is_Cancel_Jurisdiction__c) this.isCancel = true;*/

    	if (String.isNotBlank(loanerApplyId)) {
    		loanerApply = [SELECT id,Name,Demo_purpose__c,EC_Code_1__c,EC_Code_2__c,EC_Code_3__c,EC_Code_4__c,
    							EC_Code_5__c,EC_Code_6__c,EC_Code_7__c,EC_Code_8__c,EC_Code_9__c,
    							EC_Code_10__c,Prepare_Day__c,Rental_Start_Date__c,Rental_End_Date__c,EC_Code_11__c
                                ,EC_Code_12__c,EC_Code_13__c,EC_Code_14__c,EC_Code_15__c,EC_Code_16__c
                                ,EC_Code_17__c,EC_Code_18__c,EC_Code_19__c,EC_Code_20__c,Status__c,Equipment_Type__c
                                ,Loaner_LendFrom__c,Loaner_LendOrder__c,Manager_detail_Del__c
                                ,Loaner_LendFrom__r.Rental_Start_Date__c,Loaner_LendFrom__r.Rental_End_Date__c,Approval_Status__c
                                ,DealerOrder_From__c,Approval_Step__c,Request_shipping_Date__c,Remind_Date__c
                                ,Loaner_LendUser1__c,Loaner_LendUser2__c,Loaner_LendUser3__c,Loaner_LendUser4__c
                                ,Loaner_LendUser5__c,ProductCount19__c,ProductCount20__c,AllLead_OrderName__c
                                ,ProductCount1__c,ProductCount2__c,ProductCount3__c,ProductCount4__c,ProductCount5__c,ProductCount6__c
                                ,ProductCount7__c,ProductCount8__c,ProductCount9__c,ProductCount10__c,ProductCount11__c,ProductCount12__c
                                ,ProductCount13__c,ProductCount14__c,ProductCount15__c,ProductCount16__c,ProductCount17__c,ProductCount18__c
    						FROM loaner_application__c WHERE Id = :loanerApplyId ];

            rec = new Asset();
            rec.Equipment_Type__c = loanerApply.Equipment_Type__c;
            ecCodeList = new List<String>();
            if(String.isNotBlank(loanerApply.EC_Code_1__c)) ecCodeList.add(loanerApply.EC_Code_1__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_2__c)) ecCodeList.add(loanerApply.EC_Code_2__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_3__c)) ecCodeList.add(loanerApply.EC_Code_3__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_4__c)) ecCodeList.add(loanerApply.EC_Code_4__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_5__c)) ecCodeList.add(loanerApply.EC_Code_5__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_6__c)) ecCodeList.add(loanerApply.EC_Code_6__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_7__c)) ecCodeList.add(loanerApply.EC_Code_7__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_8__c)) ecCodeList.add(loanerApply.EC_Code_8__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_9__c)) ecCodeList.add(loanerApply.EC_Code_9__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_10__c)) ecCodeList.add(loanerApply.EC_Code_10__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_11__c)) ecCodeList.add(loanerApply.EC_Code_11__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_12__c)) ecCodeList.add(loanerApply.EC_Code_12__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_13__c)) ecCodeList.add(loanerApply.EC_Code_13__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_14__c)) ecCodeList.add(loanerApply.EC_Code_14__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_15__c)) ecCodeList.add(loanerApply.EC_Code_15__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_16__c)) ecCodeList.add(loanerApply.EC_Code_16__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_17__c)) ecCodeList.add(loanerApply.EC_Code_17__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_18__c)) ecCodeList.add(loanerApply.EC_Code_18__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_19__c)) ecCodeList.add(loanerApply.EC_Code_19__c.trim());
            if(String.isNotBlank(loanerApply.EC_Code_20__c)) ecCodeList.add(loanerApply.EC_Code_20__c.trim());
            if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
                dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
            }

    		// 已存在样机借出明细历史取得
            List<loaner_application_detail__c> loanerApplyDetSelected = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,LOANER__r.AssetType__c,LOANER__r.Description,
            							LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,LOANER__r.Rental_Start_Date__c 
                                        ,LOANER__r.Count_can_allocate_F__c,LOANER__r.RecordTypeId,loaner_ApplyNo__c,RAESD_Status__c,LOANER__r.Name
                                        ,Allocated_Det__c,LendPrimary_Name__c,Inspection_result__c,delivery_company__c,Tracking_Number__c
                                        ,Return_to_wh_staff__c,Allocate_Date__c,StockDown_Date__c,Pre_inspection_Date__c,Shipment_Request_Date__c
                                        ,Receipt_Date__c,StockDown__c,Receipt_Status__c,Equipment_Type__c,LOANER__r.loaner_place__c,loaner_application__c
                                        ,loaner_application__r.Status__c,LOANER__r.Equipment_Type__c,loanerOrder_Status__c,Remark__c,LOANER__r.Remarks2__c
                                        ,loaner_application__r.loaner_request_number__c,LOANER__r.Rental_Customer__r.Name,LOANER__r.Rental_End_Date__c,LOANER__r.ProductName__c
                                     from  loaner_application_detail__c
                                     where loaner_application__c = :loanerApplyId
                                     order by Name];
        	for(Integer i = 0; i < loanerApplyDetSelected.size(); i++){
                if (i == Select_Limit) {Over_Limit=true; break;}
                EquipmentSetInfo midData = null;
                if(loanerApplyDetSelected[i].LendPrimary_Name__c != null){
                    lend_DetName.add(loanerApplyDetSelected[i].LendPrimary_Name__c);
                    midData = new EquipmentSetInfo(loanerApplyDetSelected[i]);
                    midData.firstDet = true;
                }else{
                    midData = new EquipmentSetInfo(loanerApplyDetSelected[i]);
                }
                loanerAssetSelected.add(loanerApplyDetSelected[i].LOANER__c);
        		equipmentSetRecords.add(midData);
        	}


            // 样机转借数据
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '[借出开始日]必须输入转借申请单开始和结束之间的日期。'));
            if(loanerApply.Loaner_LendOrder__c && loanerApply.DealerOrder_From__c != null){
                List<loaner_application_detail__c> loanerApplyLendDetSelected = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,LOANER__r.AssetType__c,LOANER__r.Description,
                                            LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,LOANER__r.Rental_Start_Date__c 
                                            ,LOANER__r.Count_can_allocate_F__c,LOANER__r.RecordTypeId,loaner_ApplyNo__c,RAESD_Status__c,LOANER__r.Name
                                            ,Allocated_Det__c,LendPrimary_Name__c,Inspection_result__c,delivery_company__c,Tracking_Number__c
                                        ,Return_to_wh_staff__c,Allocate_Date__c,StockDown_Date__c,Pre_inspection_Date__c,Shipment_Request_Date__c
                                        ,Receipt_Date__c,StockDown__c,Receipt_Status__c,Equipment_Type__c,LOANER__r.loaner_place__c,loaner_application__c
                                        ,loaner_application__r.Status__c,LOANER__r.Equipment_Type__c,Remark__c,LOANER__r.Remarks2__c,loaner_application__r.loaner_request_number__c
                                        ,LOANER__r.Rental_Customer__r.Name,LOANER__r.Rental_End_Date__c,LOANER__r.ProductName__c,is_distribution__c
                                         from  loaner_application_detail__c
                                         where DealerID__c = :String.valueOf(loanerApply.DealerOrder_From__c).subString(0,15)
                                         AND Id not in : lend_DetName
                                         AND Lend_Det__c = true 
                                         AND is_distribution__c = false 
                                         order by Name];
                system.debug('111'+loanerApplyLendDetSelected.size());
                system.debug('111'+lend_DetName);
                system.debug(loanerApply.DealerOrder_From__c);
                for(Integer i = 0; i < loanerApplyLendDetSelected.size(); i++){
                    if (i == Select_Limit) {Over_Limit=true; break;}
                    loanerAssetSelected.add(loanerApplyLendDetSelected[i].LOANER__c);
                    EquipmentSetInfo midData = new EquipmentSetInfo(loanerApplyLendDetSelected[i]);
                    midData.firstDet = true;
                    midData.check = false;
                    midData.oldcheck = false;
                    equipmentSetRecords.add(midData);
                }
                system.debug(equipmentSetRecords.size());
            }

            prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
            loanerApply.Prepare_Day__c = prepareDay;

            //其他已存在的样机借出历史
            /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
                                        LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
                                        loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
                                        ,Allocated_Det__c,LendPrimary_Name__c
                                     from  loaner_application_detail__c
                                     where loaner_application__c != :loanerApplyId
                                     and LOANER__c in :loanerAssetSelected
                                     AND Arrival_wh_Date__c = null
                                     AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
                                     and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
                                     or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
                                     AND StockUp__c = false
                                     order by Name];
            Map<String, Date> othersMap = new Map<String,Date>();

            for (loaner_application_detail__c other : others) {
                if (othersMap.containsKey(other.LOANER__c)) {
                    continue;
                } else {
                    if(other.Received_loaner_Date__c == null){
                        othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
                    }else{
                        othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
                    }
                }
            }*/

            for (EquipmentSetInfo info : equipmentSetRecords) {
                info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
                info.Rental_End_Date = loanerApply.Rental_End_Date__c;
                info.SEdayCount  = dayCount;
                /*if(info.aset.Status == '在库'){
                    if(othersMap.containsKey(info.aset.Id)){
                        info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
                    }else{
                        info.earliest_Lend_Date = Date.today();
                    }
                }*/
            }
    	}
        this.getLoanerSet();
        if(loanerApply.Equipment_Type__c != 'BS'){
            this.getDefaultLoSet();
        }
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'equipmentSetRecords + ' + equipmentSetRecords));
        // 显示数据条数信息
        makeMessage();
        system.debug(equipmentSetRecords);
        system.debug(equipmentSetRecords.size());

    }
    // 获取借出元的所有用户
    public void getleadUser() {
        if(loanerApply.DealerOrder_From__c != null){
            List<user> userList = [SELECT Id
                                   FROM user
                                   WHERE AccountId = :loanerApply.DealerOrder_From__c
                                    AND IsActive = true];
            Integer i = 1;
            for(user us: userList){
                String column = 'Loaner_LendUser' + i + '__c';
                loanerApply.put(column,us.Id);
                i++;
            }
        }
    }
    // 获取样机套装
    public void getLoanerSet() {
        // 所有样机Set
        loanerSetRecords = new List<EquipmentSetInfo>();
        List<loaner_Set__c> loanerSetSearch = [select Id,set_type__c, Name, Equipment_Type__c,Remarks__c,SerialNumber__c,Internal_Asset_number__c,Status__c,loaner_place__c,Reservation_information__c
                                                 from  Loaner_Set__c
                                                 WHERE Equipment_Type__c = :loanerApply.Equipment_Type__c
                                                 order by Name];
        Integer line = 0;
        for(loaner_Set__c ls : loanerSetSearch){
            EquipmentSetInfo li = new EquipmentSetInfo(line, ls);
            loanerSetRecords.add(li);
            line += 1;
        }
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'loanerSetRecords' + loanerSetRecords));
    }

    // 获取申请单中默认样机
    public void getDefaultLoSet() {
        system.debug('getDefaultLoSet');
        List<String> lend_DetName = new List<String>();
        //已选择个体管理样机
        List<String> loanerindividualList = new List<String>();
        //// 画面已打勾的明细保留
        List<EquipmentSetInfo> selectedloanerRecords = new List<EquipmentSetInfo>();
        for (EquipmentSetInfo info : equipmentSetRecords) {
            if (info.check == true) {
                selectedloanerRecords.add(info);
                if(String.isNotEmpty(info.lad.LendPrimary_Name__c)){
                    lend_DetName.add(info.lad.LendPrimary_Name__c);
                }
                if(String.valueOf(info.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
                    loanerindividualList.add(info.aset.Id);
                }
            }
        }
        equipmentSetRecords = new List<EquipmentSetInfo>();
        loanerAssetSelected = new list<String>();
        for (EquipmentSetInfo info : selectedloanerRecords) {
            loanerAssetSelected.add(info.aset.Id);
        }

        // 已存在明细行做成
        equipmentSetRecords.addAll(selectedloanerRecords);
        // 所有ECcode样机

        //loanerSetRecords = new List<loaner_Set__c>();
        //转借分支
        if(loanerApply.Loaner_LendOrder__c){
            List<loaner_application_detail__c> loanerApplyLendDetSelected = new List<loaner_application_detail__c>();
            if(ecCodeList.size() > 0){
                loanerApplyLendDetSelected = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,LOANER__r.AssetType__c,LOANER__r.Description,LOANER__r.Rental_Start_Date__c,
                                            LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status
                                            ,LOANER__r.Count_can_allocate_F__c,LOANER__r.RecordTypeId,loaner_ApplyNo__c,RAESD_Status__c
                                            ,Allocated_Det__c,LendPrimary_Name__c,Inspection_result__c,delivery_company__c,Tracking_Number__c
                                        ,Return_to_wh_staff__c,Allocate_Date__c,StockDown_Date__c,Pre_inspection_Date__c,Shipment_Request_Date__c
                                        ,Receipt_Date__c,StockDown__c,Receipt_Status__c,Equipment_Type__c,LOANER__r.loaner_place__c,loaner_application__c
                                        ,loaner_application__r.Status__c,LOANER__r.Equipment_Type__c,Remark__c,LOANER__r.Remarks2__c,loaner_application__r.loaner_request_number__c
                                        ,LOANER__r.Rental_Customer__r.Name,LOANER__r.Rental_End_Date__c,LOANER__r.ProductName__c,LOANER__r.Name
                                     from  loaner_application_detail__c
                                     where DealerID__c = :String.valueOf(loanerApply.DealerOrder_From__c).subString(0,15)
                                     AND Id not in : lend_DetName
                                     AND LOANER__r.EC_Code__c in : ecCodeList
                                     AND Lend_Det__c = true 
                                     AND is_distribution__c = false 
                                     order by Name];
                system.debug('1');
     //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'loanerApplyLendDetSelected. ' + loanerApplyLendDetSelected.size()));
     //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'ecCodeList.' + ecCodeList.size()));
            }else{
                loanerApplyLendDetSelected = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,LOANER__r.AssetType__c,LOANER__r.Rental_Start_Date__c,
                                            LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,LOANER__r.Description
                                            ,LOANER__r.Count_can_allocate_F__c,LOANER__r.RecordTypeId,loaner_ApplyNo__c,RAESD_Status__c
                                            ,Allocated_Det__c,LendPrimary_Name__c,Inspection_result__c,delivery_company__c,Tracking_Number__c
                                        ,Return_to_wh_staff__c,Allocate_Date__c,StockDown_Date__c,Pre_inspection_Date__c,Shipment_Request_Date__c
                                        ,Receipt_Date__c,StockDown__c,Receipt_Status__c,Equipment_Type__c,LOANER__r.loaner_place__c,loaner_application__c
                                        ,loaner_application__r.Status__c,LOANER__r.Equipment_Type__c,Remark__c,LOANER__r.Remarks2__c,loaner_application__r.loaner_request_number__c
                                        ,LOANER__r.Rental_Customer__r.Name,LOANER__r.Rental_End_Date__c,LOANER__r.ProductName__c,LOANER__r.Name
                                     from  loaner_application_detail__c
                                     where DealerID__c = :String.valueOf(loanerApply.DealerOrder_From__c).subString(0,15)
                                     AND Id not in : lend_DetName
                                     AND Lend_Det__c = true 
                                     AND is_distribution__c = false 
                                     order by Name];
                system.debug('2');
            }
            
            for(Integer i = 0; i < loanerApplyLendDetSelected.size(); i++){
                if (i == Select_Limit) {Over_Limit=true; break;}
                loanerAssetSelected.add(loanerApplyLendDetSelected[i].LOANER__c);
                EquipmentSetInfo midData = new EquipmentSetInfo(loanerApplyLendDetSelected[i]);
                midData.firstDet = true;
                midData.check = false;
                midData.oldcheck = false;
                equipmentSetRecords.add(midData);
            }
            system.debug(equipmentSetRecords.size());
        }else{
            //非转借分支
            /* WLIG-C3N6BW XHL 样机分配显示其它分野的保有设备，故添加过滤条件
            AND Equipment_Type__c = :loanerApply.Equipment_Type__c
             */

            List<Asset> queryList = [select Id,Name, SerialNumber, Internal_Asset_number__c, OT_Code__c,AssetType__c,Description,
                                                EC_Code__c, status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c
                                                ,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c,Name__c,ProductName__c,Rental_Start_Date__c 
                                            from Asset
                                            WHERE EC_Code__c in : ecCodeList
                                            AND Id not in : loanerindividualList 
                                            AND Equipment_Type__c = :loanerApply.Equipment_Type__c
                                            order by EC_Code__c];
            for (Asset query : queryList) {
                loanerAssetSelected.add(query.Id);
            }
            system.debug(queryList);
            // 新明细行做成
            Integer j = 0;
            for (Integer i = 0;  i < queryList.size(); i++) {
                if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
                j++;
            }
        }
        if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
            dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
        }
        prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
        loanerApply.Prepare_Day__c = prepareDay;

        //其他已存在的样机借出历史
        /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
                                    LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
                                    loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
                                    ,Allocated_Det__c,LendPrimary_Name__c,Remark__c,LOANER__r.Remarks2__c
                                 from  loaner_application_detail__c
                                 where loaner_application__c != :loanerApplyId
                                 and LOANER__c in :loanerAssetSelected
                                 AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
                                 AND Arrival_wh_Date__c = null
                                and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
                                 or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
                                 AND StockUp__c = false
                                 order by Name];
                                 //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'others。' + others[0].Id));
        Map<String, Date> othersMap = new Map<String,Date>();

        for (loaner_application_detail__c other : others) {
            if (othersMap.containsKey(other.LOANER__c)) {
                continue;
            } else {
                if(other.Received_loaner_Date__c == null){
                    othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
                }else{
                    othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
                }
            }
        }*/
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'othersMap + ' + othersMap));

        for (EquipmentSetInfo info : equipmentSetRecords) {
            info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
            info.Rental_End_Date = loanerApply.Rental_End_Date__c;
            info.SEdayCount  = dayCount;
            /*if(info.aset.Status == '在库'){
                if(othersMap.containsKey(info.aset.Id)){
                    info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
                }else{
                    info.earliest_Lend_Date = Date.today();
                }
            }*/
        }
        system.debug('end');
    }

    // 获取样机套装
    public void getLoanerSetdet() {
        //已选择个体管理样机
        List<String> loanerindividualList = new List<String>();
        //// 画面已打勾的明细保留
        List<EquipmentSetInfo> selectedloanerRecords = new List<EquipmentSetInfo>();
        for (EquipmentSetInfo info : equipmentSetRecords) {
            if (info.check == true) {
                selectedloanerRecords.add(info);
                if(String.valueOf(info.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
                    loanerindividualList.add(info.aset.Id);
                }
            }
        }
        equipmentSetRecords = new List<EquipmentSetInfo>();
        loanerAssetSelected = new list<String>();
        for (EquipmentSetInfo info : selectedloanerRecords) {
            loanerAssetSelected.add(info.aset.Id);
        }

        // 已存在明细行做成
        equipmentSetRecords.addAll(selectedloanerRecords);

        // 样机set中所有样机
        List<String> loanerSetDetIDList = new List<String>();
        
        for(Loaner_Set_Detail__c lSD : [SELECT Id,Asset__c FROM Loaner_Set_Detail__c WHERE Loaner_Set__c = :setId]){
            loanerSetDetIDList.add(lSD.Asset__c);
        }
        /* WLIG-C3N6BW XHL 样机分配显示其它分野的保有设备，故添加过滤条件
            AND Equipment_Type__c = :loanerApply.Equipment_Type__c
         */
        List<Asset> queryList = [select Id,Name, SerialNumber, Internal_Asset_number__c,Name__c,AssetType__c,Loaner__c,Rental_Start_Date__c ,
                                        OT_Code__c, EC_Code__c, status,Count_can_allocate_F__c,Description,
                                        RecordTypeId,loaner_place__c,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c,ProductName__c
                                    from Asset
                                    where Id in :loanerSetDetIDList
                                    AND Id not in : loanerindividualList
                                    AND Equipment_Type__c = :loanerApply.Equipment_Type__c
                                    /*AND status = '在库'*/];
        for (Asset query : queryList) {
            loanerAssetSelected.add(query.Id);
        }
        // 新明细行做成
        Integer j = 0;
        for (Integer i = 0;  i < queryList.size(); i++) {
            if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
                j++;
            //}
        }
        if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
            dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
        }
        prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
        loanerApply.Prepare_Day__c = prepareDay;

        //其他已存在的样机借出历史
        /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
                                    LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
                                    loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
                                    ,Allocated_Det__c,LendPrimary_Name__c
                                 from  loaner_application_detail__c
                                 where loaner_application__c != :loanerApplyId
                                 and LOANER__c in :loanerAssetSelected
                                 AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
                                 AND Arrival_wh_Date__c = null
                                and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
                                 or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
                                 AND StockUp__c = false
                                 order by Name];
                                 //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'others。' + others[0].Id));
        Map<String, Date> othersMap = new Map<String,Date>();

        for (loaner_application_detail__c other : others) {
            if (othersMap.containsKey(other.LOANER__c)) {
                continue;
            } else {
                if(other.Received_loaner_Date__c == null){
                    othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
                }else{
                    othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
                }
            }
        }*/
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'othersMap + ' + othersMap));

        for (EquipmentSetInfo info : equipmentSetRecords) {
            info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
            info.Rental_End_Date = loanerApply.Rental_End_Date__c;
            info.SEdayCount  = dayCount;
            /*if(info.aset.Status == '在库'){
                if(othersMap.containsKey(info.aset.Id)){
                    info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
                }else{
                    info.earliest_Lend_Date = Date.today();
                }
            }*/
        }
    }

    // 检索样机
    public void searchLoanerApp() {
        //已选择个体管理样机
        List<String> loanerindividualList = new List<String>();
    	//// 画面已打勾的明细保留
    	List<EquipmentSetInfo> selectedloanerRecords = new List<EquipmentSetInfo>();
    	for (EquipmentSetInfo info : equipmentSetRecords) {
            if (info.check == true) {
                selectedloanerRecords.add(info);
                if(String.valueOf(info.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
                    loanerindividualList.add(info.aset.Id);
                }
            }else{
                if(info.oldcheck == true && info.lad != null){
                    del.add(info.lad);
                }
            }
        }
        equipmentSetRecords = new List<EquipmentSetInfo>();
        loanerAssetSelected = new list<String>();
        for (EquipmentSetInfo info : selectedloanerRecords) {
            loanerAssetSelected.add(info.aset.Id);  
        }
        // 已存在明细行做成
        equipmentSetRecords.addAll(selectedloanerRecords);
        // 所有ECcode样机
        String ecCodeTail = '(\'';
        for(Integer i = 0 ; i< ecCodeList.size();i++){
            if(i<ecCodeList.size()-1){
                ecCodeTail += ecCodeList[i]+'\',\'';
            }else{
                ecCodeTail += ecCodeList[i]+'\')';
            }
        }

        String loanerindTail = '(\'';
        for(Integer i = 0 ; i< loanerindividualList.size();i++){
            if(i<loanerindividualList.size()-1){
                loanerindTail += loanerindividualList[i]+'\',\'';
            }else{
                loanerindTail += loanerindividualList[i]+'\')';
            }
        }

        String soql = 'select Id,Name, SerialNumber, Loaner__c,Internal_Asset_number__c, OT_Code__c,EC_Code__c, Name__c,ProductName__c,AssetType__c,Description,Rental_Start_Date__c,';
              soql += ' status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c from Asset WHERE Id != null ';


        if (!String.isBlank(assName)) {
            soql += ' and Name like \'%' + String.escapeSingleQuotes(assName.trim().replaceAll('%', '\\%')) + '%\'';
        }
        if (!String.isBlank(rec.OT_Code__c)) {
            soql += ' and OT_Code__c like \'%' + String.escapeSingleQuotes(rec.OT_Code__c.trim().replaceAll('%', '\\%')) + '%\'';
        }
        if (!String.isBlank(assECcode)) {
            soql += ' and EC_Code__c like \'%' + String.escapeSingleQuotes(assECcode.trim().replaceAll('%', '\\%')) + '%\'';
        }
        if (!String.isBlank(rec.Equipment_Type__c)) {
            soql += ' and Equipment_Type__c = \'' + String.escapeSingleQuotes(rec.Equipment_Type__c) + '\'';
        }
        if (!String.isBlank(rec.loaner_place__c)) {
            soql += ' and loaner_place__c = \'' + String.escapeSingleQuotes(rec.loaner_place__c) + '\'';
        }
        if (!String.isBlank(rec.Status)) {
            soql += ' and status = \'' + String.escapeSingleQuotes(rec.Status) + '\'';
        }
         if (!String.isBlank(rec.SerialNumber)) {
            soql += ' and SerialNumber like \'%' + String.escapeSingleQuotes(rec.SerialNumber.trim().replaceAll('%', '\\%')) + '%\'';
        }
        if (!String.isBlank(rec.Internal_Asset_number__c)) {
            soql += ' and Internal_Asset_number__c like \'%' + String.escapeSingleQuotes(rec.Internal_Asset_number__c.trim().replaceAll('%', '\\%')) + '%\'';
        }
        /**
         *2018/10/15
         *NDT/ANI分野修改
        */

        if(!String.isBlank(rec.Remarks2__c)){
            soql +=  ' and Remarks2__c like \'%' + String.escapeSingleQuotes(rec.Remarks2__c.trim().replaceAll('%','\\%')) + '%\'';
        }

        if (loanerindividualList.size() > 0) {
            soql += ' and Id not in ' + loanerindTail;
        }
        if (ecCodeList.size() > 0) {
            soql += ' and EC_Code__c in ' + ecCodeTail;
        }

        system.debug(soql);
        List<Asset> queryList = Database.query(soql);
        /*List<Asset> queryList = [select Id,Name, SerialNumber, Internal_Asset_number__c, OT_Code__c,
                                            EC_Code__c, status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c
                                        from Asset
                                        WHERE EC_Code__c in : ecCodeList
                                        AND Id not in : loanerindividualList
                                        order by EC_Code__c];*/
        for (Asset query : queryList) {
            loanerAssetSelected.add(query.Id);
            loanerindividualList.add(query.Id);
        }
        system.debug(queryList);
        // 新明细行做成
        Integer j = 0;
        for (Integer i = 0;  i < queryList.size(); i++) {
            if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
                j++;
            //}
        }


        // 所有样机
        soql = this.makeSoql(assName, rec.OT_Code__c, assECcode, rec.Equipment_Type__c, rec.loaner_place__c, rec.Status,rec.SerialNumber,rec.Internal_Asset_number__c, loanerindividualList);
        soql += ' order by RecordType.Name asc limit ' + (Select_Limit + 1);
        system.debug(soql);
        queryList = Database.query(soql);
        for (Asset query : queryList) {
            loanerAssetSelected.add(query.Id);
        }
        system.debug(queryList);
        // 新明细行做成
        j = 0;
        for (Integer i = 0;  i < queryList.size(); i++) {
            if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
                j++;
            //}
        }
        if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
            dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
        }
        prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
        loanerApply.Prepare_Day__c = prepareDay;

        //其他已存在的样机借出历史
        /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
                                    LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
                                    loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
                                    ,Allocated_Det__c,LendPrimary_Name__c
                                 from  loaner_application_detail__c
                                 where loaner_application__c != :loanerApplyId
                                 and LOANER__c in :loanerAssetSelected
                                 AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
                                 AND Arrival_wh_Date__c = null
                                and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
                                 or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
                                 AND StockUp__c = false
                                 order by Name];
                                 //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'others。' + others[0].Id));
        Map<String, Date> othersMap = new Map<String,Date>();

        for (loaner_application_detail__c other : others) {
            if (othersMap.containsKey(other.LOANER__c)) {
                continue;
            } else {
                if(other.Received_loaner_Date__c == null){
                    othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
                }else{
                    othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
                }
            }
        }*/
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'othersMap + ' + othersMap));

        for (EquipmentSetInfo info : equipmentSetRecords) {
            info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
            info.Rental_End_Date = loanerApply.Rental_End_Date__c;
            info.SEdayCount  = dayCount;
            /*if(info.aset.Status == '在库'){
                if(othersMap.containsKey(info.aset.Id)){
                    info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
                }else{
                    info.earliest_Lend_Date = Date.today();
                }
            }*/
        }
        // 显示数据条数信息
        makeMessage();
    }

    public PageReference save() {
        system.debug(isManager);    
        Boolean hasError = false;
        Boolean chukuStatus = false;
        String strMessage = null;
        Map<String,String> asetEquipmentMap = new Map<String,String>();
        List<String> asetEquipmentList = new List<String>();
        Set<String> typeSet = new Set<String>();
        Set<String> LoanerSet = new Set<String>();
        if(loanerApply.Equipment_Type__c == 'IE' && loanerApply.Remind_Date__c != null){
            if(loanerApply.Remind_Date__c > Date.today()){
                hasError = true;
                strMessage = '请提前3个工作日分配样机。';
            }
        }

        Integer num = 0;
        /*if(isCancel){
            hasError = true;
            strMessage = '您的账户已被冻结，请联系管理员。';
        }*/

        /*if(loanerApply.Rental_Start_Date__c == null){
            hasError = true;
            strMessage = '请输入[借出开始日]';
        }
        if(loanerApply.Rental_End_Date__c == null){
            hasError = true;
            strMessage = '请输入[借出结束日]';
        }
        if (loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null && loanerApply.Rental_Start_Date__c > loanerApply.Rental_End_Date__c) {
            hasError = true;
            strMessage = '[借出开始日]必须小于等于[借出结束日]';
        }*/
        for (EquipmentSetInfo ass : equipmentSetRecords)  {
            if(ass.check == true){
                
                asetEquipmentMap.put(ass.aset.loaner_place__c, ass.aset.loaner_place__c);
                asetEquipmentList.add(ass.aset.loaner_place__c);
                typeSet.add(ass.aset.AssetType__c);
                if(loanerApply.Equipment_Type__c  == 'BS' && loanerApply.Loaner_LendOrder__c){
                    LoanerSet.add(ass.lad.loaner_application__c);
                    num++;
                }
            }
        }

        if ((loanerApply.Equipment_Type__c != 'IE' && loanerApply.Equipment_Type__c != 'NDT' && loanerApply.Equipment_Type__c != 'ANI')  && asetEquipmentMap.size() > 1) {
            hasError = true;
            strMessage = 'IE以外的申请单，只能借一个存放地的样机。';
        }
        if ((loanerApply.Equipment_Type__c != 'IE' && loanerApply.Equipment_Type__c != 'NDT' && loanerApply.Equipment_Type__c != 'ANI') && loanerApply.Approval_Status__c == false && asetEquipmentMap.size() > 1) {
            hasError = true;
            strMessage = '只能借一个存放地的样机。';
        }
        if(loanerApply.Equipment_Type__c  == 'BS' && typeSet.size()>1 && typeSet.contains('维修部件') ){
            hasError = true;
            strMessage = '维修产品只能单独出借。'; 
        }
        if(loanerApply.Equipment_Type__c  == 'BS' && LoanerSet.size()>1 && loanerApply.Loaner_LendOrder__c){
            hasError = true;
            strMessage = '只能转借一个借用单的样机。'; 
        }

        List<loaner_application_detail__c> temp = [select id from loaner_application_detail__c where loaner_application__c = :LoanerSet and Receipt_Status__c = 'OK'];
        system.debug(temp.size()+'------'+num);
        if(temp.size() > num && loanerApply.Equipment_Type__c  == 'BS' && loanerApply.Loaner_LendOrder__c){
            hasError = true;
            strMessage = '转借时请选择申请单内全部样机。'; 
        }

        if (hasError) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, strMessage));
            return null;
        }
        Savepoint sp = Database.setSavepoint();
        try{
            //转借分支
            if(loanerApply.Loaner_LendOrder__c){
                Map<String,String> lendOrderName = new Map<String,String>();
                List<loaner_application_detail__c> ins = New List<loaner_application_detail__c>();
                //del = New List<loaner_application_detail__c>();
                List<String> lendPrimaryList = new List<String>();
                List<String> delendIDList = new List<String>();
                Map<String,Decimal> asetNoMap = new Map<String,Decimal>();
                List<loaner_application_detail__c> oldList = new List<loaner_application_detail__c>();
                Integer indexNum = 1;
                Integer i = 1;
                if (loanerApply.Loaner_LendFrom__r.Rental_Start_Date__c > loanerApply.Rental_Start_Date__c || loanerApply.Loaner_LendFrom__r.Rental_End_Date__c < loanerApply.Rental_Start_Date__c) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '[借出开始日]必须输入转借申请单开始和结束之间的日期。'));
                    return null;
                }
                for (EquipmentSetInfo ass : equipmentSetRecords)  {
                    if(ass.check == true){
                        //判断是否已经分配，借出后不计算数量
                        if(ass.lad.Allocated_Det__c == true){

                        }else{
                            if(String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
                                if(asetNoMap.containsKey(ass.aset.Id)){
                                    if(ass.deatilNo > 0){
                                        asetNoMap.put(ass.aset.Id, asetNoMap.get(ass.aset.Id) + ass.deatilNo);
                                    }else if(ass.lad.RAESD_Status__c == '已分配'){
                                        asetNoMap.put(ass.aset.Id, asetNoMap.get(ass.aset.Id) + 1);
                                    }
                                }else{
                                    if(ass.deatilNo > 0){
                                        asetNoMap.put(ass.aset.Id,ass.deatilNo);
                                    }else if(ass.lad.RAESD_Status__c == '已分配'){
                                        asetNoMap.put(ass.aset.Id,1);
                                    }
                                }
                                if(ass.aset.Count_can_allocate_F__c < asetNoMap.get(ass.aset.Id)){
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '样机 ' + ass.aset.EC_Code__c + ' 借出数量超出可分配数量。'));
                                    return null;
                                }
                            }
                        }
                        if(ass.lad.Name == null && String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 && ass.aset.status != '在库'){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '第' + indexNum +'行数据的状态是' + ass.aset.status + '，无法再分配。'));
                            return null;
                        }
                        if(String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2 && ass.aset.Count_can_allocate_F__c <= 0){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '第' + indexNum +'行数据的可以分配数量是'+ ass.aset.Count_can_allocate_F__c +'，无法再分配。'));
                            return null;
                        }
                        if (ass.firstDet == false && loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_Start_Date__c < ass.earliest_Lend_Date) {
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '第' + indexNum +'行数据的[借出开始日]必须输入从[最早可借出日]开始起的日期。'));
                            return null;
                        }
                        if(ass.deatilNo > 0){
                            for(Integer j = 0;  j < ass.deatilNo; j++){
                                loaner_application_detail__c insertDet = new loaner_application_detail__c();
                                String str = string.valueOf(i);
                                if(str.length() == 1){
                                    str = '0' + str;
                                }
                                if(String.isNotEmpty(ass.lad.Id)){
                                    if(ass.firstDet && ass.lad.loaner_application__c != loanerApplyId){
                                        lendOrderName.put(ass.lad.loaner_application__r.loaner_request_number__c, ass.lad.loaner_application__r.loaner_request_number__c);
                                        insertDet.loanerOrder_Status__c = ass.lad.loaner_application__c +',' + ass.lad.loaner_application__r.Status__c;
                                        insertDet.LendPrimary_Name__c = ass.lad.Id;
                                        insertDet.LOANER__c = ass.aset.Id;
                                        ass.lad.is_distribution__c = true;
                                        oldList.add(ass.lad);
                                    }else{
                                        insertDet.Id = ass.lad.Id;
                                    }
                                    insertDet.loaner_application__c = loanerApplyId;
                                    insertDet.RAESD_Status__c = '已分配';
                                    insertDet.Allocate_Date__c = Date.today();
                                }
                                //else{
                                //    insertDet.loaner_application__c = loanerApplyId;
                                //    insertDet.RAESD_Status__c = '已分配';
                                //    insertDet.LOANER__c = ass.aset.Id;
                                //    insertDet.Allocate_Date__c = Date.today();
                                //}
                                if(String.isNotBlank(ass.lad.LendPrimary_Name__c)) lendPrimaryList.add(ass.lad.LendPrimary_Name__c);
                                insertDet.Name = loanerApply.Name + '-' + str;
                                insertDet.Remark__c = ass.remark;
                                ins.add(insertDet);
                                i ++;
                            }
                        }
                        /*else{
                            loaner_application_detail__c insertDet = new loaner_application_detail__c();
                            String str = string.valueOf(i);
                            if(str.length() == 1){
                                str = '0' + str;
                            }
                            if(String.isNotEmpty(ass.lad.Id)){
                                if(ass.firstDet && ass.lad.loaner_application__c != loanerApplyId){
                                    lendOrderName.put(ass.lad.loaner_application__r.loaner_request_number__c, ass.lad.loaner_application__r.loaner_request_number__c);
                                    insertDet.loanerOrder_Status__c = ass.lad.loaner_application__c +',' + ass.lad.loaner_application__r.Status__c;
                                    insertDet.LendPrimary_Name__c = ass.lad.Id ;
                                    insertDet.LOANER__c = ass.aset.Id;
                                }else{
                                    insertDet.Id = ass.lad.Id;
                                }
                                insertDet.loaner_application__c = loanerApplyId;
                                insertDet.RAESD_Status__c = '已分配';
                                insertDet.Allocate_Date__c = Date.today();
                            }
                            //else{
                            //    insertDet.loaner_application__c = loanerApplyId;
                            //    insertDet.RAESD_Status__c = '已分配';
                            //    insertDet.Allocate_Date__c = Date.today();
                            //    insertDet.LOANER__c = ass.aset.Id;
                            //}
                            if(String.isNotBlank(ass.lad.LendPrimary_Name__c)) lendPrimaryList.add(ass.lad.LendPrimary_Name__c);
                            insertDet.Name = loanerApply.Name + '-' + str;
                            insertDet.Remark__c = ass.remark;
                            ins.add(insertDet);
                            i ++;
                        }*/
                    }else if(ass.oldcheck == true && ass.firstDet == false){
                        loaner_application_detail__c delDet = new loaner_application_detail__c();
                        delDet.Id = ass.lad.Id;
                        del.add(delDet);
                    }else if(ass.oldcheck == true && ass.firstDet == true){
                        delendIDList.add(ass.lad.Id);


                    }
                    indexNum += 1;
                }
                loanerApply.loaner_place__c = '';
                if(asetEquipmentMap.size() == 1){
                    if(asetEquipmentList.size() > 0) loanerApply.loaner_place__c = asetEquipmentList[0];
                }
                this.getleadUser();
                
                this.moveDetail(delendIDList);
                //return null;
                //this.addDetail(inlendIDList);

                //删除取消的样机明细
                if (del.size()>0){
                    delete del;
                }
                if(ins.size()>0){
                    upsert ins;
                }
                if(oldList.size()>0){
                    update oldList;
                }
                for(loaner_application_detail__c lad : [SELECT Id,loaner_application__r.loaner_request_number__c FROM loaner_application_detail__c WHERE Id in : lendPrimaryList]){
                    lendOrderName.put(lad.loaner_application__r.loaner_request_number__c, lad.loaner_application__r.loaner_request_number__c);
                }
                loanerApply.AllLead_OrderName__c = '';
                if(lendOrderName.size() > 0){
                    for(String lon : lendOrderName.keySet()){
                        loanerApply.AllLead_OrderName__c += lon + ' \r\n ';
                    }
                }
                system.debug(typeSet);
                if(loanerApply.Equipment_Type__c  == 'BS' &&  typeSet.contains('维修部件')){
                    loanerApply.Is_Repair_Products__c = true;
                }else{
                    loanerApply.Is_Repair_Products__c = false;
                }

                if(loanerApply.Equipment_Type__c == 'BS' && typeSet.contains('高端样机')){
                    loanerApply.Is_High_end_Products__c = true;
                }else{
                    loanerApply.Is_High_end_Products__c = false;
                }
                update loanerApply;


            }else{
                //非转借分支
                List<loaner_application_detail__c> ins = New List<loaner_application_detail__c>();
                //del = New List<loaner_application_detail__c>();
                Map<String,Decimal> asetNoMap = new Map<String,Decimal>();
                Integer indexNum = 1;
                Integer i = 1;
                for (EquipmentSetInfo ass : equipmentSetRecords)  {
                    if(ass.check == true){
                        //判断是否已经分配，借出后不计算数量
                        if(ass.lad.Allocated_Det__c == true){

                        }else{
                            if(String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
                                if(asetNoMap.containsKey(ass.aset.Id)){
                                    if(ass.deatilNo > 0){
                                        asetNoMap.put(ass.aset.Id, asetNoMap.get(ass.aset.Id) + ass.deatilNo);
                                    }else if(ass.lad.RAESD_Status__c == '已分配'){
                                        asetNoMap.put(ass.aset.Id, asetNoMap.get(ass.aset.Id) + 1);
                                    }
                                }else{
                                    if(ass.deatilNo > 0){
                                        asetNoMap.put(ass.aset.Id,ass.deatilNo);
                                    }else if(ass.lad.RAESD_Status__c == '已分配'){
                                        asetNoMap.put(ass.aset.Id,1);
                                    }
                                }
                                if(ass.aset.Count_can_allocate_F__c < asetNoMap.get(ass.aset.Id)){
                                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '样机 ' + ass.aset.EC_Code__c + ' 借出数量超出可分配数量。'));
                                    return null;
                                }
                            }
                        }
                        if(ass.lad.Name == null && String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 && ass.aset.status != '在库'){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '第' + indexNum +'行数据的状态是' + ass.aset.status + '，无法再分配。'));
                            return null;
                        }
                        if(String.valueOf(ass.aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2 && ass.aset.Count_can_allocate_F__c <= 0){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '第' + indexNum +'行数据的可以分配数量是'+ ass.aset.Count_can_allocate_F__c +'，无法再分配。'));
                            return null;
                        }
                        //if (loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_Start_Date__c < ass.earliest_Lend_Date) {
                        //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '第' + indexNum +'行数据的[借出开始日]必须入力从[最早可借出日]开始起的日期。'));
                        //     return null;
                        //}
                        if(!isManager){
                            if(ass.deatilNo > 0){
                                for(Integer j = 0;  j < ass.deatilNo; j++){
                                    loaner_application_detail__c insertDet = new loaner_application_detail__c();
                                    String str = string.valueOf(i);
                                    if(str.length() == 1){
                                        str = '0' + str;
                                    }
                                    if(String.isNotBlank(ass.lad.Id)){
                                        insertDet.Id = ass.lad.Id;
                                        if(loanerApply.Status__c == '驳回'){
                                            insertDet.RAESD_Status__c = '已分配';
                                        }
                                    }else{
                                        insertDet.loaner_application__c = loanerApplyId;
                                        insertDet.LOANER__c = ass.aset.Id;
                                    }
                                    insertDet.Name = loanerApply.Name + '-' + str;
                                    insertDet.RAESD_Status__c = '已分配';
                                    insertDet.Allocate_Date__c = Date.today();
                                    insertDet.Remark__c = ass.remark;
                                    ins.add(insertDet);
                                    i ++;
                                }
                            }else{
                                loaner_application_detail__c insertDet = new loaner_application_detail__c();
                                String str = string.valueOf(i);
                                if(str.length() == 1){
                                    str = '0' + str;
                                }
                                if(String.isNotBlank(ass.lad.Id)){
                                    insertDet.Id = ass.lad.Id;
                                    if(loanerApply.Status__c == '驳回'){
                                        insertDet.RAESD_Status__c = '已分配';
                                    }
                                }else{
                                    insertDet.loaner_application__c = loanerApplyId;
                                    insertDet.LOANER__c = ass.aset.Id;
                                }
                                insertDet.Name = loanerApply.Name + '-' + str;
                                insertDet.RAESD_Status__c = '已分配';
                                insertDet.Allocate_Date__c = Date.today();
                                insertDet.Remark__c = ass.remark;
                                ins.add(insertDet);
                                i ++;
                            }
                        }else{
                            if(ass.deatilNo > 0){
                                for(Integer j = 0;  j < ass.deatilNo; j++){
                                    loaner_application_detail__c insertDet = new loaner_application_detail__c();
                                    String str = string.valueOf(i);
                                    if(str.length() == 1){
                                        str = '0' + str;
                                    }
                                    if(String.isNotBlank(ass.lad.Id)){
                                        insertDet.Id = ass.lad.Id;
                                        if(loanerApply.Status__c == '驳回'){
                                            insertDet.RAESD_Status__c = '已分配';
                                        }
                                    }else{
                                        insertDet.loaner_application__c = loanerApplyId;
                                        if(loanerApply.Status__c == '已批准'){
                                            insertDet.RAESD_Status__c = '已批准';
                                        }else if(loanerApply.Status__c == '申请中'){
                                            if(loanerApply.Equipment_Type__c == 'IE' && loanerApply.Approval_Step__c == 1){
                                                insertDet.RAESD_Status__c = '已分配';
                                            }else{
                                                insertDet.RAESD_Status__c = '申请中';
                                            }
                                        }else if(loanerApply.Status__c == '草案中' || loanerApply.Status__c == '驳回' || loanerApply.Status__c == '销售担当批准'){
                                            insertDet.RAESD_Status__c = '已分配';
                                        }else{
                                            insertDet.RAESD_Status__c = '已出库指示';
                                            chukuStatus = true;
                                        }
                                        insertDet.LOANER__c = ass.aset.Id;
                                    }
                                    insertDet.Name = loanerApply.Name + '-' + str;
                                    insertDet.Allocate_Date__c = Date.today();
                                    insertDet.Remark__c = ass.remark;
                                    ins.add(insertDet);
                                    i ++;
                                }
                            }else{
                                loaner_application_detail__c insertDet = new loaner_application_detail__c();
                                String str = string.valueOf(i);
                                if(str.length() == 1){
                                    str = '0' + str;
                                }
                                if(String.isNotBlank(ass.lad.Id)){
                                    insertDet.Id = ass.lad.Id;
                                    if(loanerApply.Status__c == '驳回'){
                                        insertDet.RAESD_Status__c = '已分配';
                                    }
                                }else{
                                    insertDet.loaner_application__c = loanerApplyId;
                                    if(loanerApply.Status__c == '已批准'){
                                        insertDet.RAESD_Status__c = '已批准';
                                    }else if(loanerApply.Status__c == '申请中'){
                                        if(loanerApply.Equipment_Type__c == 'IE' && loanerApply.Approval_Step__c == 1){
                                            insertDet.RAESD_Status__c = '已分配';
                                        }else{
                                            insertDet.RAESD_Status__c = '申请中';
                                        }
                                    }else if(loanerApply.Status__c == '草案中'  || loanerApply.Status__c == '驳回' || loanerApply.Status__c == '销售担当批准'){
                                        insertDet.RAESD_Status__c = '已分配';
                                    }else{
                                        insertDet.RAESD_Status__c = '已出库指示';
                                        chukuStatus = true;
                                    }
                                    insertDet.LOANER__c = ass.aset.Id;
                                }
                                insertDet.Name = loanerApply.Name + '-' + str;
                                insertDet.Allocate_Date__c = Date.today();
                                insertDet.Remark__c = ass.remark;
                                ins.add(insertDet);
                                i ++;
                            }
                        }
                        
                    }else if(ass.oldcheck == true){
                        loaner_application_detail__c delDet = new loaner_application_detail__c();
                        delDet.Id = ass.lad.Id;
                        del.add(delDet);
                    }
                    indexNum += 1;
                }
                loanerApply.loaner_place__c = '';
                if(asetEquipmentMap.size() == 1){
                    if(asetEquipmentList.size() > 0) loanerApply.loaner_place__c = asetEquipmentList[0];
                }
                if(chukuStatus == true)loanerApply.Status__c = '已出库指示';
                
                //删除取消的样机明细
                if(isManager && loanerApply.Manager_detail_Del__c == false){

                }else{
                    if (del.size()>0){
                        delete del;
                    }
                }
                if(ins.size()>0){
                    upsert ins;
                }
                system.debug(typeSet);
                if(loanerApply.Equipment_Type__c  == 'BS' &&  typeSet.contains('维修部件')){
                    loanerApply.Is_Repair_Products__c = true;
                }else{
                    loanerApply.Is_Repair_Products__c = false;
                }

                if(loanerApply.Equipment_Type__c == 'BS' && typeSet.contains('高端样机')){
                    loanerApply.Is_High_end_Products__c = true;
                }else{
                    loanerApply.Is_High_end_Products__c = false;
                }
                update loanerApply;
            }
        }catch(Exception e){
            ApexPages.addMessages(e);
            Database.rollback(sp);
            return  null;
        }
    	return new Pagereference('/'+loanerApplyId);
    }
    // 追加转借明细
    /*public void addDetail(List<String> addlist) {
        List<loaner_application_detail__c> addDetList = [select Id, Name,Receipt_Status__c,Receipt_Date__c
                                 from  loaner_application_detail__c
                                 WHERE Id in : addlist];
        for(loaner_application_detail__c det : addDetList){
            if(det.Receipt_Status__c != 'OK' && det.Receipt_Status__c == null){
                det.Receipt_Status__c = 'OK';
                det.Receipt_Date__c = Date.today();
            }
            //日期
            det.Asset_Return_Date__c = Date.today();
            det.Received_loaner_Date__c = Date.today();
            det.After_Inspection_Date__c = Date.today();
            det.Arrival_wh_Date__c = Date.today();
            det.RAESD_Status__c = '已回库';
            //上架加成
             det.StockUp__c = true;
            det.Check_lost_Item__c = 'OK';
            det.Inspection_result_after__c = 'OK';
            //物流信息
            det.Return_Track_Company__c = System.label.Default_Logistics_company;
            det.Return_Track_Number__c = System.label.Default_Logistics_No;
        }
        update addDetList;


    }*/
    //取消转借明细
    public void moveDetail(List<String> movelist) {

        if(moveList.size() == 0 || moveList == null){
            return;
        }

       

        List<loaner_application_detail__c> moveDetList = [select Id, Name,LendPrimary_Name__c,RAESD_Status__c
                                       ,loanerOrder_Status__c
                                 from  loaner_application_detail__c
                                 WHERE Id in : movelist];

        List<String> idList = new List<String>();
        for(loaner_application_detail__c lad : moveDetList){
            idList.add(lad.LendPrimary_Name__c);
        }

        List<loaner_application_detail__c> oldLadList = [SELECT id FROM loaner_application_detail__c WHERE id IN :idList ];
        for(loaner_application_detail__c lad : oldLadList){
            lad.is_distribution__c = false;
        }
        if(oldLadList.size() > 0) update oldLadList;

        if(moveDetList.size() > 0 ) delete moveDetList;
    }
    // 取消转借明细
    /*public void moveDetail(List<String> movelist) {
        List<String> deleteList = new List<String>();
        Map<String,String> deleteMap = new Map<String,String>();
        Map<String,String> deleteNameMap = new Map<String,String>();
        Map<String,String> deleteOrderStatusMap = new Map<String,String>();

        List<loaner_application_detail__c> moveDetList = [select Id, Name,LendPrimary_Name__c,RAESD_Status__c
                                       ,loanerOrder_Status__c
                                 from  loaner_application_detail__c
                                 WHERE Id in : movelist];
        Map<Id,loaner_application__c>  loaner_appMap= new Map<Id,loaner_application__c>();
        for(loaner_application_detail__c det : moveDetList){
            loaner_application__c loaner_app = new loaner_application__c();
            if(String.isNotBlank(det.LendPrimary_Name__c)){
                deleteList.add(det.LendPrimary_Name__c);
                if(det.loanerOrder_Status__c.contains(',')){
                    loaner_app.Id = det.loanerOrder_Status__c.split(',')[0];
                    loaner_app.Status__c = det.loanerOrder_Status__c.split(',')[1];
                    loaner_appMap.put(loaner_app.Id, loaner_app);
                }
            }
        }
        //取原申请明细的单号ID
        List<loaner_application_detail__c> movedeleteList = [select Id,Name,loaner_application__c
                                 from  loaner_application_detail__c
                                 WHERE Id in : deleteList];
        for(loaner_application_detail__c lapp : movedeleteList){
            deleteMap.put(lapp.Id, lapp.loaner_application__c);
            deleteNameMap.put(lapp.Id, lapp.Name);
        }
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'deleteMap-----' + deleteMap));
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'deleteNameMap-----' + deleteNameMap));
System.debug('deleteMap +++++' + deleteMap);
        for(loaner_application_detail__c det : moveDetList){
            if(String.isNotBlank(det.LendPrimary_Name__c)){
                deleteList.add(det.LendPrimary_Name__c);
                det.Name = deleteNameMap.get(det.LendPrimary_Name__c);
                det.loaner_application__c = deleteMap.get(det.LendPrimary_Name__c);
            }
            det.LendPrimary_Name__c = '';
        }

        System.debug('moveDetList +++++' + moveDetList);

        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'movedeleteList' + movedeleteList));
        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, 'moveDetList' + moveDetList));
        //return;
        if(movedeleteList.size() > 0 ) delete movedeleteList;

        update moveDetList;
        if(loaner_appMap.size() > 0 ) update loaner_appMap.values();

    }*/
    // 排序
    public void sortTable() {
        //已选择个体管理样机
        List<String> loanerindividualList = new List<String>();
        //// 画面已打勾的明细保留
        String strProd = null;
        List<EquipmentSetInfo> selectedloanerRecords = new List<EquipmentSetInfo>();
        for (EquipmentSetInfo info : equipmentSetRecords) {
            if (info.check == true) {
                selectedloanerRecords.add(info);
            }else{
                if(strProd==null || strProd.length()==0){
                    strProd = '\'' + String.valueOf(info.aset.Id) + '\'';
                }
                else{
                    strProd += ',\'' + String.valueOf(info.aset.Id) + '\'';
                }
            }
        }
        equipmentSetRecords = new List<EquipmentSetInfo>();
        loanerAssetSelected = new list<String>();
        //Map<String,String> equipmentSetSelectedMap = new Map<String,String>();
        for (EquipmentSetInfo info : selectedloanerRecords) {
            loanerAssetSelected.add(info.aset.Id);
            //equipmentSetSelectedMap.put(info.aset.Id, info.aset.Id);
        }

        // 排序
        if (this.sortKey == this.preSortKey) {
            // 方向が変わるのみ
            this.sortOrderAsc = !this.sortOrderAsc;
            this.sortOrder[Integer.valueOf(this.sortKey)] = (this.sortOrderAsc == true ? '↑' : '↓');
        } else {
            this.sortOrderAsc = true;
            this.sortOrder[Integer.valueOf(this.preSortKey)] = '　';
            this.sortOrder[Integer.valueOf(this.sortKey)] = (this.sortOrderAsc == true ? '↑' : '↓');
        }
        this.preSortKey = this.sortKey;
        // 所有备品set
        String soql = this.makeSoql(assName, rec.OT_Code__c, assECcode, rec.Equipment_Type__c, rec.loaner_place__c, rec.Status,rec.SerialNumber,rec.Internal_Asset_number__c,loanerindividualList);
        soql += ' AND Id IN (' + strProd + ')';
        soql += ' order by ' + this.columus[Integer.valueOf(this.sortKey)] + ' ' + (this.sortOrderAsc == true ? 'asc nulls first' : 'desc nulls last') + ' limit ' + (Select_Limit + 1);
        List<Asset> queryList = Database.query(soql);
        for (Asset query : queryList) {
            loanerAssetSelected.add(query.Id);
        }

        // 已存在明细行做成
        //equipmentSetRecords.addAll(selectedloanerRecords);
        for (Integer i = 0; i < selectedloanerRecords.size(); i++) {
            // 201を超えた場合前200のみを出す
            if (i == Select_Limit) {Over_Limit=true; break;}
            equipmentSetRecords.add(selectedloanerRecords[i]);
        }
        // 新明细行做成
        Integer j = 0;
        for (Integer i = 0;  i < queryList.size(); i++) {
            // 201を超えた場合前200のみを出す
            if (j == Select_Limit - selectedloanerRecords.size()) {Over_Limit=true; break;}
            //if (!equipmentSetSelectedMap.containsKey(queryList[i].Id)) {
                j++;
                equipmentSetRecords.add(new EquipmentSetInfo(queryList[i]));
            //}
        }
        if(loanerApply.Rental_Start_Date__c != null && loanerApply.Rental_End_Date__c != null){
            dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
        }
        //Integer dayCount = (loanerApply.Rental_Start_Date__c).daysBetween(loanerApply.Rental_End_Date__c);
        prepareDay = loanerApply.Prepare_Day__c == null ? Integer.valueOf(System.Label.LoanerRentalPrepare) : loanerApply.Prepare_Day__c.intValue();
        loanerApply.Prepare_Day__c = prepareDay;

        //其他已存在的样机借出历史
        /*List<loaner_application_detail__c> others = [select Id, Name, LOANER__r.SerialNumber,LOANER__c ,loaner_application__r.Rental_Start_Date__c,
                                    LOANER__r.Internal_Asset_number__c, LOANER__r.OT_Code__c,LOANER__r.EC_Code__c,LOANER__r.Status,
                                    loaner_application__r.Rental_End_Date__c,loaner_application__r.Approval_Date__c,Received_loaner_Date__c
                                    ,Allocated_Det__c
                                 from  loaner_application_detail__c
                                 where loaner_application__c != :loanerApplyId
                                 and LOANER__c in :loanerAssetSelected
                                 AND Arrival_wh_Date__c = null
                                 AND LOANER__r.RecordTypeId  = :System.label.Asset_Record_Type1
                                 and ((loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c = null)
                                 or (loaner_application__r.Approval_Date__c != null AND Received_loaner_Date__c != null AND Received_loaner_Date__c >= :Date.today().addDays(-prepareDay)))
                                 AND StockUp__c = false
                                 order by Name];
        Map<String, Date> othersMap = new Map<String,Date>();

        for (loaner_application_detail__c other : others) {
            if (othersMap.containsKey(other.LOANER__c)) {
                continue;
            } else {
                //othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
                if(other.Received_loaner_Date__c == null){
                    othersMap.put(other.LOANER__c, other.loaner_application__r.Rental_End_Date__c);
                }else{
                    othersMap.put(other.LOANER__c, other.Received_loaner_Date__c);
                }
            }
        }*/

        for (EquipmentSetInfo info : equipmentSetRecords) {
            info.Rental_Start_Date = loanerApply.Rental_Start_Date__c;
            info.Rental_End_Date = loanerApply.Rental_End_Date__c;
            info.SEdayCount  = dayCount;
            /*if(info.aset.Status == '在库'){
                if(othersMap.containsKey(info.aset.Id)){
                    info.earliest_Lend_Date = othersMap.get(info.aset.Id).addDays(prepareDay);
                }else{
                    info.earliest_Lend_Date = Date.today();
                }
            }*/
        }
        // 显示数据条数信息
        makeMessage();
    }

    // 做成检索SQL文
    private String makeSoql(String assName, String otCode, String eCcode, String equipmentType, String loanerPlace, String status,String serialNumber,String internal_Asset_No,List<String> exId) {
        String sqlTail = '(\'';
        for(Integer i = 0 ; i< exId.size();i++){
            if(i<exId.size()-1){
                sqlTail += exId[i]+'\',\'';
            }else{
                sqlTail += exId[i]+'\')';
            }
        }
        String soql = 'select Id,Description,AssetType__c,Name, Name__c,ProductName__c,SerialNumber, Internal_Asset_number__c, OT_Code__c, EC_Code__c, status,Count_can_allocate_F__c,RecordTypeId,loaner_place__c,Remarks2__c,Rental_Customer__r.Name,Rental_End_Date__c,Rental_Start_Date__c  '
                    + 'from Asset where Id != null ';

        if (!String.isBlank(assName)) {
            soql += ' and Name like \'%' + String.escapeSingleQuotes(assName.trim().replaceAll('%', '\\%')) + '%\'';
        }
        if (!String.isBlank(otCode)) {
            soql += ' and OT_Code__c like \'%' + String.escapeSingleQuotes(otCode.trim().replaceAll('%', '\\%')) + '%\'';
        }
        if (!String.isBlank(eCcode)) {
            soql += ' and EC_Code__c like \'%' + String.escapeSingleQuotes(eCcode.trim().replaceAll('%', '\\%')) + '%\'';
        }
        if (!String.isBlank(equipmentType)) {
            soql += ' and Equipment_Type__c = \'' + String.escapeSingleQuotes(equipmentType) + '\'';
        }
        if (!String.isBlank(loanerPlace)) {
            soql += ' and loaner_place__c = \'' + String.escapeSingleQuotes(loanerPlace) + '\'';
        }
        if (!String.isBlank(status)) {
            soql += ' and status = \'' + String.escapeSingleQuotes(status) + '\'';
        }
         if (!String.isBlank(serialNumber)) {
            soql += ' and SerialNumber like \'%' + String.escapeSingleQuotes(serialNumber.trim().replaceAll('%', '\\%')) + '%\'';
        }
        /**
         *2018/10/15
         *NDT/ANI分野修改
        */

        if(!String.isBlank(rec.Remarks2__c)){
            soql +=  ' and Remarks2__c like \'%' + String.escapeSingleQuotes(rec.Remarks2__c.trim().replaceAll('%','\\%')) + '%\'';
        }
        if (!String.isBlank(internal_Asset_No)) {
            soql += ' and Internal_Asset_number__c like \'%' + String.escapeSingleQuotes(internal_Asset_No.trim().replaceAll('%', '\\%')) + '%\'';
        }
        if (exId.size() > 0) {
            soql += ' and Id not in ' + sqlTail;
        }
        system.debug(soql);
        return soql;
    }

    // 显示数据条数信息
    private void makeMessage() {
        if (Over_Limit) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '数据超过' + Select_Limit + '件，只显示前' + Select_Limit + '件'));
            Over_Limit = false;
        }
    }

    // 返回按钮
    public PageReference cancel() {
        PageReference ref =  new Pagereference('/');
        //if (String.isNotBlank(loanerApplyId)) {
            // 返回样机借出申请
        ref = new Pagereference('/' + loanerApplyId);
        //}
        //ref.setRedirect(true);
        return ref;
    }
    //data bean
    class EquipmentSetInfo implements Comparable {
     	public Boolean check { get; set; }
        public Boolean oldcheck { get; set; }
        public loaner_application_detail__c lad { get; set; }
        public Asset aset { get; set; }
        public Loaner_Set__c lSet { get; set; }
        public Date Rental_Start_Date { get; set; }
        public Date Rental_End_Date { get; set; }
        //最早可借出时间
        public Date earliest_Lend_Date { get; set; }
        public Integer SEdayCount { get; set; }
        public Integer deatilNo { get; set; }
        public Boolean canInput { get; set; }
        public Boolean showNo { get; set; }
        public String remark { get; set; }
        //public Date endDate {get; set; }
        //转借元申请明细标记
        public Boolean firstDet { get; set; }

        // 已存产品明细
        public EquipmentSetInfo(loaner_application_detail__c e) {
            check = true;
            oldcheck= true;
            lad = e;
            aset = e.LOANER__r;
            //endDate = aset.Rental_End_Date__c;
            if(String.isNotBlank(lad.Remark__c)){
                remark = lad.Remark__c;
            }else{
                remark = aset.Remarks2__c;
            }
            deatilNo = 1;
            canInput = false;
            firstDet = false;
            if(String.valueOf(aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
                showNo = true;
            }else{
                showNo = false;
            }
        }
        public EquipmentSetInfo(Integer in_line, Loaner_Set__c e) {
            deatilNo = in_line;
            lSet = e;

        }

        public EquipmentSetInfo(Asset e) {
            system.debug(e);
            check = false;
            oldcheck = false;
            lad = new loaner_application_detail__c();
            aset = e;
            remark = aset.Remarks2__c;
            firstDet = false;
            if(String.valueOf(aset.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type2){
                canInput = true;
                showNo = true;
            }else{
                //lad.loaner_ApplyNo__c = 1;
                deatilNo = 1;
                canInput = false;
                showNo = false;
            }
        }
        // 排序
        public Integer compareTo(Object compareTo) {
            return null;
        }
    }
}