/**************************************************************************************************
 * Name: DirectAssignController
 * Purpose: directly assign new apply 
 * Author: Prec-tech team
 * Create Date: 2021-10-27
 * Modify History:
 * 2021-10-27       Create this class
 **************************************************************************************************/
public with sharing class DirectAssignController{

	public Rental_Apply_Equipment_Set_Detail__c raesd {get;set;}
	public String searchKey{get;set;}
	public List<Rental_Apply_Equipment_Set_Detail__c> raesdList {get;set;}
	public List<Wrapper> wrappers {get;set;}
	public String targetId { get; set; }
	public String messageHead { get; set; }
	public Asset ast;
	public Rental_Apply_Sequence__c ras;
	public String externalKey;
	public String assetId;

	public DirectAssignController(){
		String recordId = ApexPages.currentPage().getParameters().get('oldquenId');
		// 暂定分配数据指定给对象有的情况
		targetId = ApexPages.currentPage().getParameters().get('targetId');
		if(String.isNotEmpty(recordId)){
			raesd = [SELECT Id,Fixture_Model_No_text__c,Asset__c,Rental_Apply__r.Name,Rental_Apply_Equipment_Set__r.Name,
					Queue_Day__c,Queue_Number__c,Rental_Apply__r.WorkPlace__c,Rental_Apply__r.Person_In_Charge__r.Name,
					Rental_Apply__r.demo_purpose2__c,Queue_Conment__c,Equipment_Type_text__c,Salesdepartment_before__c,
					Internal_asset_location_before__c,jumpReason__c,Queue_User__r.Name,Rental_Apply__r.Hospital__r.Name,Rental_Apply__c,
					Rental_Apply__r.Campaign__r.Name,Externalkey__c,Rental_Apply__r.Internal_asset_location_F__c,QuenType__c
					 FROM Rental_Apply_Equipment_Set_Detail__c 
					 WHERE Is_Body__c=true 
					 AND Rental_Apply_Equipment_Set__c=:recordId limit 1];
			assetId = raesd.Asset__c; 
			String soql = null;
			if (String.isNotEmpty(targetId)) {
				messageHead = '抢夺';
				soql = 'SELECT Id,Fixture_Model_No_text__c,Asset__c,Rental_Apply__r.Name,Rental_Apply_Equipment_Set__r.Name,Queue_Time__c,Queue_User__c,'
							+ 'Queue_Day__c,Queue_Number__c,Rental_Apply__r.WorkPlace__c,Rental_Apply__r.Person_In_Charge__r.Name,jumpReason__c,'
							+ 'Rental_Apply__r.demo_purpose2__c,Queue_Conment__c,Equipment_Type_text__c,ExternalKey__c,Allow_Adjust_Queue_Flag__c,'
							+ 'Queue_User__r.Name,Rental_Apply__r.Hospital__r.Name,Rental_Apply__r.Campaign__r.Name,Salesdepartment_before__c,Internal_asset_location_before__c'
							+ ' FROM Rental_Apply_Equipment_Set_Detail__c' 
							+ ' WHERE Is_Body__c=true '
							+ ' AND Rental_Apply_Equipment_Set__c =:targetId';
			} else {
				messageHead = '指定';
				String modelNo = raesd.Fixture_Model_No_text__c;
				String location = raesd.Internal_asset_location_before__c;
				String externalKey = raesd.Externalkey__c;
				System.debug(LoggingLevel.INFO, '*** externalKey: ' + externalKey);
				soql = 'SELECT Id,Fixture_Model_No_text__c,Asset__c,Rental_Apply__r.Name,Rental_Apply_Equipment_Set__r.Name,Queue_Time__c,Queue_User__c,'
							+ 'Queue_Day__c,Queue_Number__c,Rental_Apply__r.WorkPlace__c,Rental_Apply__r.Person_In_Charge__r.Name,jumpReason__c,'
							+ 'Rental_Apply__r.demo_purpose2__c,Queue_Conment__c,Equipment_Type_text__c,ExternalKey__c,Allow_Adjust_Queue_Flag__c,'
							+ 'Queue_User__r.Name,Rental_Apply__r.Hospital__r.Name,Rental_Apply__r.Campaign__r.Name,Salesdepartment_before__c,Internal_asset_location_before__c'
							+ ' FROM Rental_Apply_Equipment_Set_Detail__c' 
							+ ' WHERE Is_Body__c=true '
							+ ' AND Queue_Number__c > 0'
					 		+ ' AND Cancel_Select__c = false'
							+ ' AND Id !=:recordId'
							+ ' AND Externalkey__c =:externalKey'
							+ ' ORDER BY Queue_Number__c';
							// + ' AND Fixture_Model_No_text__c =:modelNo'
							// + ' AND Internal_asset_location_before__c =:location';
				// if(raesd.Salesdepartment_before__c.contains(';')){
				// 	for(String salesdepartment:raesd.Salesdepartment_before__c.split(';')){
				// 		String searchText = '%' + salesdepartment + '%';
				// 		soql += ' AND Salesdepartment_before__c like:searchText';
				// 	}
				// }else{
				// 	String searchText = '%' + raesd.Salesdepartment_before__c + '%';
				// 	soql += ' AND Salesdepartment_before__c like:searchText';
				// }
			}
			
			System.debug(LoggingLevel.INFO, '*** soql: ' + soql);
			raesdList = Database.query(soql);
			wrappers = new List<Wrapper>();
			for(Rental_Apply_Equipment_Set_Detail__c detail:raesdList){
				Wrapper wrapper =new Wrapper();
				wrapper.selected = false;
				wrapper.detail = detail;
				
				wrappers.add(wrapper);
			}
			// raesd = raesdList[0];
		}
		
	}

	public PageReference search(){
		try {
		    System.debug(LoggingLevel.INFO, '*** raesd: ' + raesd);
			String searchText = '%' + searchKey + '%';
			String locationEmail = FixtureUtil.locationMap.get(raesd.Internal_asset_location_before__c);

			raesdList = [SELECT Id,Fixture_Model_No_text__c,Asset__c,Rental_Apply__r.Name,Rental_Apply_Equipment_Set__r.Name,Queue_User__c,Queue_Time__c,
						Queue_Day__c,Queue_Number__c,Rental_Apply__r.WorkPlace__c,Rental_Apply__r.Person_In_Charge__r.Name,jumpReason__c,Rental_Apply__r.Salesdept__c,
						Rental_Apply__r.demo_purpose2__c,Queue_Conment__c,Equipment_Type_text__c,ExternalKey__c,Allow_Adjust_Queue_Flag__c,Internal_asset_location_before__c,
						Queue_User__r.Name,Rental_Apply__r.Hospital__r.Name,Rental_Apply__r.Campaign__r.Name,Salesdepartment_before__c,Rental_Apply__r.Loaner_centre_mail_address__c
						 FROM Rental_Apply_Equipment_Set_Detail__c 
						 WHERE Is_Body__c=true 
						 AND Id <>:raesd.Id
						 AND (Shipment_Status_Text__c = '待分配' OR Shipment_Status_Text__c = '排队中')
						 AND Cancel_Select__c = false
						 AND Fixture_Model_No_text__c =:raesd.Fixture_Model_No_text__c
						 AND Rental_Apply__r.Name LIKE :searchText
						 ORDER BY Queue_Number__c];
			wrappers = new List<Wrapper>();
			for(Rental_Apply_Equipment_Set_Detail__c detail:raesdList){
				if(locationEmail!=null && locationEmail.equalsIgnoreCase(detail.Rental_Apply__r.Loaner_centre_mail_address__c)){
					Wrapper wrapper =new Wrapper();
					wrapper.selected = false;
					wrapper.detail = detail;
					
					wrappers.add(wrapper);
				}
				
			}
			if(wrappers.size() == 0){
				throw new ControllerUtil.myException('无任何配套满足!');
			}
		}
		catch (Exception e) {
		    ApexPages.addMessages(e);
		}
		
		
		return null;

	}

	public static Boolean containValue(String value,List<String> opList){
		for(String op:opList){
			if(op.contains(value.replace('医疗', ''))){
				return true;
			}
		}
		return false;
	}

	public class Wrapper{
		public Boolean selected{get;set;}
		public Rental_Apply_Equipment_Set_Detail__c detail{set;get;}
		
	}

	public PageReference quenTop(){
		Savepoint sp = Database.setSavepoint();
        try {
            Rental_Apply_Equipment_Set_Detail__c detail = null;
        	for(Wrapper w:wrappers){
        		if(w.selected){
        			if(detail != null){
        				throw new ControllerUtil.myException('只能选择一个队列进行指定分配');
        			}
        			detail = w.detail;
        		}
        	}
        	if(detail == null){
        		throw new ControllerUtil.myException('请勾选数据进行操作');
        	}else if(!detail.Allow_Adjust_Queue_Flag__c){
        		throw new ControllerUtil.myException('备品总窗口未申请插队，无法调整顺序，请确认。');
        	}
        	if(raesd.QuenType__c == null){
	        	throw new ControllerUtil.myException('原单未参与过排队，无法明确队列信息并置顶或置底，请选择‘原单放弃排队’后进行排队');
	        }
        	System.debug(LoggingLevel.INFO, '*** raesd.Asset__c: ' + raesd.Asset__c);
        	detail = assignedUpdate(detail);
        	System.debug(LoggingLevel.INFO, '*1111** detail: ' + detail);
        	RentalApplyEquipmentSetDetailHandler.disabled = false;
            update detail;
            
            reQueue(raesd,'top');
           	// QueuePageByAssetIdController con = new QueuePageByAssetIdController();
            // con.saveQueue(raesd,1,false,true);
        	System.debug(LoggingLevel.INFO, '*** updateold: ');
        }
        catch (Exception e) {
            System.debug('e.getMessage()***'+ e.getMessage()+e.getLineNumber());
            ApexPages.addMessages(e);
            Database.rollback(sp);
            raesd = [SELECT Id,Fixture_Model_No_text__c,Asset__c,Rental_Apply__r.Name,Rental_Apply_Equipment_Set__r.Name,
					Queue_Day__c,Queue_Number__c,Rental_Apply__r.WorkPlace__c,Rental_Apply__r.Person_In_Charge__r.Name,
					Rental_Apply__r.demo_purpose2__c,Queue_Conment__c,Equipment_Type_text__c,Salesdepartment_before__c,
					Internal_asset_location_before__c,jumpReason__c,Queue_User__r.Name,Rental_Apply__r.Hospital__r.Name,Rental_Apply__c,
					Rental_Apply__r.Campaign__r.Name,Externalkey__c,Rental_Apply__r.Internal_asset_location_F__c,QuenType__c
					 FROM Rental_Apply_Equipment_Set_Detail__c 
					 WHERE Id=:raesd.Id];
            return null;
        }

        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, messageHead + '暂定分配成功'));
        return null;
	}

	public PageReference quenBottom(){
		Savepoint sp = Database.setSavepoint();
        try {
            Rental_Apply_Equipment_Set_Detail__c detail = null;
        	for(Wrapper w:wrappers){
        		if(w.selected){
        			if(detail != null){
        				throw new ControllerUtil.myException('只能选择一个队列进行指定分配');
        			}
        			detail = w.detail;
        		}
        	}
        	if(detail == null){
        		throw new ControllerUtil.myException('请勾选数据进行操作');
        	}else if(!detail.Allow_Adjust_Queue_Flag__c){
        		throw new ControllerUtil.myException('备品总窗口未申请插队，无法调整顺序，请确认。');
        	}
        	if(raesd.QuenType__c == null){
	        	throw new ControllerUtil.myException('原单未参与过排队，无法明确队列信息并置顶或置底，请选择‘原单放弃排队’后进行排队');
	        }
        	detail = assignedUpdate(detail);
        	RentalApplyEquipmentSetDetailHandler.disabled = false;
            update detail;
        	
            reQueue(raesd,'bottom');
        }
        catch (Exception e) {
            System.debug('e.getMessage()***'+ e.getMessage()+e.getLineNumber());
            ApexPages.addMessages(e);
            Database.rollback(sp);
            raesd = [SELECT Id,Fixture_Model_No_text__c,Asset__c,Rental_Apply__r.Name,Rental_Apply_Equipment_Set__r.Name,
					Queue_Day__c,Queue_Number__c,Rental_Apply__r.WorkPlace__c,Rental_Apply__r.Person_In_Charge__r.Name,
					Rental_Apply__r.demo_purpose2__c,Queue_Conment__c,Equipment_Type_text__c,Salesdepartment_before__c,
					Internal_asset_location_before__c,jumpReason__c,Queue_User__r.Name,Rental_Apply__r.Hospital__r.Name,Rental_Apply__c,
					Rental_Apply__r.Campaign__r.Name,Externalkey__c,Rental_Apply__r.Internal_asset_location_F__c,QuenType__c
					 FROM Rental_Apply_Equipment_Set_Detail__c 
					 WHERE Id=:raesd.Id];
            return null;
        }
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, messageHead + '暂定分配成功'));
        return null;
	}

	public PageReference quenToDiscard(){
		Savepoint sp = Database.setSavepoint();
        try {
            Rental_Apply_Equipment_Set_Detail__c detail = null;
        	for(Wrapper w:wrappers){
        		if(w.selected){
        			if(detail != null){
        				throw new ControllerUtil.myException('只能选择一个队列进行指定分配');
        			}
        			detail = w.detail;
        		}
        	}
        	if(detail == null){
        		throw new ControllerUtil.myException('请勾选数据进行操作');
        	}else if(!detail.Allow_Adjust_Queue_Flag__c){
        		throw new ControllerUtil.myException('备品总窗口未申请插队，无法调整顺序，请确认。');
        	}
        	detail = assignedUpdate(detail);
        	RentalApplyEquipmentSetDetailHandler.disabled = false;
            update detail;
            // QueuePageByAssetIdController.saveQueue();
            raesd.Asset__c = null;
            raesd.Shipment_Status_Text__c = '待分配';
            raesd.Queue_Number__c = null;
            raesd.Queue_Day__c = null;
            raesd.Queue_Time__c = null;
            update raesd;
        }
        catch (Exception e) {
            System.debug('e.getMessage()***'+ e.getMessage()+e.getLineNumber());
            ApexPages.addMessages(e);
            Database.rollback(sp);
            raesd = [SELECT Id,Fixture_Model_No_text__c,Asset__c,Rental_Apply__r.Name,Rental_Apply_Equipment_Set__r.Name,
					Queue_Day__c,Queue_Number__c,Rental_Apply__r.WorkPlace__c,Rental_Apply__r.Person_In_Charge__r.Name,
					Rental_Apply__r.demo_purpose2__c,Queue_Conment__c,Equipment_Type_text__c,Salesdepartment_before__c,
					Internal_asset_location_before__c,jumpReason__c,Queue_User__r.Name,Rental_Apply__r.Hospital__r.Name,Rental_Apply__c,
					Rental_Apply__r.Campaign__r.Name,Externalkey__c,Rental_Apply__r.Internal_asset_location_F__c,QuenType__c
					FROM Rental_Apply_Equipment_Set_Detail__c 
					WHERE Id=:raesd.Id];
            return null;
        }
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, messageHead + '暂定分配成功'));
        return null;
	}

	public Rental_Apply_Equipment_Set_Detail__c assignedUpdate(Rental_Apply_Equipment_Set_Detail__c detail){
		if(raesd.Asset__c ==null){
			throw new ControllerUtil.myException('当前记录已更新，请刷新页面重试！');
		}
		detail.Asset__c = raesd.Asset__c;
    	Decimal oldQueueNumber = detail.Queue_Number__c;
    	String externalKey = detail.Externalkey__c;
    	detail.Queue_Number__c = 0;
    	detail.IsAdjust__c = true;
    	detail.Shipment_Status_Text__c = '暂定分配';
    	// 备品存放地(借出时)
    	detail.Internal_asset_location_before__c = raesd.Internal_asset_location_before__c;
    	detail.UniqueKey_Queue__c = null;
    	// if(detail.Queue_Day__c == null){
    	// 	detail.Queue_User__c   = UserInfo.getUserId();
     //        detail.Queue_Day__c    = Date.today();
     //        detail.Queue_Time__c   = RentalFixtureSetAssignController.getCurrentTime(); 
    	// }
    	System.debug(LoggingLevel.INFO, '*** newdetail: ' + detail);
    	raesd.Asset__c = null;	
    	raesd.Shipment_Status_Text__c = '排队中';
  		RentalApplyEquipmentSetDetailHandler.disabled = true;
		update raesd;
		System.debug(LoggingLevel.INFO, '*** raesd: ' + raesd);
		System.debug(LoggingLevel.INFO, '*** detail.Asset__c: ' + detail.Asset__c);
    	Asset ass = [SELECT Id,Out_of_wh__c,Out_of_wh_Sys__c,Last_Reserve_RAES_Detail__c FROM Asset WHERE Id=:assetId FOR Update];
    	System.debug(LoggingLevel.INFO, '**000* ass: ' + ass);
    	ass.Out_of_wh__c -= 1;
    	ass.Last_Reserve_RAES_Detail__c = null;
    	AssetHandler.disabled = true;
    	update ass;
    	System.debug(LoggingLevel.INFO, '*** ass: ' + ass);
    	return detail;
 
	}

	public Rental_Apply_Equipment_Set_Detail__c getSetDetail(){
		Rental_Apply_Equipment_Set_Detail__c selectSetDetail = null;
		Wrapper selectWrapper = null;
		for(Wrapper w:wrappers){
			if(w.selected){
				if(selectSetDetail !=null){
					throw new ControllerUtil.myException('请每次只选择一条数据');
					
				}else{
					selectSetDetail = w.detail;
				}
				
			}
		}

		return selectSetDetail;
	}

	public void initsequenceApply(){
		ast = [SELECT Id,Fixture_Model_No_F__c,Salesdepartment__c,Internal_asset_location__c,
				SalesProvince__c,Product_category__c,Equipment_Type__c 
				FROM Asset 
				WHERE Id=:raesd.Asset__c];
		externalKey = ast.Fixture_Model_No_F__c + ast.Internal_asset_location__c + ast.Salesdepartment__c
							+ ast.Equipment_Type__c + ast.Product_category__c;
		System.debug(LoggingLevel.INFO, '*** externalKey: ' + externalKey);
		// ras = getapplySequence(raesd.Id);
				
	}

	public List<Rental_Apply_Sequence__c> getapplySequence(String raesdId){

		List<Rental_Apply_Sequence__c> applySequences = [SELECT Id,ExternalKey__c,Fixture_Model_No__c,Internal_asset_location__c,Product_category__c,
												Salesdepartment__c,Series_No__c	,Demo_Purpose2__c,Invalid_Flag__c,Equipment_Type__c 
												FROM Rental_Apply_Sequence__c
												WHERE Apply_Set_Detail__c=:raesdId];
		return applySequences;
	}


	public Boolean isSinglekey(List<Rental_Apply_Sequence__c> sequenceList){
        String externalKey = sequenceList[0].Apply_Set_Detail_ExternalKey__c;
        for(Rental_Apply_Sequence__c sequeuece:sequenceList){
            if(externalKey != sequeuece.Apply_Set_Detail_ExternalKey__c){
                return false;
            }
        }
        return true;
    }

    public static void reQueue(Rental_Apply_Equipment_Set_Detail__c detail,String updownType){
    	List<Rental_Apply_Equipment_Set_Detail__c> updList = new List<Rental_Apply_Equipment_Set_Detail__c>();

    	detail =  [SELECT Id, Rental_Apply_Equipment_Set__c, Asset__c,Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c,QuenType__c,
                                               FSD_Fixture_Model_No__c, Fixture_Model_No_text__c,Externalkey__c,Rental_Apply__r.Product_category__c,
                                               Rental_Apply__r.demo_purpose2__c,Is_Body__c, FSD_Is_OneToOne__c, Select_Time__c,Rental_Apply__r.Salesdepartment__c,
                                               Rental_Apply__r.EquipmentGuaranteeFlg__c,Fixture_Model_No__c,Salesdepartment_before__c,Equipment_Type_text__c,
                                               Cancel_Select__c, Fixture_Model_No_F__c, Queue_Number__c, Internal_asset_location__c,Rental_Apply__r.Demo_purpose1__c,
                                               IsAdjust__c,Salesdepartment__c, Product_category_F__c, Equipment_Type__c, Internal_asset_location_before__c,
                                               Rental_Apply__r.Internal_asset_location_F__c,Cancel_Reason__c,Loaner_cancel_reason__c,Rental_Apply__r.Request_shipping_day__c,
                                               Loaner_cancel_Remarks__c ,Rental_Apply__r.CampaignType__c,Queue_Day__c,Queue_Time__c,Rental_Apply__r.Request_approval_time__c,
                                               Product_category_text__c
                                        FROM Rental_Apply_Equipment_Set_Detail__c
                                        WHERE Id=:detail.Id];
        System.debug(LoggingLevel.INFO, '*** detail: ' + detail);
    	String queuetype = detail.QuenType__c==null? '默认排队':detail.QuenType__c;
        RentalFixtureSetAssignController.KeyObj obj = new RentalFixtureSetAssignController.KeyObj();
        List<Rental_Apply_Sequence__c> allsequenceList = new List<Rental_Apply_Sequence__c>();
        List<String> sequencekeylist = new List<String>();
        if(detail.QuenType__c == null){
        	throw new ControllerUtil.myException('原单未参与过排队，无法明确队列信息并置顶或置底，请选择‘原单放弃排队’后进行排队');
        	// RentalFixtureSetAssignController.ApplyObj applyObj = new RentalFixtureSetAssignController.ApplyObj();
	        // applyObj.location = detail.Internal_asset_location_before__c;
	        // applyObj.productType = detail.Rental_Apply__r.Product_category__c;
	        // applyObj.salesdepartment = detail.Rental_Apply__r.Salesdepartment__c ;
	        // applyObj.purpose1 = detail.Rental_Apply__r.Demo_purpose1__c;
	        // applyObj.purpose2 = detail.Rental_Apply__r.demo_purpose2__c;
	        // applyObj.campaignType = '全国性学会';
	        // // queueIds.add(detail.Id);
	        // obj = RentalFixtureSetAssignController.getdefultInfo(detail,applyObj,detail.Internal_asset_location_before__c);
	        //  // 备品配套明细型号(借出时)
	        // detail.Fixture_Model_No_text__c = obj.model;
	        // // 所在地区(本部) 借出时
	        // detail.Salesdepartment_before__c = obj.salesdepartments;
	        
	        // // 产品分类(GI/SP)(借出时)
	        // detail.Product_category_text__c = obj.productType;
	        // // 备品分类(借出时)
	        // detail.Equipment_Type_text__c = obj.equipmenttypes;
	        // // 备品存放地(借出时)
	        // //detail.Internal_asset_location_before__c = obj.location;
	        // String key = obj.model  + obj.location + obj.salesdepartments  + obj.equipmenttypes  + obj.productType;
	        // System.debug(LoggingLevel.INFO, '*** detail.Id: ' + detail.Id);
	        // System.debug(LoggingLevel.INFO, '*** key: ' + key);
	        // detail.ExternalKey__c = key;
	        // detail.QuenType__c = queuetype;
        }else{
        	obj.model = detail.Fixture_Model_No_text__c;
        	obj.location = detail.Internal_asset_location_before__c;
        	obj.salesdepartments = detail.Salesdepartment_before__c;
        	obj.equipmenttypes = detail.Equipment_Type_text__c;
        	obj.productType = detail.Product_category_text__c;
        	obj.salesdepartmentList = obj.salesdepartments.split(',');
        	obj.equipmentList = obj.equipmenttypes.split(',');
        	obj.productTypes = obj.productType.split(',');
        }

        List<Rental_Apply_Equipment_Set_Detail__c> updateList = [SELECT Id, Rental_Apply_Equipment_Set__c, Asset__c,Rental_Apply_Equipment_Set__r.Fixture_Set__r.Product_Type__c,
                                                                   FSD_Fixture_Model_No__c, Fixture_Model_No_text__c,Externalkey__c,Rental_Apply__r.demo_purpose2__c,Equipment_Type_text__c,
                                                                   Is_Body__c, FSD_Is_OneToOne__c, Select_Time__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,Fixture_Model_No__c,
                                                                   Cancel_Select__c, Fixture_Model_No_F__c, Queue_Number__c, Internal_asset_location__c,IsAdjust__c,Queue_Day__c,Queue_Time__c,
                                                                   Salesdepartment__c, Product_category_F__c, Equipment_Type__c, Rental_Apply__r.Internal_asset_location_F__c,
                                                                   Cancel_Reason__c,Loaner_cancel_reason__c,Loaner_cancel_Remarks__c ,Rental_Apply__r.Request_shipping_day__c,Rental_Apply__r.Request_approval_time__c
                                                            FROM Rental_Apply_Equipment_Set_Detail__c
                                                            WHERE Externalkey__c =:detail.ExternalKey__c
                                                            AND Cancel_Select__c = false
                                                            AND Is_Body__c = true
                                                            AND Id <>:detail.Id
                                                            AND Queue_Number__c > 0 
                                                            ORDER BY Queue_Number__c];
        detail.IsAdjust__c = true;
        if(updownType == 'top'){
        	detail.Queue_Number__c = 1;
        }else if(updownType == 'bottom'){
        	detail.Queue_Number__c = updateList.size() + 1;
        }else{
        	detail.Queue_Number__c = -1;
        }
        for(String sales:obj.salesdepartmentList){
        
            for(String equip:obj.equipmentList){
                for(String type:obj.productTypes){
                    Rental_Apply_Sequence__c newSequence = new Rental_Apply_Sequence__c();
                    newSequence.ExternalKey__c = obj.model + obj.location + sales + equip + type;
                    newSequence.Demo_Purpose2__c = detail.Rental_Apply__r.demo_purpose2__c;
                    newSequence.Apply_Set_Detail__c = detail.Id;
                    newSequence.Series_No__c = detail.Queue_Number__c;
                    newSequence.Salesdepartment__c = sales;
                    newSequence.Product_category__c = type;
                    newSequence.Rental_Apply__c = detail.Rental_Apply__c;
                    newSequence.Internal_asset_location__c = obj.location;
                    newSequence.Fixture_Model_No__c = obj.model;
                    newSequence.Equipment_Type__c = equip;
                    sequencekeylist.add(newSequence.ExternalKey__c);
                    allsequenceList.add(newSequence);
                   
                }
            }
        }
        System.debug(LoggingLevel.INFO, '*** detail: ' + detail);
        updList.add(detail);
        insert allsequenceList;
        if(updownType != 'bottom'){
        	Integer i = 2;
        	for(Rental_Apply_Equipment_Set_Detail__c sdetail:updateList){
        		sdetail.Queue_Number__c = i;
        		i ++;
        	}
        	updList.addAll(updateList);
        }else{
	        Integer i = 1;
        	for(Rental_Apply_Equipment_Set_Detail__c sdetail:updateList){
        		sdetail.Queue_Number__c = i;
        		i ++;
        	}
        	updList.addAll(updateList);
        }
        update updList;
        allsequenceList = [SELECT Id,ExternalKey__c,Demo_Purpose2__c,Rental_Apply__r.Request_shipping_day__c,Rental_Apply__r.EquipmentGuaranteeFlg__c,
                                                        Apply_Set_Detail__c,Apply_Set_Detail_ExternalKey__c,Rental_Apply__r.Request_approval_time__c,Apply_Set_Detail__r.IsAdjust__c,
                                                        Series_No__c,Salesdepartment__c,Product_category__c,Apply_Set_Detail__r.Queue_Day__c,Apply_Set_Detail__r.Queue_Time__c,
                                                        Rental_Apply__c,Internal_asset_location__c,Series_Unequal_Queue_Flag__c,
                                                        Apply_Set_Detail__r.Queue_Number__c,Apply_Set_Detail__r.Queue_Time_F__c,Apply_Set_Detail__r.IndexFromUniqueKey__c,
                                                        // 20220105 ljh add Apply_Set_Detail__r.Queue_Time_F__c,Apply_Set_Detail__r.IndexFromUniqueKey__c,
                                                        Fixture_Model_No__c,Equipment_Type__c
                                                        FROM Rental_Apply_Sequence__c
                                                        WHERE Apply_Set_Detail__r.Queue_Day__c<>null 
                                                        AND Apply_Set_Detail__r.Queue_Time__c <> null
                                                        AND Series_No__c > 0
                                                        AND Invalid_Flag__c = false
                                                        AND Externalkey__c IN:sequencekeylist
                                                        ];
        allsequenceList = Batch_QueueAllDetail.getSortSequenceList(allsequenceList);
        update allsequenceList;
    }

	public PageReference backtoSetAssign(){
		if (String.isNotEmpty(targetId)) {
			PageReference ref =  new Pagereference('/');
				ref = new Pagereference('/apex/MainFixtureSelect?pt_recid=' + targetId);
				ref.setRedirect(true);
				return ref;
		} else {
			if(raesd.Rental_Apply__c != null){
				PageReference ref =  new Pagereference('/');
				ref = new Pagereference('/apex/RentalFixtureSetAssign?pt_recid=' + raesd.Rental_Apply__c);
				ref.setRedirect(true);
				return ref;
			}
			return null;
		}
	}
}