// xudan 20160106 Arrival_wh_time__c -> Arrival_wh_time2__c（回库はSet単位なので、積み上げ項目使わず）
public without sharing class EquipmentSetShippmentReceived5Controller {
    public Rental_Apply_Equipment_Set__c es { get; set; }
    public String crossRegion {get;set;}
    private Map<String, String> roleRegionMap {get;set;}
    public List<EsdInfo> esdList { get; set; }
    public boolean done_flg {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 SR_status { get; private set; }
    public String Step_status { get; private set; }
    public Boolean needCDS { get; private set; }
    public String open_type { get; private set; }
    public String Raid {get;set;}
    private String Id;
    
    public Integer getEsdListSize() {
        return esdList.size();
    }
    
    public EquipmentSetShippmentReceived5Controller() {
//        Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        Id = ApexPages.currentPage().getParameters().get('id');
        if (SR_status == null) {
            SR_status = ApexPages.currentPage().getParameters().get('type');
        }
        if (Step_status == null) {
            Step_status = ApexPages.currentPage().getParameters().get('step');
        }
        if (open_type == null) {
            open_type = ApexPages.currentPage().getParameters().get('open');
        }
        roleRegionMap = new Map<String, String> {
            '备品中心北方管理成员' => '北京 备品中心',
            '备品中心华东管理成员' => '上海 备品中心',
            '备品中心南方管理成员' => '广州 备品中心'
        };
    }
    
    // 画面初始化
    public PageReference init() {
        done_flg = false;
        es = new Rental_Apply_Equipment_Set__c();
        esdList = new List<EsdInfo>();
        Set<Id> esIds = new Set<Id>();
        saveBtnDisabled = false;
        ReturnRefuse = true;
        ErrorMessage = '';
        crossRegion = '';
        if (Id != null) {
            List<String> ids = Id.split(',');
            // 当前User
            String userid = Userinfo.getUserId();
            User user = [select Id,Name,UserRole.Name from User where Id = :userid];
            // 备品set
            List<Rental_Apply_Equipment_Set__c> esList = [select Rental_Apply__c, Id, RAES_Status__c, Name, Shippment_loaner_time2__c
                                                               , Rental_Apply__r.Cross_Region_Assign__c
                                            from Rental_Apply_Equipment_Set__c
                                           where (Rental_Apply__r.Name in :ids or Id in :ids)
                                             //and Cancel_Select__c = False
                                             ];

            //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;
                    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 AssetName__c, SerialNumber_F__c, Repair_Status_F__c, OnStock_By_Cancel__c, Inspection_Comment__c,Inspection_result_after_Final__c, Inspection_result_after_NG_Final__c, Check_lost_Item_F__c,Rental_Apply_Equipment_Set__r.Fixture_Set__r.Name, Fixture_QRCode_F__c, 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.Name, Rental_Apply__r.Hospital__c, Rental_Apply__r.Hospital__r.Name,
                       Rental_Apply__r.Person_In_Charge__c, Rental_Apply__r.Person_In_Charge__r.Name, Rental_Apply__r.demo_purpose2__c, Rental_Apply__r.WorkPlace__c, Rental_Apply__r.OCM_dept_category__c, Fixture_Model_No__c,
                       Inspection_result_after_ng__c, Inspection_result_ng__c, Lost_item_giveup__c, CDS_complete__c, Loaner_accsessary__c, Inspection_NG_abord_reason__c, Is_Body__c
                  from Rental_Apply_Equipment_Set_Detail__c
                 where Rental_Apply_Equipment_Set__c in :esIds
                   and ((Shipment_request_time2__c <> null and Cancel_Select__c = False ) or Repair_Status_F__c = '修理完毕')
                 order by Rental_Apply_Equipment_Set__r.Name, Rental_Apply_Equipment_Set__c, Name
        ];

        for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
            EsdInfo ei = new EsdInfo(esd);
            if ((esd.Check_lost_Item_F__c == 'OK' || esd.Repair_Status_F__c == '修理完毕')
                    && !esd.Arrival_in_wh__c) {
                ei.editable = true;
            }
            esdList.add(ei);
        }

        if (esdList.size() <= 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有备品set明细'));
            saveBtnDisabled = true;
            return null;
        }
        Step_status = '回收后检测';
        SR_status = 'Shippment';
        system.debug('=====' + Step_status);
        system.debug('=====' + open_type);

        return null;
    }

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

    // Step 切り替えボタン、发货-发货运输单号 等
    public PageReference Shippment2() {
        Step_status = '发货';
        return new PageReference('/apex/EquipmentSetShippmentReceived6?id=' + this.Id);
    }

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

        String userid = Userinfo.getUserId();
        List<Rental_Apply_Equipment_Set_Detail__c> eList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        for (EsdInfo esdInfo : esdList) {
            Rental_Apply_Equipment_Set_Detail__c esd = esdInfo.rec;
            if (esdInfo.editable) {
                eList.add(esd);
            }
        }
        Boolean needSaveSet = false;
        Boolean needSaveDetail = false;
        
        
        // TODO 没变化不存
        if (Step_status == '回收后检测') {
            
            for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
                if (String.isNotBlank(esd.Inspection_result_after_Final__c)) {
                    //esd.After_Inspection_time_Final__c = System.now();
                    //esd.Inspection_staff_After_Final__c = userid;
                } else {
                    esd.After_Inspection_time_Final__c = null;
                    esd.Inspection_staff_After_Final__c = null;
                    if (String.isNotBlank(esd.Inspection_result_after__c)) {
                        //esd.After_Inspection_time__c = System.now();
                        //esd.Inspection_staff_After__c = userid;
                    } else {
                        esd.After_Inspection_time__c = null;
                        esd.Inspection_staff_After__c = null;
                    }
                }
            }
            needSaveDetail = true;
        }
        
        Savepoint sp = Database.setSavepoint();
        try {
            //if (needSaveSet) ControllerUtil.upRAdEquipmentSet(es);
            //if (needSaveDetail) ControllerUtil.updRAEquipmentSetDetail(eList);
            if (needSaveDetail) FixtureUtil.withoutUpsertObjects(eList);
            
            //PageReference ref = new Pagereference('/apex/EquipmentSetShippmentReceived5?id=' + Id + '&type=' + SR_status + '&step=' + this.Step_status + '&open=' + this.open_type);
            //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)));
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getDmlMessage(0)+'( '+Step_status+' )'));
            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 editable { get; set; }
        // 备品借出申请故障报告 按钮显示逻辑
        public boolean showFaultRepor { get; set;}
        public String faultReportFlag { get; set;}
        public String personInChargeId { get; set;}
        public String personInChargeName { get; set;}
        public String demoPurpose2 { get; set;}
        public String raName { get; set;}
        public String hospitalId { get; set;}
        public String hospitalName { get; set;}
        public String workPlace { get; set;}
        public String deptCategory { get; set;}

        public EsdInfo(Rental_apply_equipment_Set_Detail__c rec) {
            this.rec = rec;
            this.editable = 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');
            }
            //当明细 设备为主体 且 NG时 显示按钮
            if (rec.Is_Body__c == true && rec.Inspection_result_after__c == 'NG'){
                showFaultRepor = true;
            }

            List<Rental_Apply_Fault__c> rafList = [SELECT Id ,status__c ,Rental_Apply_Equipment_Set_Detail__c from Rental_Apply_Fault__c where Rental_Apply_Equipment_Set_Detail__c = :rec.Id Order By CreatedDate DESC LIMIT 1];
            
            
            if( rafList != null && rafList.size() > 0 ){         
                this.faultReportFlag = rafList[0].Id;    
            }else {
                this.faultReportFlag = '不存在故障报告单';
            }

            personInChargeId = rec.Rental_Apply__r.Person_In_Charge__c;
            personInChargeName = rec.Rental_Apply__r.Person_In_Charge__r.Name;
            demoPurpose2 = rec.Rental_Apply__r.demo_purpose2__c;
            raName = rec.Rental_Apply__r.Name;
            hospitalId = rec.Rental_Apply__r.Hospital__c;
            hospitalName = rec.Rental_Apply__r.Hospital__r.Name;
            workPlace = rec.Rental_Apply__r.WorkPlace__c;
            deptCategory = rec.Rental_Apply__r.OCM_dept_category__c;
        }
    }
}