public with sharing class RentalApplyJumpController {
	/*--------- private ---------*/
    public Id objId {get; set;}            // 申请单ID
    private String raesIds {get; set;}      // 被选中的一览记录Id
    public String saveStatus {get; set;}    // 插队结果： 'ok'--成功
    /*--------- public(画面表示用) ---------*/
    public List<LineInfo> infoList {get; set;}   // 符合插队条件的被选中的一览记录
    public Id RaId {get; private set;}   // 申请单Id
    public Integer infoListSize { 
        get {
            return infoList == null ? 0 : infoList.size();
        }
    }
    public String errorMessage;
    List<Rental_Apply_Equipment_Set_Detail__c> raesdList;
    public RentalApplyJumpController() {
    	this.objId = ApexPages.currentPage().getParameters().get('objId');
        this.raesIds = ApexPages.currentPage().getParameters().get('raesIds');
        RaId = this.objId;
        raesdList = new List<Rental_Apply_Equipment_Set_Detail__c>();
    }
    public void init() {
    	infoList = new List<LineInfo>();
    	try{
            if (String.isBlank(this.objId)) {
                throw new ControllerUtil.myException('请设置备品借出申请的Id');
            }
            if (String.isBlank(this.raesIds)) {
                throw new ControllerUtil.myException('请设置备品借出申请一览的Id');
            }
            check();
	        for(Rental_Apply_Equipment_Set_Detail__c rd:raesdList){
	        	LineInfo lf = new LineInfo(rd);
	        	infoList.add(lf);
	        }
        } catch (ControllerUtil.myException me) {
            System.debug('myException caught when init: ' + me.getMessage());
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, me.getMessage()));
            errorMessage = me.getStackTraceString();
            return;
        } catch (Exception e) {
            System.debug('Exception caught when init: ' + e.getStackTraceString());
            ApexPages.addMessages(e);
            errorMessage = e.getStackTraceString();
            return;
        }

    }
    public PageReference saveJump() {
        check();
        List<Rental_Apply_Equipment_Set_Detail__c> updList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        // 明细行check
        Integer cntSelect = 0;
        Boolean hasError = false;
        for (LineInfo line : infoList) {
            if (line.isSelect == true) {
                if (String.isBlank(line.raesd.jumpReason__c)) {
                    line.raesd.jumpReason__c.addError('请输入插队原因');
                    hasError = true;
                }
                cntSelect += 1;
            }
        }
        if (cntSelect == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '未选择插队的明细。'));
            hasError = true;
        }
        if (hasError == true) {
            return null;
        }
        // 保存逻辑
        // for(){
            
        // }
        // 备品智能化 add by dzk 2023-10-24 start 申请插队批准过程
        Set<Id> renApplySet = new Set<Id>();
        // Map<Id,Id> renApplyMap = new Map<Id,Id>();
        User userData = [SELECT Id, Name,Profile.Name FROM User WHERE Id = :UserInfo.getUserId()];
        for (LineInfo line : infoList) {
            renApplySet.add(line.raesd.Rental_Apply__c);
        }
        // 20240111 ljh 插队申请优化 start
        List<Rental_Apply__c> rentalList = [SELECT Id,Name,
                                                   BuchangApprovalManagerSales__c 
                                                FROM Rental_Apply__c 
                                                WHERE Id =: renApplySet];
        // for(Rental_Apply__c ren : rentalList){
            // renApplyMap.put(ren.Id, ren.BuchangApprovalManagerSales__c);
        // }
        for (LineInfo line : infoList) {
            if (line.isSelect == true) {
                Rental_Apply_Equipment_Set_Detail__c upd = new Rental_Apply_Equipment_Set_Detail__c();
                upd = line.raesd;
                upd.jumpReason__c = line.raesd.jumpReason__c;
                // upd.BuchangApprovalManagerSales__c = renApplyMap.get(line.raesd.Rental_Apply__c);
                upd.BuchangApprovalManagerSales__c = rentalList[0].BuchangApprovalManagerSales__c;
                if(String.isBlank(line.raesd.OPD_Adjust_Queue__c) && userData.Profile.Name != '2B1_备品中心受理窗口'){
                    upd.Allow_Adjust_Queue_Flag__c = true;
                }else{
                    upd.Allow_Adjust_Queue_Flag__c = false;
                }
                updList.add(upd);
            }
        }
        // 20240111 ljh 插队申请优化 end
        FixtureUtil.withoutUpdate(updList);
        saveStatus = 'ok';
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存完了。'));
        // 发送邮件
        
        for(Rental_Apply_Equipment_Set_Detail__c appSetDetail : updList){
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setObjectId(appSetDetail.Id);
            String jumpUserId = System.Label.RentalApplyJumpUserId;
            if((jumpUserId.contains(userData.Id) && String.isNotBlank(appSetDetail.OPD_Adjust_Queue__c))
                || (userData.Profile.Name == '2B1_备品中心受理窗口')){
                Approval.ProcessResult processResult = Approval.process(req);
            }
        }
        // 备品智能化 add by dzk 2023-10-24 end 申请插队批准过程
        return null;
    }
    public void check(){
        // 判断是否存在状态和Id和父申请单都符合的选中一览记录
        String[] ids = raesIds.split(',');
        // 分单条件之一览状态--'待分配', '排队中', 
        // '暂定分配'
        Set<String> statusRaesSet = new Set<String>{FixtureUtil.raesStatusMap.get(FixtureUtil.RaesStatus.Dai_Fen_Pei.ordinal()),
                FixtureUtil.raesStatusMap.get(FixtureUtil.RaesStatus.Pai_Dui_Zhong.ordinal())
                // ,FixtureUtil.raesStatusMap.get(FixtureUtil.RaesStatus.Zan_Ding_Fen_Pei.ordinal())
                };
        raesdList = [
                // 备品智能化 add by dzk 2023-12-10 start 申请插队批准过程
                SELECT Id, Name,RAESD_Status__c,Rental_Apply__c,Fixture_Model_No__c,Rental_Apply_Equipment_Set__c,
                 Allow_Adjust_Queue_Flag__c,jumpReason__c,OPD_Adjust_Queue__c 
                  // 备品智能化 add by dzk 2023-12-10 end 申请插队批准过程
                FROM Rental_Apply_Equipment_Set_Detail__c
                WHERE  Is_Body__c = true 
                AND Rental_Apply_Equipment_Set__c in :ids
                AND Rental_Apply__c = :this.objId
                AND RAESD_Status__c in :statusRaesSet];
        if(raesdList.size() != ids.size()) {
            throw new ControllerUtil.myException('已选一览状态不符合插队条件,请选择明细状态都是 待分配与排队中的一览');
        }
    }
    class LineInfo {
        // 选择
        public boolean isSelect { get; set; }
        // 借出备品set一览 明细
        public Rental_Apply_Equipment_Set_Detail__c raesd { get; set; }
        public LineInfo(Rental_Apply_Equipment_Set_Detail__c r) {
            isSelect = false;
            raesd = r;
        }
    }

   
}