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

    public TransferShippmentReceived4Controller() {
        Id = ApexPages.currentPage().getParameters().get('id');
        ApplyId = Id;
    }

    private List<TransferApplyDetail__c> getDetails(Set<Id> tasIdSet) {
        List<TransferApplyDetail__c> tadList = [
                select Lost_item_Memo_Final__c, Lost_item_Memo__c, TransferApplySummary__r.Wei_loaner_arranged__c, TransferApply__r.Asset_return_ng_num__c
                , TransferApplySummary__r.Shippment_loaner_time2__c
                , TransferApply__r.RecordType.DeveloperName
                , DeliverySlip__c
                , Redeliver_Staff__c
                , Redeliver_SlipNo__c
                , Redeliver_Distributor_method__c
                , Redeliver_DeliveryCompany__c
                , Shippment_loaner_time__c
                , NoItemReturn__c, SerialNumber_F__c, Asset_return_time__c, Check_lost_Item_F__c, TransferApplySummary__r.Received_ng_detail__c, TransferApplySummary__r.Wei_Return_Finish__c, TransferApplySummary__r.Received_Confirm__c, Check_lost_Item_Final__c, Return_DeliverySlip__c, Fixture_Name_F__c, TransferApplySummary__r.Fixture_Set__r.Name, TransferApplySummary__c, Fixture_QRCode_F__c, TransferApply__r.Name, 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, Main_OneToOne__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,ArrivalResult__c,Arrival_NG_Comment__c  //20210426 ljh add 1832
                  from TransferApplyDetail__c
                 where TransferApplySummary__c in :tasIdSet and DeliverySlip__c <> null
                   //and Cancel_Select__c = False
                 order by TransferApplySummary__r.Name, TransferApplySummary__c, Name
        ];
        return tadList;
    }
    /**
    @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>();
        Map<Id, TransferApplySummary__c> esMap = new Map<Id, TransferApplySummary__c>();
        saveBtnDisabled = false;
        if (Id != null) {
            List<String> ids = Id.split(',');
            // 当前User
            List<TransferApplySummary__c> esList;
            esList = [select TransferApply__r.Loaner_centre_mail_address__c, TransferApply__r.Name
                            , First_TAD_Model_No_F__c, First_TAD__r.SerialNumber_F__c, First_TAD__r.Loaner_asset_no__c
                            , 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)
                        order by TransferApply__r.Name, Id];
            if (esList.size() > 0) {
                for (TransferApplySummary__c raes : esList) {
                    esMap.put(raes.Id, raes);
                }
                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 = getDetails(esMap.keySet());
        String raesId = '';
        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;
    }

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

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

                if (String.isNotBlank(esd.Check_lost_Item_Final__c)) {
                    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;
                    }
                } 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;
                    }
                    if (String.isBlank(esd.Check_lost_Item__c)) {
                        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) {
                    esd.CDS_complete_time__c = null;
                    esd.CDS_staff__c = null;
                }
                eList.add(esd);
                assetIdForLockSet.add(esd.Asset__c);
            }
        }

        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 {
            FixtureUtil.withoutUpsertObjects(eList);
            done_flg = true;
        } catch (Exception ex) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
            done_flg = false;
        }
        return null;
    }

    public class EsdInfo {
        public TransferApplyDetail__c rec { get; set; }
        public boolean isChecked { get; set; }
        public boolean editable { get; set; }
        public String fsName {get; set;}
        public Id slipId {get;set;}

        public EsdInfo(TransferApplyDetail__c rec, Boolean isStartUser, Boolean isDestUser, Boolean is2B3) {
            this.rec = rec;
            this.isChecked = true;
            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;
            }
            // 备品中心发到办事处，又被寄回时，要看回寄，由调拨前地区用户做欠品确认
            String applyType = rec.TransferApply__r.RecordType.DeveloperName;
            if(applyType == 'CenterToAgency') {
                if (rec.Asset_return_time__c != null) {
                    this.editable = (isStartUser || is2B3) && String.isBlank(rec.Inspection_result_after__c) && !rec.Arrival_in_wh__c;
                    this.slipId = rec.Return_DeliverySlip__c;
                }
            }
            // 其它类型只要发货了，由调拨后地区用户做欠品确认
            else if(applyType == 'CenterToCenter' || applyType == 'AgencyToCenter') {
                if (rec.Shippment_loaner_time__c != null) {
                    this.editable = (isDestUser || is2B3) && String.isBlank(rec.Inspection_result_after__c) && !rec.Arrival_in_wh__c;
                    this.slipId = rec.DeliverySlip__c;
                }
            }
        }
    }
}