// xudan 20160106 Arrival_wh_time__c -> Arrival_wh_time2__c（回库はSet単位なので、積み上げ項目使わず）
// EquipmentSetShippmentReceived4CtrlTest
public without sharing class EquipmentSetShippmentReceived4Controller {
    public FixtureDeliverySlip__c slip { get; set; }
    public Rental_Apply_Equipment_Set__c es { get; set; }
    public List<EsdInfo> esdList { get; set; }
    //public List<EsInfo> raesList { get; set; }
    public String crossRegion {get;set;}
    private Map<String, String> roleRegionMap {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 boolean done_flg {get;set;}
    public String Step_status { get; private set; }
    public Boolean needCDS { get; private set; }
    public Boolean showTab2 { get; private set; }
    public Boolean isEquipmentCenter { get; private set; }
    public String Raid {get;set;}
    public String ApplyId {get;set;}
    public String CheckedId {get;set;}
    public String UnCheckedId {get;set;}
    public String CheckedSetId {get;set;}
    public String BPRegion {get;set;} //备品中心地址
    public Boolean isSameCity {get;set;}
    private String Id;

    public boolean isMainReceivedSignRich {get;set;}//当前借出备品是否上传签收单  true为没有上传
    public boolean isAdvocateFollow{get;set;}
    public String skipId{get;set;}
    private static final Map<String,Schema.RecordTypeInfo>  DEVELOPERNAMEMAP  = Schema.SObjectType.Rental_Apply__c.getRecordTypeInfosByDeveloperName();


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

    public EquipmentSetShippmentReceived4Controller() {
//        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;
        BPRegion = '';
        isSameCity = false;
        roleRegionMap = new Map<String, String> {
            '备品中心北方管理成员' => '北京 备品中心',
            '备品中心华东管理成员' => '上海 备品中心',
            '备品中心南方管理成员' => '广州 备品中心'
        };

        isMainReceivedSignRich = false;
        isAdvocateFollow = false;
        skipId = '';
    }

    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 Id, Name, 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 Lost_item_Memo_Final__c, Lost_item_Memo__c, Rental_Apply_Equipment_Set__r.Wei_loaner_arranged__c, Rental_Apply__r.Asset_return_ng_num__c, Rental_Apply_Equipment_Set__r.Final_reply_day__c, NoItemReturn__c, SerialNumber_F__c, Asset_return_time__c, Check_lost_Item_F__c, Rental_Apply_Equipment_Set__r.Received_ng_detail__c, Rental_Apply_Equipment_Set__r.Wei_Return_Finish__c, Rental_Apply_Equipment_Set__r.Received_Confirm__c, Check_lost_Item_Final__c, Return_DeliverySlip__c, Fixture_Name_F__c, Rental_Apply_Equipment_Set__r.Fixture_Set__r.Name, Rental_Apply_Equipment_Set__c, Fixture_QRCode_F__c, 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, Is_Body__c, CDSChargement__c, CDSType__c,
                           Inspection_result_after_ng__c, Inspection_result_ng__c, Lost_item_giveup__c, Confirm_Lost_Date__c, CDS_complete__c, Loaner_accsessary__c
                      from Rental_Apply_Equipment_Set_Detail__c
                     where (Return_DeliverySlip__c = :slip.Id or Id in :esdIdMap.keySet()) 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();
            Set<Id> sendedId = new Set<Id>();
            for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
                EsdInfo esdinfo;
                if (esdIdMap.containsKey(esd.Id)) {
                    //esdinfo = new EsdInfo(esd, esdIdMap.get(esd.Id));
                    esdinfo = new EsdInfo(esd, true);
                } else {
                    esdinfo = new EsdInfo(esd, true);
                    esdInfo.hasSended = true;
                    //sendedId.add(esd.Rental_Apply_Equipment_Set__c);
                }
                if (String.isBlank(esd.Inspection_result_after__c)
                    && String.isNotBlank(esd.Rental_Apply_Equipment_Set__r.Received_Confirm__c)
                    && esd.Asset_return_time__c != null
                    && esd.Arrival_in_wh__c != true) esdinfo.editable = true;
                esdList.add(esdInfo);
            }

            //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_time__c
            //                            from Rental_Apply_Equipment_Set__c
            //                            where Id in (select Rental_Apply_Equipment_Set__c from Rental_Apply_Equipment_Set_Detail__c where Return_DeliverySlip__c = :slip.Id or Id in :esdIdMap.keySet())
            //                            AND Cancel_Select__c = false
            //                            order by Rental_Apply__r.Name, Id];

            //raesList.clear();
            //for (Rental_Apply_Equipment_Set__c raes : esList) {
            //    EsInfo esinfo = new EsInfo(raes, sendedId.contains(raes.Id));
            //    raesList.add(esinfo);
            //}
        }
        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];
        Map<Id, Rental_Apply_Equipment_Set__c> esMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
        Set<Id> esdIds = new Set<Id>();
        for (Rental_Apply_Equipment_Set__c raes : esList) {
            esMap.put(raes.Id, raes);
        }
        for (EsdInfo raesd : esdList) {
            esdIds.add(raesd.rec.Id);
        }
        List<Rental_Apply_Equipment_Set_Detail__c> eList = [
                select Lost_item_Memo_Final__c, Lost_item_Memo__c, Rental_Apply_Equipment_Set__r.Wei_loaner_arranged__c, Rental_Apply__r.Asset_return_ng_num__c, Rental_Apply_Equipment_Set__r.Final_reply_day__c, NoItemReturn__c, SerialNumber_F__c, Asset_return_time__c, Check_lost_Item_F__c, Rental_Apply_Equipment_Set__r.Received_ng_detail__c, Rental_Apply_Equipment_Set__r.Wei_Return_Finish__c, Rental_Apply_Equipment_Set__r.Received_Confirm__c, Check_lost_Item_Final__c, Return_DeliverySlip__c, Fixture_Name_F__c, Rental_Apply_Equipment_Set__r.Fixture_Set__r.Name, Rental_Apply_Equipment_Set__c, Fixture_QRCode_F__c,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, Is_Body__c, CDSChargement__c, CDSType__c,
                       Inspection_result_after_ng__c, Inspection_result_ng__c, Lost_item_giveup__c, Confirm_Lost_Date__c, CDS_complete__c, Loaner_accsessary__c
                  from Rental_Apply_Equipment_Set_Detail__c
                 where Rental_Apply_Equipment_Set__c in :esMap.keySet() and DeliverySlip__c <> null and Shipment_request_time2__c <> null //and Rental_Apply_Equipment_Set__r.Received_Confirm__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();
        Set<Id> newEsIds = new Set<Id>();

        for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
            //boolean checked = checkedIds.contains(esd.Id);
            if (!esdIds.contains(esd.Id)) {
                EsdInfo ei = new EsdInfo(esd, showTab2);
                //EsdInfo ei = new EsdInfo(esd, true);
                if (String.isBlank(esd.Inspection_result_after__c)
                    && String.isNotBlank(esd.Rental_Apply_Equipment_Set__r.Received_Confirm__c)
                    && esd.Asset_return_time__c != null
                    && esd.Arrival_in_wh__c != true) ei.editable = true;
                esdList.add(ei);
                //newEsIds.add(esd.Rental_Apply_Equipment_Set__c);
            }
        }
        //for (String esId : newEsIds) {
        //    raesList.add(new EsInfo(esMap.get(esId)));
        //}
        //for (EsdInfo raesd : esdList) {
        //    if (checkedIds.contains(raesd.rec.Id)) {
        //        raesd.isChecked = true;
        //    }
        //}
        return null;
    }

    // 画面初始化
    public PageReference init() {
        done_flg = false;
        showTab2 = (Userinfo.getProfileId() == Label.ProfileId_EquipmentCenter || Label.ProfileId_EquCenCheckAndDepot.contains(Userinfo.getProfileId()) || Label.ProfileId_EquCenAdmin.contains(Userinfo.getProfileId()) || Userinfo.getProfileId() == Label.ProfileId_SystemAdmin);
        //showTab2 = false;
        isEquipmentCenter = (Userinfo.getProfileId() == Label.ProfileId_EquipmentCenter || Userinfo.getProfileId() == Label.ProfileId_SystemAdmin);
        //isEquipmentCenter=false;
        es = new Rental_Apply_Equipment_Set__c();
        slip = new FixtureDeliverySlip__c();
        esdList = new List<EsdInfo>();
        //raesList = new List<EsInfo>();
        Map<Id, Rental_Apply_Equipment_Set__c> esMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
        saveBtnDisabled = false;
        ReturnRefuse = true;
        ErrorMessage = '';
        crossRegion = '';
        if (Id != null) {
            system.debug('==================='+Id);
            List<String> ids = Id.split(',');
            // 当前User
            String userid = Userinfo.getUserId();
            User user = [select Id,Name,UserRole.Name,OCM_man_province_Rental__c from User where Id = :userid];
            List<Rental_Apply_Equipment_Set__c> esList;
            esList = [select Rental_Apply__r.Loaner_centre_mail_address__c
                           , 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
                           //wangweipeng     2021/09/01   SFDC-C4H4BM    start
                           , Rental_Apply__r.RecordType.Name
                           , Rental_Apply__r.RecordType.Id
                           , Rental_Apply__r.HP_received_sign_rich__c
                           , Rental_Apply__r.Split_Apply_Reason__c
                           , Rental_Apply__r.Root_Rental_Apply__c
                           //wangweipeng     2021/09/01   SFDC-C4H4BM    end
                           , Name
                           , Shippment_loaner_time2__c
                           , Rental_Apply__r.Cross_Region_Assign__c
                           , Rental_Apply__r.ToAgency__c
                           , Rental_Apply__r.OwnerId
                        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 == '追加') {
            //    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_time__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];
            //} 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) {
                String ra_RecordTypeId = DEVELOPERNAMEMAP.get('AgencyRequest').getRecordTypeId();//获取记录类型
                ra_RecordTypeId = ra_RecordTypeId.substring(0,15);

                List<User> owners = [SELECT OCM_man_province_Rental__c FROM User WHERE Id=:esList[0].Rental_Apply__r.OwnerId LIMIT 1];
                if(owners.isEmpty()) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '申请者不存在！'));
                    return null;
                }
                else {
                    isSameCity = owners[0].OCM_man_province_Rental__c == esList[0].Rental_Apply__r.ToAgency__c;
                }

                boolean flag = false;
                for (Rental_Apply_Equipment_Set__c raes : esList) {

                    //wangweipeng     2021/09/09   SFDC-C4H4BM    start
                    //判断 备品签收单上传记录  是否为空
                    if(String.isBlank(raes.Rental_Apply__r.HP_received_sign_rich__c)){
                        String recordTypeId = raes.Rental_Apply__r.RecordType.Id;
                        recordTypeId = recordTypeId.substring(0,15);
                        //判断记录类型是否为办事处，如果不是办事处证明当前借出备品单位主单，那么如果前端点击取消按钮时，跳转的id为当前借出备品单id
                        if(!flag && ra_RecordTypeId != recordTypeId){
                            isAdvocateFollow = true;//提示信息区别
                            skipId = raes.Rental_Apply__c;
                            flag = true;
                        }

                        if(!flag && ra_RecordTypeId == recordTypeId){//如果记录类型为办事处，当前单位从单，并且源申请单不为空，那么的跳转的id为从单的主单id，为空就跳转到当前借出备品单
                            if(String.isNotBlank(raes.Rental_Apply__r.Root_Rental_Apply__c)){
                                skipId = raes.Rental_Apply__r.Root_Rental_Apply__c;
                                flag = true;
                            }else{
                                isAdvocateFollow = true;
                                skipId = raes.Rental_Apply__c;
                                flag = true;
                            }
                        }
                        if(!isMainReceivedSignRich){
                            isMainReceivedSignRich = true;//主单是否没有上传签收单，true 为没有上传
                        }
                    }
                    //wangweipeng     2021/09/09   SFDC-C4H4BM    end
                    
                    esMap.put(raes.Id, raes);
                    Raid = raes.Rental_Apply__c;
                    // 跨区域分配
                    if (BPRegion == '') {
                        if(String.isNotBlank(raes.Rental_Apply__r.ToAgency__c)) {
                            BPRegion = raes.Rental_Apply__r.ToAgency__c;
                        }
                        else if (String.isNotBlank(raes.Rental_Apply__r.Loaner_centre_mail_address__c)) {
                            String mail = raes.Rental_Apply__r.Loaner_centre_mail_address__c;
                            if (mail == 'OCM_Asset@olympus.com.cn') {
                                BPRegion = '北京 备品中心';
                            } else if (mail == 'OCM_AssetSH@olympus.com.cn') {
                                BPRegion = '上海 备品中心';
                            } else if (mail == 'OCM_AssetGZ@olympus.com.cn') {
                                BPRegion = '广州 备品中心';
                            }
                        }
                    }
                    if(String.isNotBlank(raes.Rental_Apply__r.Cross_Region_Assign__c)){
                        crossRegion = raes.Rental_Apply__r.Cross_Region_Assign__c;
                        if(roleRegionMap.containsKey(user.UserRole.Name)
                            && roleRegionMap.get(user.UserRole.Name) == raes.Rental_Apply__r.Cross_Region_Assign__c) {
                                crossRegion = '';
                        }
                    }
                }
            } 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 Lost_item_Memo_Final__c, Lost_item_Memo__c, Rental_Apply_Equipment_Set__r.Wei_loaner_arranged__c, Rental_Apply__r.Asset_return_ng_num__c, Rental_Apply_Equipment_Set__r.Final_reply_day__c, NoItemReturn__c, SerialNumber_F__c, Asset_return_time__c, Check_lost_Item_F__c, Rental_Apply_Equipment_Set__r.Received_ng_detail__c, Rental_Apply_Equipment_Set__r.Wei_Return_Finish__c, Rental_Apply_Equipment_Set__r.Received_Confirm__c, Check_lost_Item_Final__c, Return_DeliverySlip__c, Fixture_Name_F__c, Rental_Apply_Equipment_Set__r.Fixture_Set__r.Name, Rental_Apply_Equipment_Set__c, Fixture_QRCode_F__c, Loaner_asset_no__c, 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, Is_Body__c, CDSChargement__c, CDSType__c,
                       Inspection_result_after_ng__c, Inspection_result_ng__c, Lost_item_giveup__c, Confirm_Lost_Date__c, CDS_complete__c, Loaner_accsessary__c
                  from Rental_Apply_Equipment_Set_Detail__c
                 where Rental_Apply_Equipment_Set__c in :esMap.keySet() and DeliverySlip__c <> null and Shipment_request_time2__c <> null //and Rental_Apply_Equipment_Set__r.Received_Confirm__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
        ];
        system.debug(eList);

        needCDS = false;
        String raesId = '';
        for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
            EsdInfo ei = new EsdInfo(esd, showTab2);
            if (String.isBlank(esd.Inspection_result_after__c)
                && String.isNotBlank(esd.Rental_Apply_Equipment_Set__r.Received_Confirm__c)
                && esd.Asset_return_time__c != null
                && esd.Arrival_in_wh__c != true) ei.editable = true;
            esdList.add(ei);
            //if (raesId != (String)esd.Rental_Apply_Equipment_Set__c) {
            //    EsInfo es = new EsInfo(esMap.get((String)esd.Rental_Apply_Equipment_Set__c));
            //    raesList.add(es);
            //    raesId = esd.Rental_Apply_Equipment_Set__c;
            //}
        }

        //and Check_lost_Item__c = null and Return_DeliverySlip__c = null
        if (showTab2) {
            if (String.isBlank(Step_status)) {
                Step_status = '明细';
            }
        } else {
            if (String.isBlank(Step_status)) {
                Step_status = '追加';
            }
        }

        //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;
    }

    //wangweipeng     2021/09/09   SFDC-C4H4BM    start
    //重定向到
    public PageReference redirectPag(){
        PageReference ref = new Pagereference('/' + skipId);
        ref.setRedirect(true);
        return ref;
    }
    //wangweipeng     2021/09/09   SFDC-C4H4BM    end


    //// 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 ShippmentDetailAdd() {
        if (showTab2) Step_status = '明细';
        Id uid = Userinfo.getUserId();
     //   slip.Wh_Staff__c = uid;
        //slip.DeliveryType__c = '回寄';
        Set<String> esIds = new Set<String>(CheckedSetId.split(':'));
        List<Rental_Apply_Equipment_Set_Detail__c> eList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        List<Rental_Apply_Equipment_Set_Detail__c> eList_dummy = new List<Rental_Apply_Equipment_Set_Detail__c>();
        //List<Rental_Apply_Equipment_Set_Detail__c> eList2 = new List<Rental_Apply_Equipment_Set_Detail__c>();

        //if (!String.isBlank(CheckedId)) {
        //  Set<String> checkedIds = new Set<String>(CheckedId.split(':'));
        //  for (EsdInfo esd : esdList) {
        //      boolean checked = checkedIds.contains(esd.rec.Id);
        //      esd.isChecked = checked;
        //      if (checked) {
        //          if (String.isNotBlank(esd.rec.Check_lost_Item__c)) {
        //              esd.rec.Lost_item_check_time__c = Datetime.now();
        //              esd.rec.Lost_item_check_staff__c = uid;
        //          }
        //          if (esd.rec.Check_lost_Item__c == '欠品') {
        //              esd.rec.Return_DeliverySlip__c = null;
        //          }
        //          if (esd.rec.CDS_complete__c) {
        //              esd.rec.CDS_complete_time__c = Datetime.now();
        //              esd.rec.CDS_staff__c = uid;
        //          }
        //          eList.add(esd.rec);
        //      }
        //    }
        //}
        if (slip.Id == null) {
            slip.Shippment_loaner_time__c = Datetime.now();
        }
        boolean needDeliverySlip = false;
        boolean needDummyDeliverySlip = false;
        Set<String> dummyNo = new Set<String>();
        for (EsdInfo esd : esdList) {
            //if (esd.rec.Check_lost_Item__c == '欠品') {
            //  esd.rec.Return_DeliverySlip__c = null;
            //  esd.rec.Lost_item_check_time__c = Datetime.now();
            //  esd.rec.Lost_item_check_staff__c = uid;
            //  eList.add(esd.rec);
            //} else if (esd.rec.Check_lost_Item__c == 'Add') {
            //  esd.rec.Check_lost_Item__c = null;
            //  esd.isChecked = true;
            //  eList.add(esd.rec);
            //}
            if (esIds.contains(esd.rec.Id)) {
                //esd.isChecked = true;
                if (esd.rec.Confirm_Lost_Date__c <> null) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '有确认遗失的保有设备不能回寄。'));
                    Step_status = '追加';
                    done_flg = false;
                    return null;
                }
                if (String.isBlank(esd.rec.Return_DeliverySlip__c) && !esd.rec.Lost_item_giveup__c && esd.rec.Check_lost_Item_F__c != '消耗') {
                    needDeliverySlip = true;
                    eList.add(esd.rec);
                }
            }
            if (esd.rec.NoItemReturn__c == true && String.isBlank(esd.rec.Return_DeliverySlip__c) && esd.rec.Check_lost_Item_F__c != '消耗' && !esd.rec.Lost_item_giveup__c) {
                needDummyDeliverySlip = true;
                eList_dummy.add(esd.rec);
                dummyNo.add(esd.rec.Rental_Apply_Equipment_Set__r.Rental_Apply__r.Name + '_Dummy');
            }
        }
        //UnCheckedId = null;
        Map<String, FixtureDeliverySlip__c> slip_dummy = new Map<String, FixtureDeliverySlip__c>();
        if (needDummyDeliverySlip) {
            List<FixtureDeliverySlip__c> slipDs = [select Id, Name, DeliveryCompany_SlipNo__c,DeliveryType__c,Distributor_method__c,DeliveryCompany__c,Wh_Staff__c
                                                    from FixtureDeliverySlip__c
                                                    where Name in :dummyNo and DeliveryType__c = '回寄'];
            if (slipDs.size() > 0) {
                for (FixtureDeliverySlip__c dummy_slip : slipDs) {
                    slip_dummy.put(dummy_slip.Name, dummy_slip);
                    dummyNo.remove(dummy_slip.Name);
                }
            }
            if (dummyNo.size() > 0) {
                for (String dummy_name : dummyNo) {
                    FixtureDeliverySlip__c dummy_slip = new FixtureDeliverySlip__c();
                    dummy_slip.Name = dummy_name;
                    dummy_slip.DeliveryType__c = slip.DeliveryType__c;
                    dummy_slip.Distributor_method__c = slip.Distributor_method__c;
                    dummy_slip.DeliveryCompany__c = slip.DeliveryCompany__c;
                    dummy_slip.Wh_Staff__c = slip.Wh_Staff__c;
                    slip_dummy.put(dummy_name, dummy_slip);
                }

            }
        }

        Savepoint sp = Database.setSavepoint();
        try {
            Datetime now = System.now();
            if (needDeliverySlip) {
                //ControllerUtil.updRADeliverySlipDetail(slip);
                FixtureUtil.withoutUpsertObjects(new List<FixtureDeliverySlip__c>{ slip });
                for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
                    esd.Return_DeliverySlip__c = slip.Id;
                    esd.Asset_return_time__c = now;
                }
                //ControllerUtil.updRAEquipmentSetDetail(eList);
                if (!needDummyDeliverySlip) FixtureUtil.withoutUpsertObjects(eList);
            }

            if (needDummyDeliverySlip) {
                FixtureUtil.withoutUpsertObjects(slip_dummy.values());
                for (Rental_Apply_Equipment_Set_Detail__c esd : eList_dummy) {
                    FixtureDeliverySlip__c newslip = slip_dummy.get(esd.Rental_Apply_Equipment_Set__r.Rental_Apply__r.Name + '_Dummy');
                    esd.Return_DeliverySlip__c = newslip.Id;
                    esd.Asset_return_time__c = System.now();
                }
                if (!needDeliverySlip) {
                    FixtureUtil.withoutUpsertObjects(eList_dummy);
                } else {
                    eList.addAll(eList_dummy);
                    FixtureUtil.withoutUpsertObjects(eList);
                }
            }

            searchSlip();
            // 20230722 ljh
            // if (!showTab2) {
            //     done_flg = true;
            // } else {
            //     done_flg = false;
            // }
            done_flg = true;
            // 20230722 ljh 
        } catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            String msg = ex.getMessage();
            if (msg != null && msg.contains('DUPLICATE_VALUE') && msg.contains('DeliveryCompany_SlipNo__c')) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '系统已存在相同的运输单。如果继续使用该运输单回寄，请输入运输单号检索，检索后再勾选配套回寄。'));
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()+'( '+Step_status+' )'));
            }
            Database.rollback(sp);
            Step_status = '追加';
            done_flg = false;
            return 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 ShippmentDetail() {
        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() {
        Rental_Apply_Equipment_Set_Detail__c updDetail = null;
        for (EsdInfo esd : esdList) {
            if (esd.rec.Id == UnCheckedId) {
                if (esd.hasSended) {
                    esd.rec.Return_DeliverySlip__c = null;
                    esd.rec.Asset_return_time__c = null;
                    updDetail = esd.rec;
                } else {
                    esd.isChecked = false;
                }
            }
        }
        UnCheckedId = null;
        if (updDetail != null) {
            Savepoint sp = Database.setSavepoint();
            try {
                update updDetail;
                searchSlip();
            } catch (Exception ex) {
                system.debug('=====' + ex.getMessage());
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()+'( '+Step_status+' )'));
                Database.rollback(sp);
                return null;
            }
        }
        system.debug('========3esdList='+JSON.serialize(esdList));
        return null;
    }

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

        //检查是否可以继续
        String userid = Userinfo.getUserId();
        List<Rental_Apply_Equipment_Set_Detail__c> eList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        Set<String> assetIdForLockSet = new Set<String>();
        for (EsdInfo esdInfo : esdList) {
            if (esdInfo.isChecked && esdInfo.editable) {
                Rental_Apply_Equipment_Set_Detail__c esd = esdInfo.rec;

                if (String.isNotBlank(esd.Check_lost_Item_Final__c)) {
                    //esd.Lost_item_check_staff_Final__c = userid;
                    //esd.Lost_item_check_time_Final__c = system.now();
                    if (esd.Check_lost_Item_Final__c == '欠品' || esd.Check_lost_Item_Final__c == '消耗' ) {
                        esd.Return_DeliverySlip__c = null;
                        esd.CDS_complete__c = false;
                        if (esd.Check_lost_Item_Final__c == '欠品') esd.NoItemReturn__c = false;
                        //esd.Asset_return_time__c = null;
                    }
                } else {
                    esd.Lost_item_check_staff_Final__c = null;
                    esd.Lost_item_check_time_Final__c = null;
                    if (esd.Check_lost_Item__c == '欠品' || esd.Check_lost_Item__c == '消耗' ) {
                        esd.Return_DeliverySlip__c = null;
                        esd.CDS_complete__c = false;
                        if (esd.Check_lost_Item__c == '欠品') esd.NoItemReturn__c = false;
                        //esd.Asset_return_time__c = null;
                    }
                    if (String.isNotBlank(esd.Check_lost_Item__c)) {
                        // OCM_OLY-435対応
                        //esd.Lost_item_check_staff__c = userid;
                        //esd.Lost_item_check_time__c = system.now();
                    } else {
                        esd.Lost_item_check_staff__c = null;
                        esd.Lost_item_check_time__c = null;
                    }
                }

                if (esd.Lost_item_giveup__c && esd.Check_lost_Item__c == null) {
                    esd.Check_lost_Item__c = '欠品';
                    esd.Return_DeliverySlip__c = null;
                }

                if (esd.CDS_complete__c) {
                    // OCM_OLY-435対応
                    //esd.CDS_complete_time__c = system.now();
                    //esd.CDS_staff__c = userid;
                } else {
                    esd.CDS_complete_time__c = null;
                    esd.CDS_staff__c = null;
                }
                eList.add(esd);
                assetIdForLockSet.add(esd.Asset__c);
            }
        }
        Boolean needSaveSet = false;
        Boolean needSaveDetail = false;
        Boolean needDeliverySlip = false;

        //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;
        //    }
        //}
        if (Step_status == '明细') {
            needSaveDetail = true;
        }
        List<Asset> assetIdForLockList = [SELECT  Id
                 FROM Asset
                WHERE Id = :assetIdForLockSet
                AND Asset_loaner_category__c != '耗材'
                AND RecordTypeId = '01210000000kOPR'
                FOR UPDATE];
        Savepoint sp = Database.setSavepoint();
        try {
            //if (needSaveDetail) ControllerUtil.updRAEquipmentSetDetail(eList);
            if (needSaveDetail) FixtureUtil.withoutUpsertObjects(eList);

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

        //return null;
    }

    //public class EsInfo {
    //     public Rental_apply_equipment_Set__c rec { get; set; }
    //     public boolean isChecked { get; set; }

    //     public EsInfo(Rental_apply_equipment_Set__c rec, boolean checked) {
    //        this.rec = rec;
    //        this.isChecked = checked;
    //     }

    //     public EsInfo(Rental_apply_equipment_Set__c rec) {
    //        this(rec, false);
    //    }
    //}

    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 boolean editable { get; set; }
        public boolean overtime { get; set; }
        public boolean showRaesCheck {get;set;}

        public EsdInfo(Rental_apply_equipment_Set_Detail__c rec, boolean checked) {
            this.rec = rec;
            this.isChecked = checked;
            this.hasSended = false;
            this.editable = false;
            this.overtime = false;
            this.showRaesCheck = rec.Rental_Apply_Equipment_Set__r.Wei_Return_Finish__c > 0 && rec.Rental_Apply_Equipment_Set__r.Received_Confirm__c != null && rec.Rental_Apply_Equipment_Set__r.Wei_loaner_arranged__c == 0;

            if (rec.Rental_Apply__r.Asset_return_ng_num__c > 0 && rec.Rental_Apply_Equipment_Set__r.Received_Confirm__c != 'NG' && rec.Rental_Apply_Equipment_Set__r.Final_reply_day__c < system.today()) {
                this.overtime = true;
            }

            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);
        }
    }
}