public with sharing class Lost_Return_DeliverySlipController {
    public Boolean readOnly {get; set;}
    public FixtureDeliverySlip__c slip { get; set; }
    public String taId { get; set; }

    public List<PageBean> pbList { get; set; }



    public Lost_Return_DeliverySlipController() {
        taId = ApexPages.currentPage().getParameters().get('id');
        slip = new FixtureDeliverySlip__c();
        slip.DeliveryType__c = '发货';
        slip.Wh_Staff__c = UserInfo.getUserId();
        pbList = new List<PageBean>();
    }

    public void init() {
        if (String.isBlank(taId)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请传入正确的参数'));
            readOnly = true;
            return;
        }
        else {
            List<TransferApply__c> taList = [SELECT Id FROM TransferApply__c WHERE Id = :taId];
            if (taList.size() == 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '调拨申请不存在,请传入正确的参数'));
                readOnly = true;
                return;
            }
            else {
                List<TransferApplyDetail__c> tadList =[SELECT Id
                                                            , Inspection_result_after_ng__c
                                                            , Lost_item_check_staff__c
                                                            , Fixture_Model_No__c
                                                            , SerialNumber__c
                                                            , TAESD_Status__c
                                                            , Fixture_QRCode_F__c
                                                            , Return_DeliverySlip__c
                                                            , TransferApply__r.RecordType.DeveloperName
                                                         FROM TransferApplyDetail__c
                                                        WHERE TransferApply__c = :taId
                                                          AND Check_lost_Item_F__c = '欠品'
                                                          AND Detail_Finish__c = false];
                if (tadList.size() == 0) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有欠品中的调拨明细'));
                    readOnly = true;
                    return;
                }
                else {
                    for (TransferApplyDetail__c tad : tadList) {
                        PageBean pb = new PageBean(tad);
                        pbList.add(pb);
                    }
                }
            }
        }
    }

    public PageReference returnDelivery() {
        Savepoint sp = Database.setSavepoint();
        try {

            if (String.isBlank(slip.Wh_Staff__c)) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请填写物流单担当者'));
                return null;
            }
            else if (String.isBlank(slip.DeliveryCompany__c)) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请填写物流单物流公司 '));
                return null;
            }
            else if (String.isBlank(slip.Distributor_method__c)) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请填写物流单运输方式'));
                return null;
            }
            else if (String.isBlank(slip.Name)) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请填写物流单单号'));
                return null;
            }
            Map<Id, TransferApplyDetail__c> tadMap = new Map<Id, TransferApplyDetail__c>();
            Set<Id> tadIdSet= new Set<Id>();
            for (PageBean pb : pbList) {
                if (pb.checked) {
                    tadMap.put(pb.tad.Id, pb.tad);
                    tadIdSet.add(pb.tad.Id);
                }
            }
            if (tadMap.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未勾选发货的明细'));
                return null;
            }

            for (TransferApplyDetail__c tad : [SELECT Id
                                                    , Inspection_result_after_ng__c
                                                    , Lost_item_check_staff__c
                                                    , Fixture_Model_No__c
                                                    , SerialNumber__c
                                                    , TAESD_Status__c
                                                    , Fixture_QRCode_F__c
                                                    , Return_DeliverySlip__c
                                                    , TransferApply__r.RecordType.DeveloperName
                                                 FROM TransferApplyDetail__c
                                                WHERE TransferApply__c = :taId
                                                  AND Check_lost_Item_F__c = '欠品'
                                                  AND Detail_Finish__c = false
                                                  AND Id =:tadMap.keySet() FOR UPDATE]
            ) {
                tadIdSet.remove(tad.Id);
            }

            if (tadIdSet.size() > 0) {
                for (Id tadId : tadIdSet) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, tadMap.get(tadId).SerialNumber__c + ':不符合欠品发货条件。请刷新画面重试'));
                }
                return null;
            }
            Id userId = UserInfo.getUserId();
            Datetime no = Datetime.now();
            for (TransferApplyDetail__c tad : tadMap.values()) {
                tad.Redeliver_Staff__c = slip.Wh_Staff__c;
                tad.Redeliver_DeliveryCompany__c = slip.DeliveryCompany__c;
                tad.Redeliver_Distributor_method__c = slip.Distributor_method__c;
                tad.Redeliver_SlipNo__c = slip.Name;
                //if (tad.TransferApply__r.RecordType.DeveloperName == 'CenterToAgency') {
                    //tad.Lost_item_check_staff_Final__c = userId;
                    //tad.Lost_item_check_time_Final__c = no;
                    //tad.Check_lost_Item_Final__c = 'OK';
                    //if(tad.Return_DeliverySlip__c == null) {
                    //    tad.ArrivalResult__c = 'OK';
                    //}
                //}
            }
            FixtureUtil.withoutUpdate(tadMap.values());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, '保存成功'));
        }
        catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
        }
        return null;
    }

    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];
        }
        else {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '没有检索出符合条件的运输单'));
        }
        return null;
    }

    public Class PageBean {
        public Boolean checked {get; set;}
        public TransferApplyDetail__c tad {get; set;}

        public PageBean(TransferApplyDetail__c tad1) {
            checked = false;
            tad = tad1;
        }
    }
}