public without sharing class TransferShippmentReceived5Controller {
    public List<EsdInfo> esdList { get; set; }
    public boolean done_flg {get;set;}
    public Boolean saveBtnDisabled { get; private set; }
    public String SR_status { get; private set; }
    public String Step_status { get; private set; }
    public String open_type { get; private set; }
    private Boolean isStartUser; // 是否是调拨前地区的用户
    private Boolean isDestUser; // 是否是调拨后地区的用户
    private Boolean is2B3; // 是否是2B3_照片
    private String Id;

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

    public TransferShippmentReceived5Controller() {
        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');
        }
    }
    /**
    @description 用户角色与地区地否匹配
    @param roleName 角色Name
    @param center 备品中心
    */
    private Boolean isMatch(String roleName, String center) {
        switch on center {
            when '北京 备品中心' {
                return roleName == '备品中心北方管理成员';
            }
            when '上海 备品中心' {
                return roleName == '备品中心华东管理成员';
            }
            when '广州 备品中心' {
                return roleName == '备品中心南方管理成员';
            }
        }
        return false;
    }
    // 画面初始化
    public PageReference init() {
        done_flg = false;
        esdList = new List<EsdInfo>();
        Set<Id> esIds = new Set<Id>();
        saveBtnDisabled = false;
        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<TransferApplySummary__c> esList = [select TransferApply__c, Id, TAS_Status__c, Name, Shippment_loaner_time2__c
                                                        , TransferApply__r.From_Location__c, TransferApply__r.Destination_location__c
                                            from TransferApplySummary__c
                                           where (TransferApply__r.Name in :ids or Id in :ids)
                                             //and Cancel_Select__c = False 取消的需要重新上架，所以要检索出来
                                             ];

            if (esList.size() > 0) {
                for (TransferApplySummary__c raes : esList) {
                    esIds.add(raes.Id);
                }
                User user1 = [SELECT UserRole.Name, Profile.Name FROM User WHERE Id=:UserInfo.getUserId()];
                isStartUser = isMatch(user1.UserRole.Name, esList[0].TransferApply__r.From_Location__c);
                isDestUser = isMatch(user1.UserRole.Name, esList[0].TransferApply__r.Destination_location__c);
                //20210519 you WLIG-C2J9AA start
                //is2B3 = user1.Profile.Name == '2B3_备品中心管理者(照片)';
                is2B3 = false;
                if(user1.Profile.Name == '2B3_备品中心管理者(照片)' || user1.UserRole.Name == '备品运营部'){
                   is2B3 = true;
                }
                //20210519 you WLIG-C2J9AA end
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '备品不存在'));
                saveBtnDisabled = true;
                return null;
            }

        }

        // 备品set明细
        List<TransferApplyDetail__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,TransferApplySummary__r.Fixture_Set__r.Name, Fixture_QRCode_F__c, TransferApplySummary__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,
                       TransferApply__r.RecordType.DeveloperName
                       , Return_DeliverySlip__c, Cancel_Select__c, Inspection_NG_abord_reason__c
                  from TransferApplyDetail__c
                 where TransferApplySummary__c in :esIds
                   and ((Shipment_request_time2__c <> null and Cancel_Select__c = False ) or Repair_Status_F__c = '修理完毕')
                 //order by TransferApplySummary__c, Is_First_TAD_F__c DESC, TransferApplySummary__r.Name, IndexFromUniqueKey__c
                 order by TransferApplySummary__r.Name, TransferApplySummary__c, Name
        ];
        for (TransferApplyDetail__c esd : eList) {
            EsdInfo ei = new EsdInfo(esd, isStartUser, isDestUser, is2B3);
            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';

        return null;
    }

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

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

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

        String userid = Userinfo.getUserId();
        List<TransferApplyDetail__c> eList = new List<TransferApplyDetail__c>();
        for (EsdInfo esdInfo : esdList) {
            TransferApplyDetail__c esd = esdInfo.rec;
            if (esdInfo.editable) {
                eList.add(esd);
            }
        }
        Boolean needSaveDetail = false;

        for (TransferApplyDetail__c esd : eList) {
            if (String.isNotBlank(esd.Inspection_result_after_Final__c)) {

            } else {
                esd.After_Inspection_time_Final__c = null;
                esd.Inspection_staff_After_Final__c = null;
                if (String.isNotBlank(esd.Inspection_result_after__c)) {

                } else {
                    esd.After_Inspection_time__c = null;
                    esd.Inspection_staff_After__c = null;
                }
            }

        }

        Savepoint sp = Database.setSavepoint();
        try {
            FixtureUtil.withoutUpsertObjects(eList);
            done_flg = true;
        } 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;
    }

    public class EsdInfo {
        public TransferApplyDetail__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 String fsName {get;set;}

        public EsdInfo(TransferApplyDetail__c rec, Boolean isStartUser, Boolean isDestUser, Boolean is2B3) {
            this.rec = rec;
            this.editable = false;
            this.fsName = rec.TransferApplySummary__r.Name;
            if(String.isNotBlank(rec.TransferApplySummary__r.Fixture_Set__r.Name)){
                this.fsName += ':' + rec.TransferApplySummary__r.Fixture_Set__r.Name;
            }
            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(is2B3) {
                this.editable = true;
            }
            // 取消或寄回，由调拨前中心操作
            else if(isStartUser) {
                this.editable = rec.Return_DeliverySlip__c != null || rec.Cancel_Select__c;
            }
            // 未取消且未寄回，由调拨后中心操作
            else if(isDestUser) {
                this.editable = rec.Return_DeliverySlip__c == null && !rec.Cancel_Select__c;
            }
            this.editable = this.editable && !rec.Arrival_in_wh__c && (rec.Check_lost_Item_F__c == 'OK' || rec.Repair_Status_F__c == '修理完毕');
        }
    }
}