public without sharing class EquipmentRentalUnassignController {
    // 备品申请书
    public Rental_Apply__c rentalApply { get; set; }
    // 明细行项目
    public List<LineInfo> lineInfoList { get; set; }
    //备品申请书ID
    public String rentalApplyId { get; private set; }
    public Boolean hasError { get; private set; }
    public Boolean saveBtn { get; private set; }
    //现有备品数量（基于备品一览数量）
    public Integer EquipmentSetCnt{get;set;}
    private static final Map<String,Schema.RecordTypeInfo>  DEVELOPERNAMEMAP  = Schema.SObjectType.Rental_Apply__c.getRecordTypeInfosByDeveloperName();

    public String EquipmentId {get; private set;}
    // private String EquipmentId {get; set;}      // 被选中的一览记录Id

    public EquipmentRentalUnassignController() {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        rentalApplyId = ApexPages.currentPage().getParameters().get('raid');
        EquipmentId = ApexPages.currentPage().getParameters().get('EquipmentId');

    }

    // 画面初始化
    public PageReference init() {

        String tempId = DEVELOPERNAMEMAP.get('StandardRequest').getRecordTypeId();
        String recordId = tempId.length() == 15 ? tempId :tempId.substring(0,tempId.length() - 3);
        saveBtn = false;
        hasError = false;
        rentalApply = new Rental_Apply__c();
        lineInfoList = new List<LineInfo>();

        if (rentalApplyId != null && rentalApplyId.length() > 0) {
            // 备品借出申请取得
            List<Rental_Apply__c> raList = [
                select Id, Status__c, RA_Status__c
                  from Rental_Apply__c
                 where Id = :rentalApplyId];

            if (raList.size() > 0) {
                rentalApply = raList[0];
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品申请书不存在，请确认。'));
                saveBtn = true;
                return null;
            }
        } else {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品申请书不存在，请确认。'));
            saveBtn = true;
            return null;
        }
        List<Id> qumentIds = new List<Id>();
        if (EquipmentId != null && EquipmentId.length() > 0) {
       		List<Id> rentalequimentIds = EquipmentId.split(',');

            List<Rental_Apply_Equipment_Set__c> rentalequipmentList = [select Id,Name,RAES_Status__c,Cancel_Select__c from Rental_Apply_Equipment_Set__c 
            			where RARecordTypeId__c = :recordId and Id in :rentalequimentIds ];
            if (rentalequipmentList == null || rentalequipmentList.size() == 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '您选择的一览不符合条件,请重新选中'));
                saveBtn = true;
                return null;
            }else{
            	Boolean a = false;
            	String str = '';
            	for (Rental_Apply_Equipment_Set__c se : rentalequipmentList) {
            		if (se.RAES_Status__c == '已分配' || se.RAES_Status__c == '已出库指示') {
            		    qumentIds.add(se.Id);
            		    a = true;
            		}
            		if (se.RAES_Status__c != '已分配' && se.RAES_Status__c != '已出库指示') {
            			str += se.Name + '， ';
            		}else if (se.Cancel_Select__c ) {
            		    str += se.Name +'， ';
            		}
            	}

            	if (str.length() > 0 ) {
            	    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '您选择的一览'+str.substring(0,str.length()-2)+'不符合条件'));
            	}
            	if (!a) {
            	    return null;
            	}
            }
        }

        // 备品借出备品set一览取得 
        List<Rental_Apply_Equipment_Set__c> raesList = new List<Rental_Apply_Equipment_Set__c>();
        if (qumentIds.size() == 0 && (EquipmentId == null || EquipmentId == '')) {
            raesList = [
	            select id, Name, Fixture_Set__c, Fixture_Set__r.Name, Fixture_Set__r.Loaner_code__c, RAES_Status__c, Rental_Start_Date__c, Final_reply_day__c, Yi_StockDown__c,
	                   StockDown_time__c, Shippment_loaner_time2__c, Cancel_Select__c, Cancel_Reason__c, Cancel_Mem__c, Loaner_cancel_Remarks__c, Fixture_Set__r.Loaner_name__c,
	                   First_RAESD__r.Asset__c,Loaner_cancel_reason__c //20210708 SFDC-C448KZ you start
	              from Rental_Apply_Equipment_Set__c
	             where Rental_Apply__c = :rentalApply.Id
	               and RARecordTypeId__c = :recordId 
	               and RAES_Status__c in ('已分配','已出库指示')
	               and Cancel_Select__c = false];
        }else {
        	raesList = [
	            select id, Name, Fixture_Set__c, Fixture_Set__r.Name, Fixture_Set__r.Loaner_code__c, RAES_Status__c, Rental_Start_Date__c, Final_reply_day__c, Yi_StockDown__c,
	                   StockDown_time__c, Shippment_loaner_time2__c, Cancel_Select__c, Cancel_Reason__c, Cancel_Mem__c, Loaner_cancel_Remarks__c, Fixture_Set__r.Loaner_name__c,
	                   First_RAESD__r.Asset__c,Loaner_cancel_reason__c //20210708 SFDC-C448KZ you start
	              from Rental_Apply_Equipment_Set__c
	             where Rental_Apply__c = :rentalApply.Id
	               and RARecordTypeId__c = :recordId 
	               and RAES_Status__c in ('已分配','已出库指示')
	               and Cancel_Select__c = false
	               and id in :qumentIds];
        }
         

        if (raesList.size() == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品申请书未分配明细，不能取消分配。'));
            saveBtn = true;
            return null;
        }else{
            EquipmentSetCnt = raesList.size();
        }

        // 明细行做成
        for (Rental_Apply_Equipment_Set__c raes : raesList) {
            LineInfo lineInfo = new LineInfo(raes);
            lineInfoList.add(lineInfo);
        }

        return null;
    }

    // 保存按钮
    public PageReference saveBtn() {
        List<Rental_Apply_Equipment_Set__c> delList = new List<Rental_Apply_Equipment_Set__c>();
        List<Rental_Apply_Equipment_Set__c> updList = new List<Rental_Apply_Equipment_Set__c>();
        Set<Id> esIdSet = new Set<Id>();

        // 明细行check
        Integer cntSelect = 0;
        hasError = false;
        //获取已选中的一览
        Set<Id> ylIds = new Set<Id>();
        for (LineInfo line : lineInfoList) {
            if (line.isSelect == true) {
            	ylIds.add(line.raes.Id);
                cntSelect += 1;
            }
        }
        if (cntSelect == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '未选择取消分配的明细。'));
            hasError = true;
        }
        if (hasError == true) {
            system.debug('=====hasError');
            return null;
        }

        Set<Id> raesdIdSet = new Set<Id>();
        //获取一览明细
        List<Rental_Apply_Equipment_Set_Detail__c> detailList = [select id,Is_Body_F__c,Rental_Apply__r.Internal_asset_location_F__c,Rental_Apply__r.Salesdepartment__c,Rental_Apply__r.Owner_province__c,Rental_Apply__r.demo_purpose2__c,Rental_Apply__r.Demo_purpose1__c
                                    from 
        							Rental_Apply_Equipment_Set_Detail__c 
        							where Rental_Apply_Equipment_Set__c in :ylIds AND EquipmentSet_Detail_Status_Status__c in ('已分配','已出库指示') FOR UPDATE];


        // 保存逻辑
        for (LineInfo line : lineInfoList) {
            if (line.isSelect == true) {
                Rental_Apply_Equipment_Set__c upd = new Rental_Apply_Equipment_Set__c();
                upd.Id = line.raes.Id;
                // 清空 主体产品
                upd.Product2__c = '';
                // 主体产品F
                // 备品管理编码
                // 机身编号
                // 固定资产号码


                updList.add(upd);
            }
        }
        //更新明细
        if (detailList != null && detailList.size() > 0) {
            for (Rental_Apply_Equipment_Set_Detail__c robj : detailList) {
            	// 主体和附属品均会清空如下字段
            	// 相关字段置为 null
                // 保有设备 = 空
                robj.Asset__c = null;
                // 分配时间 = 空
                robj.Select_Time__c = null;
                // 出库指示时间 = 空
                robj.Shipment_request_time2__c = null;
                // 已做出库指示 = 空
                robj.Shipment_request__c = false;

                // 备品管理编码(借出时)
                robj.EquipmentSet_Managment_Code_text__c = null;
                // 机身编号（借出时）
                robj.SerialNumber_text__c = null;


                //备品存放地(借出时) = 备品借出申请单的备品存放地
                robj.Internal_asset_location_before__c = robj.Rental_Apply__r.Internal_asset_location_F__c;
                //所在地区(本部) 借出时  = 备品借出申请单的借出申请人-销售本部
                robj.Salesdepartment_before__c = robj.Rental_Apply__r.Salesdepartment__c;
                //所在地区(省) 借出时 =备品借出申请单的借出申请人-省
                robj.SalesProvince_before__c = robj.Rental_Apply__r.Owner_province__c;
                //备品分类(借出时) =  使用目的2,使用目的1 --不用了 现在设置为null
                robj.Equipment_Type_text__c = null;
                // robj.Equipment_Type_text__c = robj.Rental_Apply__r.demo_purpose2__c + ','+robj.Rental_Apply__r.Demo_purpose1__c;
                // 清空排队信息
                //主体还需清空排队信息
				if (robj.Is_Body_F__c) {
                    // 排队备注
				    robj.Queue_Conment__c = null;
                    // 排队日
                    robj.Queue_Day__c = null;
                    // 负责人
                    robj.Queue_User__c = null;
                    // 排队No
                    robj.Queue_Number__c = null;
				}
            }
        }
        // 保存
        Savepoint sp = Database.setSavepoint();
        try {
            if (detailList.size() > 0) {
                update detailList;
            }
            if (updList.size() > 0) {
                FixtureUtil.withoutUpdate(updList);            
            }
        }
        catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            hasError = true;
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            return null;
        }


        // 保存
        // Savepoint sp = Database.setSavepoint();
        // try {
        //     // if  (   delList.size()  >   0   )   delete  delList;
        //     if (!raesdIdSet.isEmpty()) {
        //         List<Fixture_OneToOne_Link__c> fotos = [Select Id From Fixture_OneToOne_Link__c
        //                 Where Main_Asset__c =: raesdIdSet
        //                 for update];
        //         if (!fotos.isEmpty()) {
        //             for (Fixture_OneToOne_Link__c foto : fotos) {
        //                 foto.Select_Accessory_Asset_Cnt__c = 0;
        //             }
        //             FixtureUtil.withoutUpdate(fotos);
        //         }
        //     }
        //     if  (   updList.size()  >   0   ) {
        //         Set<Id> assetIdSet = new Set<Id>();
        //         for (Rental_Apply_Equipment_Set_Detail__c raesd : [SELECT Id, Asset__c
        //                                                              FROM Rental_Apply_Equipment_Set_Detail__c
        //                                                             WHERE Rental_Apply_Equipment_Set__c = :updList FOR UPDATE]
        //         ) {
        //             if (String.isNotBlank(raesd.Asset__c)) {
        //                 assetIdSet.add(raesd.Asset__c);
        //             }
        //         }
        //         if (assetIdSet.size() > 0) {
        //             List<Asset> assetList = [SELECT Id
        //                      FROM Asset
        //                     WHERE Id = :assetIdSet FOR UPDATE];
        //         }
        //         FixtureUtil.withoutUpdate(updList);
        //     }

        // }   catch (Exception ex)    {
        //     system.debug('=====' + ex.getMessage());
        //     hasError = true;
        //     ApexPages.addMessages(ex);
        //     Database.rollback(sp);
        //     return null;
        // }
        return null;
    }

    @TestVisible
    class LineInfo {
        // 选择
        public boolean isSelect { get; set; }
        // 借出备品set一览
        public Rental_Apply_Equipment_Set__c raes { get; set; }
        // 状态：可以删除、可以取消、不能取消
        //public String status { get; private set; }
        public String esName { get; private set; }
        public String loanerCode { get; private set; }
        public LineInfo(Rental_Apply_Equipment_Set__c r) {
            isSelect = false;
            raes = r;
            loanerCode = r.Fixture_Set__r.Loaner_name__c;
            ////cancel
            //if (r.Yi_StockDown__c > 0) {
            //    status = 'canCancel';
            ////下架以后改成待上架的checkbox
            ////cancel
            //} else {
            //    status = 'OnStock_Pre_Inspection';
            //}
            esName = r.Fixture_Set__r.Name;
        }
    }

}