// xudan 20160106 Arrival_wh_time__c -> Arrival_wh_time2__c（回库はSet単位なので、積み上げ項目使わず）
// RentalFixtureManage7Test-->EquipmentSetShippmentReceived3CtrlTest(测试文件变这个了)
public without sharing class EquipmentSetShippmentReceived3Controller {
    public FixtureDeliverySlip__c slip { get; set; }
    public Rental_Apply_Equipment_Set__c es { get; set; }
    public List<EsdInfo> esdList { get; set; }
    public Boolean saveBtnDisabled { get; private set; }
    public boolean ReturnRefuse {get;private set;}
    public String ErrorMessage {get; set;}
    // public String CDSFinished {get;set;}
    // public boolean LostFlg {get;set;}
    public String Step_status { get; private set; }
    public Boolean needCDS { get; private set; }
    public Boolean done_flg { get; set; }
    public String Raid {get;set;}
    public String ApplyId {get;set;}
    public String CheckedId {get;set;}
    public String UnCheckedId {get;set;}
    private String Id;

    public Integer getEsdListSize() {
        return esdList.size();
    }

    public EquipmentSetShippmentReceived3Controller() {
//        Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        Id = ApexPages.currentPage().getParameters().get('id');
        if (Step_status == null) {
            Step_status = ApexPages.currentPage().getParameters().get('step');
        }
        ApplyId = Id;
    }

    public PageReference searchSlip() {
        Map<String,boolean> esdIdMap = new Map<String,boolean>();
        for (EsdInfo esd : esdList) {
            if (!esd.hasSended)
            esdIdMap.put(esd.rec.Id, esd.isChecked);
        }

        String qryString = 'select Combine_Pack__c, Name, Id, DeliveryCompany_SlipNo__c,DeliveryType__c,Distributor_method__c,DeliveryCompany__c,Wh_Staff__c '
                + 'from FixtureDeliverySlip__c '
                + 'where Name =\''+ slip.Name +'\' and DeliveryType__c = \'发货\'';
        if (String.isNotBlank(slip.Distributor_method__c)) {
            qryString += ' and Distributor_method__c = \''+ slip.Distributor_method__c +'\'';
        }
        if (String.isNotBlank(slip.DeliveryCompany__c)) {
            qryString += ' and DeliveryCompany__c = \''+ slip.DeliveryCompany__c +'\'';
        }
        List<FixtureDeliverySlip__c> slipList = Database.query(qryString);

        if (slipList.size() > 0) {
            if (slipList.size() > 1) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '当前条件检索到复数条运输单，请追加检索条件!'));
                return null;
            }
            slip = slipList[0];

            List<Rental_Apply_Equipment_Set_Detail__c> eList = [select Rental_Apply__c, Rental_Apply__r.Shippment_ng_num__c, Rental_Apply__r.Pre_inspection_ng_num__c, SerialNumber_F__c, Rental_Apply_Equipment_Set__r.Inspection_not_finish__c, Fixture_Name_F__c, Rental_Apply_Equipment_Set__r.Fixture_Set__r.Name, Rental_Apply_Equipment_Set__r.Rental_Apply__r.Name, Rental_Apply_Equipment_Set__r.Name, Pre_inspection_time__c, StockDown__c, StockDown_time__c, Id, Name, Asset__c, Asset__r.Name, Asset__r.SerialNumber, Asset__r.Product_Serial_No__c,
                           Asset__r.Remark__c, Asset__r.ImageAsset__c, Asset__r.ImageSerial__c, Asset__r.ImageAssetUploadedTime__c, Asset__r.ImageSerialUploadedTime__c,
                           Loaner_CDS_Info__c, Inspection_result__c, Check_lost_Item__c, Pre_disinfection__c, Water_leacage_check__c, Inspection_result_after__c, Arrival_in_wh__c,
                           Asset__r.Pre_Reserve_RAES_Detail__c, Asset__r.Pre_Reserve_RAES_Detail__r.After_Inspection_time__c,
                           Inspection_result_after_ng__c, Inspection_result_ng__c, Lost_item_giveup__c, CDS_complete__c, Loaner_accsessary__c
                      from Rental_Apply_Equipment_Set_Detail__c
                     where (DeliverySlip__c = :slip.Id or Id in :esdIdMap.keySet())
                       and Cancel_Select__c = False and Return_DeliverySlip__c = null
                     order by Rental_Apply_Equipment_Set__r.Rental_Apply__r.Name, Rental_Apply_Equipment_Set__r.Name, Rental_Apply_Equipment_Set__c, Name];

            esdList.clear();
            for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
                EsdInfo esdinfo;
                if (esdIdMap.containsKey(esd.Id)) {
                    esdinfo = new EsdInfo(esd, esdIdMap.get(esd.Id));
                } else {
                    esdinfo = new EsdInfo(esd, true);
                    esdInfo.hasSended = true;
                }
                esdList.add(esdInfo);
            }
        }
        return null;
    }

    public PageReference filljsQRAction() {
        List<String> ids = ApplyId.split(',');
        Set<String> checkedIds = new Set<String>(CheckedId.split(':'));
        CheckedId = null;
        List<Rental_Apply_Equipment_Set__c> esList = [select Rental_Apply__r.Name, First_RAESD_Model_No_F__c, First_RAESD__r.SerialNumber_F__c, First_RAESD__r.Loaner_asset_no__c, Rental_Apply__c, Id, RAES_Status__c, Name, Shippment_loaner_time2__c
                                    from Rental_Apply_Equipment_Set__c
                                    where (Rental_Apply__r.Name in :ids or Id in :ids)
                                      AND Cancel_Select__c = False
                                    order by Rental_Apply__r.Name, Id];
        Set<Id> esIds = new Set<Id>();
        Set<Id> esdIds = new Set<Id>();
        Set<Id> applySet = new Set<Id>();
        for (Rental_Apply_Equipment_Set__c raes : esList) {
            esIds.add(raes.Id);
            applySet.add(raes.Rental_Apply__c);
        }
        Raid = String.join(new List<Id>(applySet), ':');
        for (EsdInfo raesd : esdList) {
            esdIds.add(raesd.rec.Id);
        }
        List<Rental_Apply_Equipment_Set_Detail__c> eList = [
                select Rental_Apply__c, Rental_Apply__r.Shippment_ng_num__c, Rental_Apply__r.Pre_inspection_ng_num__c, SerialNumber_F__c, Rental_Apply_Equipment_Set__r.Inspection_not_finish__c, Fixture_Name_F__c, Rental_Apply_Equipment_Set__r.Fixture_Set__r.Name, Rental_Apply_Equipment_Set__r.Rental_Apply__r.Name, Rental_Apply_Equipment_Set__r.Name, Pre_inspection_time__c, StockDown__c, StockDown_time__c, Id, Name, Asset__c, Asset__r.Name, Asset__r.SerialNumber, Asset__r.Product_Serial_No__c,
                       Asset__r.Remark__c, Asset__r.ImageAsset__c, Asset__r.ImageSerial__c, Asset__r.ImageAssetUploadedTime__c, Asset__r.ImageSerialUploadedTime__c,
                       Loaner_CDS_Info__c, Inspection_result__c, Check_lost_Item__c, Pre_disinfection__c, Water_leacage_check__c, Inspection_result_after__c, Arrival_in_wh__c,
                       Asset__r.Pre_Reserve_RAES_Detail__c, Asset__r.Pre_Reserve_RAES_Detail__r.After_Inspection_time__c,
                       Inspection_result_after_ng__c, Inspection_result_ng__c, Lost_item_giveup__c, CDS_complete__c, Loaner_accsessary__c
                  from Rental_Apply_Equipment_Set_Detail__c
                 where Rental_Apply_Equipment_Set__c in :esIds and DeliverySlip__c = null and Return_DeliverySlip__c = null //and Inspection_result__c <> null and Shipment_request_time2__c <> null
                   and Cancel_Select__c = False
                 order by Rental_Apply_Equipment_Set__r.Rental_Apply__r.Name, Rental_Apply_Equipment_Set__r.Name, Rental_Apply_Equipment_Set__c, Name
        ];
        //esdList.clear();
        for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
            //boolean checked = checkedIds.contains(esd.Id);
            if (!esdIds.contains(esd.Id)) {
                esdList.add(new EsdInfo(esd, false));
            }
        }

        for (EsdInfo raesd : esdList) {
            if (checkedIds.contains(raesd.rec.Rental_Apply_Equipment_Set__c)) {
                raesd.isChecked = true;
                system.debug('========4esdList='+JSON.serialize(raesd));
            }
        }
        return null;
    }

    // 画面初始化
    public PageReference init() {
        done_flg = false;
        es = new Rental_Apply_Equipment_Set__c();
        slip = new FixtureDeliverySlip__c();
        esdList = new List<EsdInfo>();
        Set<Id> esIds = new Set<Id>();
        saveBtnDisabled = false;
        ReturnRefuse = true;
        ErrorMessage = '';
        if (Id != null) {
            system.debug('==================='+Id);
            // 当前User
            String userid = Userinfo.getUserId();
            User user = [select Id,Name from User where Id = :userid];
            List<Rental_Apply_Equipment_Set__c> esList;
            List<String> ids = Id.split(',');
            esList = [select Rental_Apply__r.Name, First_RAESD_Model_No_F__c, First_RAESD__r.SerialNumber_F__c, First_RAESD__r.Loaner_asset_no__c, Rental_Apply__c, Id, RAES_Status__c, Name, Shippment_loaner_time2__c
                                        from Rental_Apply_Equipment_Set__c
                                       where (Rental_Apply__r.Name in :ids or Id in:ids)
                                         AND Cancel_Select__c = False
                                       order by Rental_Apply__r.Name, Id];
         //   if (Step_status == '追加') {

            //} else {
            //  // 备品set
         //     esList = [select Rental_Apply__r.Name, First_RAESD_Model_No_F__c, First_RAESD__r.SerialNumber_F__c, First_RAESD__r.Loaner_asset_no__c, Rental_Apply__c, Id, RAES_Status__c, Name, Shippment_loaner_time__c
         //                                   from Rental_Apply_Equipment_Set__c
         //                                  where (Rental_Apply__r.Name = :Id or Id = :Id)
         //                                    AND Cancel_Select__c = False
         //                                  ];
            //}

            //if (Step_status == '明细') {
                slip.Wh_Staff__c = userid;
                slip.DeliveryType__c = '发货';
            //}
            //List<Fixture_Set__c> esList = [select Id, Name, CDS_staff__c, Shippment_loaner_time__c, Received_loaner_time__c, 
            //                                       delivery_company__c, Return_to_wh_staff__c, Return_to_wh_staff__r.Name, Fedex_number__c, Distributor_method__c,
            //                                       Return_delivery_company__c,Return_wh_chenk_staff__c, Received_confirmation_staff__c, Received_confirmation_staff__r.Name, Return_Fedex_number__c, Return_Distributor_method__c,
            //                                       Arrival_wh_time2__c, Asset_return_time__c,
            //                                       CDS_complete__c, Arrival_in_wh__c, StockDown__c,
            //                                       Lost_item_check_time__c,Last_Reserve_Rental_Apply_Fixture_Set__c,
            //                                       StockDown_time__c
            //                                  from Fixture_Set__c where Name = :Id];
            if (esList.size() > 0) {
                //es = esList[0];
                for (Rental_Apply_Equipment_Set__c raes : esList) {
                    esIds.add(raes.Id);
                    Raid = raes.Rental_Apply__c;
                }
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '备品不存在'));
                saveBtnDisabled = true;
                return null;
            }
            //检查验证规则修理最终检测日
            /*   todo
            List<Rental_Apply_Equipment_Set__c> CheckRAES = [select id,Name,RAES_Status__c,Rental_Apply__c,Rental_Apply__r.Repair__c,Cancel_Date__c,Fixture_Set__c 
                    from Rental_Apply_Equipment_Set__c where id=:es.Last_Reserve_Rental_Apply_Equipment_Set__c];
            Rental_Apply_Equipment_Set__c Ra_c = new Rental_Apply_Equipment_Set__c();
            Rental_Apply__c Rac = new Rental_Apply__c();
            if(CheckRAES.size()>0){
                Ra_c = CheckRAES[0];
                Raid = Ra_c.Rental_Apply__c;
            }
            system.debug(Ra_c.Rental_Apply__r.Repair__c );
            List<Rental_Apply__c> CheckError = new List<Rental_Apply__c>();
            CheckError = [Select id,name,repair__c,repair__r.Return_Without_Repair_Date__c,repair__r.Repair_Final_Inspection_Date__c,repair__r.Repair_Shipped_Date__c,
                                Campaign__c,Campaign__r.Status
                                            from Rental_Apply__c where id=:Ra_c.Rental_Apply__c
                                            and RA_Status__c !='取消'
                                            and RA_Status__c !='删除'];
            if(CheckError.size()>0){
                Rac = CheckError[0];
            }
            */

            //system.debug('All::::'+Rac.repair__r.Repair_Final_Inspection_Date__c);
            // system.debug('All::::'+Rac.repair__c);
            //  system.debug('All::::'+Ra_c.RAES_Status__c);
            // 本番暂不上线该功能，启用后不能入库操作感觉不对


        }

        // 备品set明细
        List<Rental_Apply_Equipment_Set_Detail__c> eList = [
                select Rental_Apply__c, Rental_Apply__r.Shippment_ng_num__c, Rental_Apply__r.Pre_inspection_ng_num__c, SerialNumber_F__c, Rental_Apply_Equipment_Set__r.Inspection_not_finish__c, Fixture_Name_F__c, Rental_Apply_Equipment_Set__r.RAES_Status__c, Rental_Apply_Equipment_Set__r.Fixture_Set__r.Name, Rental_Apply_Equipment_Set__r.Rental_Apply__r.Name, Rental_Apply_Equipment_Set__r.Name, Pre_inspection_time__c, StockDown__c, StockDown_time__c, Id, Name, Asset__c, Asset__r.Name, Asset__r.SerialNumber, Asset__r.Product_Serial_No__c,
                       Asset__r.Remark__c, Asset__r.ImageAsset__c, Asset__r.ImageSerial__c, Asset__r.ImageAssetUploadedTime__c, Asset__r.ImageSerialUploadedTime__c,
                       Loaner_CDS_Info__c, Inspection_result__c, Check_lost_Item__c, Pre_disinfection__c, Water_leacage_check__c, Inspection_result_after__c, Arrival_in_wh__c,
                       Asset__r.Pre_Reserve_RAES_Detail__c, Asset__r.Pre_Reserve_RAES_Detail__r.After_Inspection_time__c,
                       Inspection_result_after_ng__c, Inspection_result_ng__c, Lost_item_giveup__c, CDS_complete__c, Loaner_accsessary__c
                  from Rental_Apply_Equipment_Set_Detail__c
                 where Rental_Apply_Equipment_Set__c in :esIds and DeliverySlip__c = null and Return_DeliverySlip__c = null//and Shipment_request_time__c <> null
                   and Cancel_Select__c = False
                 order by Rental_Apply_Equipment_Set__r.Rental_Apply__r.Name, Rental_Apply_Equipment_Set__r.Name, Rental_Apply_Equipment_Set__c, Name
        ];
        //Set<Id> lockId = new Set<Id>();
        //for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
        //    lockId.add(esd.Id);
        //}
        //List<Rental_Apply_Equipment_Set_Detail__c> eListlock = [
        //        select Id
        //          from Rental_Apply_Equipment_Set_Detail__c
        //         where Id in :lockId for update
        //];
        system.debug(eList);

        needCDS = false;
        for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
            esdList.add(new EsdInfo(esd));
        }

        if (String.isBlank(Step_status)) {
            Step_status = '追加';
        }

        if (esdList.size() <= 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有备品set明细'));
            saveBtnDisabled = true;
            return null;
        }

        system.debug('=====' + Step_status);

        return null;
    }

    //// Step 切り替えボタン、发货前-检测
    //public PageReference Shippment() {
    //    Step_status = '运输单';
    //    return new PageReference('/apex/EquipmentSetShippmentReceived3?id=' + this.Id + '&type=' + this.SR_status + '&step=' + this.Step_status + '&open=' + this.open_type);
    //}

    // Step 切り替えボタン、发货前-检测
    public PageReference ShippmentDetail() {
        system.debug('========cid='+CheckedId);
        system.debug('========esd='+esdList.size());
        Step_status = '明细';
        //slip.Wh_Staff__c = Userinfo.getUserId();
        //slip.DeliveryType__c = '发货';
        if (!String.isBlank(CheckedId)) {
            Map<String, Set<String>> shipcount = new Map<String, Set<String>>();
            Map<String, Integer> allcount = new Map<String, Integer>();
            Set<String> checkedIds = new Set<String>(CheckedId.split(':'));
            for (EsdInfo esd : esdList) {
                boolean checked = checkedIds.contains(esd.rec.Rental_Apply_Equipment_Set__c);
                esd.isChecked = checked;
                if (checked) {
                    Set<String> count = new Set<String>();
                    if (shipcount.containsKey(esd.rec.Rental_Apply__c)) {
                        count = shipcount.get(esd.rec.Rental_Apply__c);
                    }
                    count.add(esd.rec.Rental_Apply_Equipment_Set__c);
                    shipcount.put(esd.rec.Rental_Apply__c, count);
                    allcount.put(esd.rec.Rental_Apply__c, Integer.valueOf(esd.rec.Rental_Apply__r.Shippment_ng_num__c));
                }
            }
            system.debug('========shipcount='+JSON.serialize(shipcount));
            system.debug('========shipcount='+JSON.serialize(allcount));
            for (String raid : allcount.keySet()) {
                if (allcount.get(raid) > shipcount.get(raid).size()) {
                    Step_status = '追加';
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '申请单内存在未勾选的配套，请勾选全部配套或分割申请单!'));
                }
            }
        }
        CheckedId = null;

        return null;
        //return new PageReference('/apex/EquipmentSetShippmentReceived3?id=' + this.Id + '&step=' + this.Step_status);
    }

    // Step 切り替えボタン、发货-发货运输单号 等
    public PageReference ShippmentAdd() {
        Step_status = '追加';
        system.debug('========2esdList='+JSON.serialize(esdList));
        //return new PageReference('/apex/EquipmentSetShippmentReceived3?id=' + this.Id + '&step=' + this.Step_status);
        return null;
    }

    public PageReference deleteDetail() {
        List<Rental_Apply_Equipment_Set_Detail__c> updDetails = new List<Rental_Apply_Equipment_Set_Detail__c>();
        for (EsdInfo esd : esdList) {
            if (esd.rec.Rental_Apply_Equipment_Set__c == UnCheckedId) {
                if (esd.hasSended) {
                    esd.rec.DeliverySlip__c = null;
                    updDetails.add(esd.rec);
                } else {
                    esd.isChecked = false;
                }
            }
        }
        UnCheckedId = null;
        if (updDetails.size() > 0) {
            update updDetails;
            searchSlip();
        }

        return null;
    }

    // 保存按钮
    public PageReference save() {

        List<String> raids = Raid.split(':');
        //检查是否可以继续
        List<Rental_Apply__c> RaTarList = [select Name,Campaign__c,Repair__c,next_action__c
                                                ,QIS_number__r.ReplaceDeliveryDate__c,demo_purpose2__c
                                                ,Follow_UP_Opp__r.Shipping_Finished_Day_Func__c
                                                ,Campaign__r.Status
                                                ,Campaign__r.IF_Approved__c
                                                ,Campaign__r.Meeting_Approved_No__c // 20220315 ljh obpm备品决裁状态相关修改
                                                ,Campaign__r.Approved_Status__c     // 20220315 ljh obpm备品决裁状态相关修改
                                                ,repair__r.Return_Without_Repair_Date__c
                                                ,Repair__r.Repair_Final_Inspection_Date__c
                                                ,Repair__r.Repair_Shipped_Date__c
                                            from Rental_Apply__c 
                                            where id in :raids];//20210602 ljh update 增加查询Name SFDC-C3LBNL 
        //20210604 ljh update SFDC-C3LBNL start
        Boolean errorFlag = false;
        String message0 = '';
        String message1 = '';
        String message2 = '';
        String message3 = '';
        String message = '';
        String message4 = '';//1822 yc 20211025 已购待货目的，新品已有发货日不能出库
        String message5 = '';//1822 yc 20211108 索赔QIS目的，QIS已有新品发货日不能出库
        String message6 = '';
        String message7 = '';// 20220315 ljh obpm备品决裁状态相关修改 end
        // 要判断决裁状态不能是草稿/驳回/终止申请/取消/删除
        List<String> statusList = System.Label.StatusProcessState.split(',');
        Map<Id, Rental_Apply__c> RaMap = new Map<Id, Rental_Apply__c>();
        for (Rental_Apply__c RaTar : RaTarList) {
            if( RaTar.Campaign__r.Status == '取消'){
                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '学会已取消，不能继续操作了'));
                // return null;
                errorFlag = true;
                message0 += RaTar.Name+'、';
            }else if(RaTar.Repair__r.Repair_Final_Inspection_Date__c!=null){
                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '存在修理最终检测日，不能继续了'));        
                // return null;
                errorFlag = true;
                message1 += RaTar.Name+'、';
            }else if(RaTar.repair__r.Return_Without_Repair_Date__c!=null&&RaTar.repair__c!=null ){

                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未修理归还日不为空，不能出库'));
                // return null;
                errorFlag = true;
                message2 += RaTar.Name+'、';
            }else if(RaTar.Repair__r.Repair_Shipped_Date__c!=null){

                // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '存在RC修理返送日，不能继续了'));
                // return null;
                errorFlag = true;
                message3 += RaTar.Name+'、';
            }
            //1822 yc 20211025 已购待货目的，新品已有发货日不能出库 start
            else if(RaTar.demo_purpose2__c=='已购待货' && RaTar.Follow_UP_Opp__r.Shipping_Finished_Day_Func__c!= null){
                errorFlag = true;
                message4 += RaTar.Name+'、';
            }else if(RaTar.demo_purpose2__c=='索赔QIS' && RaTar.next_action__c=='无偿更换' && RaTar.QIS_number__r.ReplaceDeliveryDate__c!= null){
                errorFlag = true;
                message5 += RaTar.Name+'、';
            }
            //1822 yc 20211025 已购待货目的，新品已有发货日不能出库 end
            // 20220315 ljh obpm备品决裁状态相关修改 start
            // else if (!campMap.isEmpty() && campMap.containsKey(RaTar.Campaign__c) && campMap.get(RaTar.Campaign__c).IF_Approved__c){
            //     if (String.isBlank(campMap.get(RaTar.Campaign__c).Meeting_Approved_No__c) 
            //         || String.isBlank(campMap.get(RaTar.Campaign__c).Meeting_Approved_No__r.MeetingApprovedNo__c)) {
            //         errorFlag = true;
            //         message6 = RaTar.Name + '、';
            //     }
            // }
            else if(RaTar.Campaign__c!= null &&  RaTar.Campaign__r.IF_Approved__c && RaTar.Campaign__r.Meeting_Approved_No__c == null) {
                errorFlag = true;
                message6 += RaTar.Name + '、';
            }
            else if(RaTar.Campaign__c!= null &&  RaTar.Campaign__r.IF_Approved__c && RaTar.Campaign__r.Meeting_Approved_No__c != null && statusList.contains(RaTar.Campaign__r.Approved_Status__c)) {
                errorFlag = true;
                message7 += RaTar.Name + '、';
            }
            // 20220315 ljh obpm备品决裁状态相关修改 end
            //20220217 sx add 备品借出申请-决裁控制 No.3 在出库时增加判断，判断学会是否申请决裁，如果是的话，再判断决裁编号是否不为空，满足条件才能出库，否则提示错误
        }
        if(errorFlag){
            if(String.isNotBlank(message0)){
                message += '单号NO.'+message0.removeEnd('、')+'学会已取消，不能继续操作了';
            }
            if(String.isNotBlank(message1)){
                message += '单号NO.'+message1.removeEnd('、')+'存在修理最终检测日，不能继续了';
            }
            if(String.isNotBlank(message2)){
                message += '单号NO.'+message2.removeEnd('、')+'未修理归还日不为空，不能出库';     
            }
            if(String.isNotBlank(message3)){
                message += '单号NO.'+message3.removeEnd('、')+'存在RC修理返送日，不能继续了';       
            }
            //1822 yc 20211025 已购待货目的，新品已有发货日不能出库 start
            if(String.isNotBlank(message4)){
                message += '单号NO.'+message4.removeEnd('、')+'已购待货目的，新品已有发货日，不能继续了';       
            }
            if(String.isNotBlank(message5)){
                message += '单号NO.'+message5.removeEnd('、')+'索赔QIS目的，QIS已有新品发货日，不能继续了';       
            }
            //1822 yc 20211025 已购待货目的，新品已有发货日不能出库 end
            if(String.isNotBlank(message6)){
                message += '单号No.'+ message6.removeEnd('、')+ '已申请决裁但决裁编码为空';
            }
            // 20220315 ljh obpm备品决裁状态相关修改 add start
            if(String.isNotBlank(message6)){
                message += '单号No.'+ message7.removeEnd('、')+ '已申请决裁但决裁编码状态不符合需求';
            }
            // 20220315 ljh obpm备品决裁状态相关修改 add end
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,message));
            return null;
        }
        //20210604 ljh update SFDC-C3LBNL end
        //检查是否可以继续
        String userid = Userinfo.getUserId();
        Set<Id> eSet = new Set<Id>();
        List<Rental_Apply_Equipment_Set_Detail__c> eList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        //申请书set
        Set<String> raSet = new Set<String>();
        for (EsdInfo esdInfo : esdList) {
            if (esdInfo.isChecked && !esdInfo.hasSended) {
                Rental_Apply_Equipment_Set_Detail__c esd = esdInfo.rec;
                //eList.add(esd);
                eSet.add(esd.Id);
                raSet.add(esd.Rental_Apply__c);
            }
        }
        if (eSet.size() == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未选择备品set，不能创建发货单'));
            return null;
        }
        eList = [select Rental_Apply__c, Rental_Apply__r.Shippment_ng_num__c, Rental_Apply__r.Pre_inspection_ng_num__c, Rental_Apply_Equipment_Set__r.Inspection_not_finish__c, Fixture_Name_F__c, Rental_Apply_Equipment_Set__r.Fixture_Set__r.Name, Rental_Apply_Equipment_Set__r.Rental_Apply__r.Name, Rental_Apply_Equipment_Set__r.Name, Pre_inspection_time__c, StockDown__c, StockDown_time__c, Id, Name, Asset__c, Asset__r.Name, Asset__r.SerialNumber, Asset__r.Product_Serial_No__c,
                           Asset__r.Remark__c, Asset__r.ImageAsset__c, Asset__r.ImageSerial__c, Asset__r.ImageAssetUploadedTime__c, Asset__r.ImageSerialUploadedTime__c,
                           Loaner_CDS_Info__c, Inspection_result__c, Check_lost_Item__c, Pre_disinfection__c, Water_leacage_check__c, Inspection_result_after__c, Arrival_in_wh__c,
                           Asset__r.Pre_Reserve_RAES_Detail__c, Asset__r.Pre_Reserve_RAES_Detail__r.After_Inspection_time__c,
                           Rental_Apply__r.Request_approval_time__c , Add_Request_approval_time__c ,ApplyToShipmentWorkTime__c, //20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 
                           Inspection_result_after_ng__c, Inspection_result_ng__c, Lost_item_giveup__c, CDS_complete__c, Loaner_accsessary__c,Key_product__c
                    from Rental_Apply_Equipment_Set_Detail__c where Id in :eSet for update];
        Boolean needSaveSet = false;
        Boolean needSaveDetail = false;
        Boolean needDeliverySlip = false;
        //wangweipeng   是否是重点产品       2021/08/30        start
        Map<String,boolean> keyPointProduct = new Map<String,boolean>();
        //wangweipeng   是否是重点产品       2021/08/30        end
        Set<Id> astForLock = new Set<Id>();
        Map<Datetime, List<Rental_Apply_Equipment_Set_Detail__c>> approvalMap = new Map<Datetime, List<Rental_Apply_Equipment_Set_Detail__c>>();// 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长
        for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
            if (esd.Inspection_result__c <> null && esd.StockDown__c == false) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '备品set未下架，不能填写发货前检查结果'));
                return null;
            }
            //wangweipeng   是否是重点产品       2021/08/30        start
            //记录当前借出备品的配套明细里面是否时重点产品，注意：只要有一个是重点产品，那么此借出备品就是重点产品
            if(esd.Key_product__c != null && esd.Key_product__c != ''){
                if(!(keyPointProduct.containsKey(esd.Rental_Apply__c)) || keyPointProduct.get(esd.Rental_Apply__c) == false){
                    keyPointProduct.put(esd.Rental_Apply__c,true);
                }
            }else{
                if(keyPointProduct.get(esd.Rental_Apply__c) == null){
                    keyPointProduct.put(esd.Rental_Apply__c,false);
                }
            }
            //wangweipeng   是否是重点产品       2021/08/30        end
            astForLock.add(esd.Asset__c);
            // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 start
            Datetime keyDt = esd.Add_Request_approval_time__c != null?esd.Add_Request_approval_time__c:esd.Rental_Apply__r.Request_approval_time__c;
            List<Rental_Apply_Equipment_Set_Detail__c> tempRaesdL;
            if(approvalMap.containsKey(keyDt)){
                tempRaesdL = approvalMap.get(keyDt);
            }else{
                tempRaesdL = new List<Rental_Apply_Equipment_Set_Detail__c>();
            }
            tempRaesdL.add(esd);                        
            approvalMap.put(keyDt,tempRaesdL);
            // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 end
        }
        List<Asset> astLock = [select Id
                 from Asset
                where id in :astForLock
                  for update];
        if (Step_status == '明细') {
            needDeliverySlip = true;
            //if (slip.Id == null) {
            //    system.debug('ID null');
            //    slip.Shippment_loaner_time__c = Datetime.now();
            //}
            if (slip.Id != null) {
                slip = [select Combine_Pack__c, Name, Id, DeliveryCompany_SlipNo__c,DeliveryType__c,Distributor_method__c,DeliveryCompany__c,Wh_Staff__c 
                        from FixtureDeliverySlip__c 
                        where Id =:slip.Id for update];
            }
            slip.Shippment_loaner_time__c = Datetime.now();
            needSaveDetail = true;
        }
        List<Rental_Apply__c> raList = [select Id, DeliverySlip__c, Campaign__c 
                                        , Campaign__r.IF_Approved__c         // 20220315 ljh obpm备品决裁状态相关修改
                                        , Campaign__r.Meeting_Approved_No__c // 20220315 ljh obpm备品决裁状态相关修改
                                        , Campaign__r.Approved_Status__c     // 20220315 ljh obpm备品决裁状态相关修改
                                        from Rental_Apply__c where Id in :raSet];
        Savepoint sp = Database.setSavepoint();
        try {
            //if (needSaveSet) ControllerUtil.upRAdEquipmentSet(es);
            if (needDeliverySlip) {
                FixtureUtil.withoutUpsertObjects(new List<FixtureDeliverySlip__c>{ slip });
                //ControllerUtil.updRADeliverySlipDetail(slip);
                // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 start
                map<String,Decimal> ApplyToShipmentMap = new map<String,Decimal>();
                if(approvalMap.size() > 0 ){
                    // dtList[0] 第一个就是最小时间
                    List<Datetime> dtList = new List<Datetime>(approvalMap.keySet());
                    Date startDateSOQL  = date.newinstance(dtList[0].year(), dtList[0].month(), dtList[0].day());
                    List<OlympusCalendar__c> ocList = [SELECT Id, Date__c,IsWorkDay__c 
                                     FROM OlympusCalendar__c
                                    WHERE Date__c >= :startDateSOQL
                                      AND Date__c <= :Date.today()
                                    ORDER BY Date__c ASC];

                    for(Datetime dt:dtList){
                        Boolean startFlag = false;
                        Boolean endFlag = false;
                        Datetime startTime = dt;
                        Date startDate = Date.newInstance(startTime.year(),startTime.month(),startTime.day());
                        Datetime endTime = Datetime.now();
                        Date endDate = Date.today();
                        // 审批时间是非奥林巴斯工作日  
                        if(ocList[0].IsWorkDay__c == 0){
                            for(OlympusCalendar__c oc:ocList){
                                if(oc.IsWorkDay__c == 1){
                                    startTime = oc.Date__c;
                                    startDate = oc.Date__c;
                                    startFlag = true;
                                    break;
                                }
                            }
                        }
                        // 发货时间是非奥林巴斯工作日
                        if(ocList[ocList.size() - 1].IsWorkDay__c == 0){
                            for(Integer i = ocList.size() - 1; i <= 0;i--){
                                if(ocList[i].IsWorkDay__c == 1){
                                    endTime = ocList[i].Date__c.addDays(1);
                                    endDate = ocList[i].Date__c.addDays(1);
                                    endFlag = true;
                                    break;
                                }
                            }
                        }
                        Decimal timeDifLast;
                        if(ocList[0].IsWorkDay__c == 0 && ocList[ocList.size() - 1].IsWorkDay__c == 0 && !startFlag && !endFlag){
                            timeDifLast = 0;
                        }else{
                            Long startL = startTime.getTime();
                            Long tendL = endTime.getTime();
                            Long timeDif = tendL - startL;                            
                            Decimal time11 = timeDif*1.00;
                            Decimal time12 = 24*3600*1000*1.00;
                            timeDifLast = time11/time12;                            
                            Integer tempWeek = 0;
                            for(OlympusCalendar__c oc:ocList){
                                if(oc.IsWorkDay__c == 0 && startDate < oc.Date__c && oc.Date__c < endDate){
                                    tempWeek++;
                                }
                            }
                            timeDifLast = timeDifLast - tempWeek;
                        }
                        // dtestLast 四舍五入 保留1位小数
                        for(Rental_Apply_Equipment_Set_Detail__c raesd00:approvalMap.get(dt)){
                            ApplyToShipmentMap.put(raesd00.Id,timeDifLast.setScale(1));
                        }
                    }
                }
                // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 end
                for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
                    esd.DeliverySlip__c = slip.Id;
                    // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 start
                    if(ApplyToShipmentMap.containsKey(esd.Id)){
                        esd.ApplyToShipmentWorkTime__c = ApplyToShipmentMap.get(esd.Id);
                    }
                    // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 end
                }

                for (Rental_Apply__c ra : raList) {
                    ra.DeliverySlip__c = slip.Id;
                    //wangweipeng   是否是重点产品       2021/08/30        start
                    ra.Is_keyPoint_Product__c = keyPointProduct.get(ra.Id);
                    //wangweipeng   是否是重点产品       2021/08/30        start

                    // 20220315 ljh obpm备品决裁状态相关修改 update start
                    //20220217 sx add 备品借出申请-决裁控制 No.4 出库成功时，把此时点的决裁编号和决裁状态写到决裁编号（出库）和决裁状态（出库）上
                    // if (!campMap.isEmpty() && campMap.containsKey(ra.Campaign__c) && campMap.get(ra.Campaign__c).IF_Approved__c){
                    //     ra.ApprovedNo_Delivery__c = campMap.get(ra.Campaign__c).Meeting_Approved_No__r.MeetingApprovedNo__c;
                    //     ra.Approved_State_Delivery__c = campMap.get(ra.Campaign__c).Meeting_Approved_No__r.ProcessState__c;
                    // }
                    if (ra.Campaign__c != null&& ra.Campaign__r.IF_Approved__c && ra.Campaign__r.Meeting_Approved_No__c != null){
                        ra.ApprovedNo_Delivery__c = ra.Campaign__r.Meeting_Approved_No__c;
                        ra.Approved_State_Delivery__c = ra.Campaign__r.Approved_Status__c;
                    }
                    // 20220315 ljh obpm备品决裁状态相关修改 update end
                }
            }
            //if (needSaveDetail) ControllerUtil.updRAEquipmentSetDetail(eList);
            if (needSaveDetail) {
                FixtureUtil.withoutUpsertObjects(eList);
                FixtureUtil.withoutUpsertObjects(raList);
            }

            //PageReference ref = new Pagereference('/apex/EquipmentSetShippmentReceived3?id=' + Id + '&step=' + this.Step_status);
            //ref.setRedirect(true);
            //return ref;
            done_flg = true;
            return null;
        } catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getDmlMessage(0)));
            Database.rollback(sp);
            done_flg = false;
            return null;
        }

        return null;
    }

    public class EsdInfo {
        public Rental_apply_equipment_Set_Detail__c rec { get; set; }
        public String imageAssetUploadedTime { get; set; }
        public String imageSerialUploadedTime { get; set; }
        // 回库はSet単位で、明細一つ一つのquickCheck要らない
        public boolean quickCheck { get; set; }
        public boolean isChecked { get; set; }
        public boolean hasSended { get; set; }

        public EsdInfo(Rental_apply_equipment_Set_Detail__c rec, boolean checked) {
            this.rec = rec;
            this.isChecked = checked;
            this.hasSended = false;

            if (rec.Asset__r.Pre_Reserve_RAES_Detail__c != null && rec.Asset__r.Pre_Reserve_RAES_Detail__r.After_Inspection_time__c != null) {
                this.quickCheck = Datetime.now() < rec.Asset__r.Pre_Reserve_RAES_Detail__r.After_Inspection_time__c + 30 ? true : false;
            } else {
                this.quickCheck = false;
            }

            if (rec.Asset__r.ImageAssetUploadedTime__c != null) {
                imageAssetUploadedTime = rec.Asset__r.ImageAssetUploadedTime__c.format('yyyy/MM/dd HH:mm');
            }
            if (rec.Asset__r.ImageSerialUploadedTime__c != null) {
                imageSerialUploadedTime = rec.Asset__r.ImageSerialUploadedTime__c.format('yyyy/MM/dd HH:mm');
            }
        }

        public EsdInfo(Rental_apply_equipment_Set_Detail__c rec) {
            this(rec, false);
        }
    }
}