public without sharing class TransferShippmentReceived2Controller {
    public List<EsdInfo> esdList { 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; }
    public Boolean done_flg { get; set; }
    public String Raid {get;set;}
    private String Id;

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

    public TransferShippmentReceived2Controller() {
        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');
        }
    }

    // 画面初始化
    public PageReference init() {
        esdList = new List<EsdInfo>();
        Set<Id> esIds = new Set<Id>();
        saveBtnDisabled = false;
        done_flg = false;
        SR_status = 'Shippment';
        if (Id != null) {
            List<String> ids = Id.split(',');
            // 当前User
            String userid = Userinfo.getUserId();
            User user = [select Id,Name from User where Id = :userid];
            // 备品set
            List<TransferApplySummary__c> esList = [
                select Yi_Inspection_not_finish__c
                     , Id
                     , Cancel_Select__c
                     , TransferApply__c
                     , TAS_Status__c
                     , Name
                     , Shippment_loaner_time2__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) {
                    if (raes.Yi_Inspection_not_finish__c > 0 || raes.Cancel_Select__c == false) {
                        esIds.add(raes.Id);
                        Raid = raes.TransferApply__c;
                    }
                }
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '备品不存在'));
                saveBtnDisabled = true;
                return null;
            }
        }

        // 备品set明细
        List<TransferApplyDetail__c> eList = [
                select Repair__c, SerialNumber_F__c, Pre_After_Inspection_elapsed_days__c, Pre_Inspection_Comment__c,Fixture_Name_F__c, Shipment_request_time2__c, DeliverySlip__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_TAES_Detail__c, Asset__r.Pre_Reserve_TAES_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 TransferApplyDetail__c
                 where TransferApplySummary__c in :esIds
                   and Cancel_Select__c = False
                 order by TransferApplySummary__r.Name, TransferApplySummary__c, Name
        ];

        for (TransferApplyDetail__c esd : eList) {
            EsdInfo ei = new EsdInfo(esd);
            if (esd.DeliverySlip__c == null && esd.Repair__c == null
                    && esd.StockDown__c == true
                    && esd.Shipment_request_time2__c != null) {
                ei.editable = true;
            }
            esdList.add(ei);
        }

        Step_status = '发货前';
        if (esdList.size() <= 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有备品set明细'));
            saveBtnDisabled = true;
            return null;
        }
        system.debug('=====' + Step_status);
        system.debug('=====' + open_type);

        return null;
    }

    // Step 切り替えボタン、发货前-检测
    public PageReference Shippment1() {
        Step_status = '发货前';
        return new PageReference('/apex/TransferShippmentReceived2?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/TransferShippmentReceived3?id=' + this.Id);
    }

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

        //检查是否可以继续
        TransferApply__c RaTar = [select Campaign__c,Repair__c,
                                                Campaign__r.Status,repair__r.Return_Without_Repair_Date__c,Repair__r.Repair_Final_Inspection_Date__c,Repair__r.Repair_Shipped_Date__c
                                            from TransferApply__c
                                            where id=:Raid];

        if( RaTar.Campaign__r.Status == '取消'){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '学会已取消，不能继续操作了'));
            return null;
        }
        else if(RaTar.Repair__r.Repair_Final_Inspection_Date__c!=null){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '存在修理最终检测日，不能继续了'));
            return null;
        }
        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;
        }
        else if(RaTar.Repair__r.Repair_Shipped_Date__c!=null){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '存在RC修理返送日，不能继续了'));
            return null;
        }

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

        for (TransferApplyDetail__c esd : eList) {
            if (esd.Inspection_result__c <> null && esd.StockDown__c == false) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '备品set未下架，不能填写发货前检查结果'));
                return null;
            }
        }

        // TODO 没变化不存
        if (Step_status == '发货前') {

            for (TransferApplyDetail__c esd : eList) {

                // 发货前检查结果
                if (esd.Inspection_result__c == null) {
                    esd.Pre_inspection_time__c = null;
                    esd.Inspection_staff__c = null;
                }
            }
            needSaveDetail = true;
        }

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

    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) {
            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_TAES_Detail__c != null && rec.Asset__r.Pre_Reserve_TAES_Detail__r.After_Inspection_time__c != null) {
                this.quickCheck = Datetime.now() < rec.Asset__r.Pre_Reserve_TAES_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');
            }
        }
    }
}