//仿EquipmentSetSRList2Controller.cls
/*
    TestClass
    RentalFixtureManage1Test
    RentalFixtureManage3Test
    RentalFixtureManage9Test
    RentalFixtureManage10Test
 */
public with sharing class ReceivingNoteListController {
    public List<ReceivingNoteSummary__c> rnsList { get; set; }
    public List<SummaryInfo> summaryInfoList{get;set;}
    public String sr_open { get; set; }
    public Boolean doneFlg {get; set; }
    public String receiving_note_no { get; set; }
    public String sr_id { get; set; }
    public String sr_type { get; set; }
    public List<SelectOption> typeList {get; set;}
    public String selectedType {get; set;}
    public String rndIdsStr {get; set;}
    public String rnId {get; set;}
    public String userId;
    public ReceivingNote__c relatedNote { get; set; }

    public Integer getRnsListSize() {
        return rnsList.size();
    }

    public ReceivingNoteListController() {
        receiving_note_no = ApexPages.currentPage().getParameters().get('id');
        sr_type = ApexPages.currentPage().getParameters().get('type');
        sr_open = ApexPages.currentPage().getParameters().get('open');
        summaryInfoList = new List<SummaryInfo>();
        userId = Userinfo.getUserId();
    }

    public void init() {

        rnsList = new List<ReceivingNoteSummary__c>();
        doneFlg = false;
        initTypeList();
        Set<Id> summaryIdSet = new Set<Id>();
        Map<Id, Integer> summaryFileCnt = new Map<Id, Integer>();

        if (receiving_note_no != null) {
            rnsList = [
                    SELECT Id
                         , ReceivingNoteSummaryNo__c
                         , Fixture_Model_No_F__c
                         , First_RND__r.SerialNumber_F__c
                         , First_RND__r.Fixture_QRCode_F__c
                         , RNS_Status__c
                         , ReceivingNote__c
                         , Wei_DataConfirmation_Cnt__c
                         , Wei_Acceptance_Cnt__c
                         , ReceivingNoteDetail_Cnt__c
                         , ReceivingNote__r.Asset_loaner_category__c
                         , ReceivingNote__r.Status__c
                         , Package_Status__c
                         , Package_Status_Memo__c
                      FROM ReceivingNoteSummary__c
                     //WLIG-BV8CHF 20210331 you  start
                     //WHERE ReceivingNote__r.ReceivingNoteNo__c = :receiving_note_no
                     WHERE ReceivingNote__r.ReceivingNoteNo_New__c = :receiving_note_no
                     //WLIG-BV8CHF 20210331 you  end
                  ORDER BY ReceivingNoteSummaryNo__c
                    ];

            for(ReceivingNoteSummary__c rns:rnsList){
                SummaryInfo summaryInfo = new SummaryInfo(rns);
                summaryInfoList.add(summaryInfo);
                rnId = rns.ReceivingNote__c;
                summaryIdSet.add(rns.Id);
            }

            if(summaryInfoList.size() == 0){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '收货清单没有收货清单明细'));
            } else {
                relatedNote = [select Id, Name from ReceivingNote__c where id = :rnId];
                AggregateResult[] fileCnt = [select count(id) cnt, LinkedEntityId
                                                from ContentDocumentLink
                                                where LinkedEntityId in :summaryIdSet
                                                group by LinkedEntityId];
                for (AggregateResult cnt : fileCnt) {
                    summaryFileCnt.put((Id)cnt.get('LinkedEntityId'), Integer.valueOf(cnt.get('cnt')));
                }

                for (SummaryInfo si : summaryInfoList) {
                    if (summaryFileCnt.containsKey(si.rns.Id)) {
                        si.fileCnt = summaryFileCnt.get(si.rns.Id);
                    }
                }
            }
        }
        return;
    }

    private void initTypeList(){
        typeList = new List<SelectOption>();
        typeList.add(new SelectOption('无','无'));
        typeList.add(new SelectOption('收货确认','收货确认'));
        typeList.add(new SelectOption('取消收货确认','取消收货确认'));
        typeList.add(new SelectOption('清点','清点'));
        typeList.add(new SelectOption('验收','验收'));
        typeList.add(new SelectOption('入库', '入库'));

        System_UserSetting__c config = System_UserSetting__c.getInstance(userId);
        selectedType = config.ReceivingNote_Action_Type__c;
        if (String.isBlank(selectedType)){
            selectedType = '无';
        }
    }
    public void setType(){

        if (selectedType != '无' && selectedType != null ){
            System_UserSetting__c config = System_UserSetting__c.getInstance(userId);
            config.ReceivingNote_Action_Type__c = selectedType;
            FixtureUtil.withoutUpsertObjects(new System_UserSetting__c[]{config});
        }

    }
    /**
    @description 变更收货确认状态
    */
    public void receivedConfirm(){
        List<ReceivingNoteSummary__c>  updateRNSList = new List<ReceivingNoteSummary__c> ();
        List<Id> rnsIdList = new List<Id>();
        List<Id> delRnsList = new List<Id>();
        Map<Id, ReceivingNoteSummary__c> updateMap = new Map<Id, ReceivingNoteSummary__c>([
                        SELECT Id
                             , Wei_DataConfirmation_Cnt__c
                             , Wei_Acceptance_Cnt__c
                             , ReceivingNoteDetail_Cnt__c
                          FROM ReceivingNoteSummary__c
                          //WLIG-BV8CHF 20210331 you  start
                         //WHERE ReceivingNote__r.ReceivingNoteNo__c = :receiving_note_no
                         WHERE ReceivingNote__r.ReceivingNoteNo_New__c = :receiving_note_no
                         //WLIG-BV8CHF 20210331 you  end
                        ]);

        if (selectedType == '收货确认') {
            for (SummaryInfo sinfo : summaryInfoList){
                if(sinfo.isChecked) {
                    if(updateMap.containsKey(sinfo.rns.Id)) {
                        ReceivingNoteSummary__c originRns = updateMap.get(sinfo.rns.Id);
                        if (sinfo.rns.Wei_DataConfirmation_Cnt__c > 0 || originRns.Wei_DataConfirmation_Cnt__c > 0) {
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【'+sinfo.rns.ReceivingNoteSummaryNo__c+'】有未做数据确认的明细存在，不能确认收货，请刷新画面重试。'));
                        }
                        if (originRns.Wei_Acceptance_Cnt__c < originRns.ReceivingNoteDetail_Cnt__c) {
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【'+sinfo.rns.ReceivingNoteSummaryNo__c+'】清点已开始，不可以修改收货确认状态，请刷新画面重试。'));
                        }
                    }
                    else {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【'+sinfo.rns.ReceivingNoteSummaryNo__c+'】不存在，请刷新画面重试。'));
                    }
                    if (sinfo.rns.Package_Status__c == null) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【'+sinfo.rns.ReceivingNoteSummaryNo__c+'】未填写外包装是否完整，不能确认收货。'));
                    }
                    // 对被选中的一览 的 确认时间 和 确认人 赋值
                    sinfo.rns.Received_Confirm_Time__c = System.now();
                    sinfo.rns.Received_Confirm_Staff__c = userId;
                    updateRNSList.add(sinfo.rns);
                    rnsIdList.add(sinfo.rns.Id);
                }
            }
            if (ApexPages.hasMessages()) return;
        }
        else if (selectedType == '取消收货确认'){
            for (SummaryInfo sinfo : summaryInfoList){
                if(sinfo.isChecked){
                    if(updateMap.containsKey(sinfo.rns.Id)) {
                        ReceivingNoteSummary__c originRns = updateMap.get(sinfo.rns.Id);
                        if (originRns.Wei_Acceptance_Cnt__c < originRns.ReceivingNoteDetail_Cnt__c) {
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【'+sinfo.rns.ReceivingNoteSummaryNo__c+'】清点已开始，不可以修改收货确认状态，请刷新画面重试。'));
                            return;
                        }
                    }
                    else {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【'+sinfo.rns.ReceivingNoteSummaryNo__c+'】不存在，请刷新画面重试。'));
                        return;
                    }
                    // 将被选中的一览的确认时间和确认人清空
                    sinfo.rns.Received_Confirm_Time__c = null;
                    sinfo.rns.Received_Confirm_Staff__c = null;
                    sinfo.rns.Package_Status__c = null;
                    sinfo.rns.Package_Status_Memo__c = null;
                    updateRNSList.add(sinfo.rns);
                    rnsIdList.add(sinfo.rns.Id);
                    delRnsList.add(sinfo.rns.Id);
                }
            }
        }

        if (updateRNSList.size() > 0){
            Savepoint sp = Database.setSavepoint();
            List<ReceivingNoteSummary__c> rnsList = [select ReceivingNoteSummaryNo__c,
                                                            Id,
                                                            Fixture_Model_No__c,
                                                            First_RND__r.SerialNumber_F__c,
                                                            First_RND__r.Fixture_QRCode_F__c,
                                                            RNS_Status__c,
                                                            ReceivingNote__r.Status__c,
                                                            Received_Confirm_Time__c,
                                                            Received_Confirm_Staff__c

                                                       from ReceivingNoteSummary__c
                                                      where Id in :rnsIdList
                                                      for update
                                                    ];
            try {
                FixtureUtil.withoutUpsertObjects(updateRNSList);
                if (delRnsList.size() > 0) {
                    List<ContentDocumentLink> delList =  [select id from ContentDocumentLink where LinkedEntityId in :delRnsList];
                    FixtureUtil.withoutDelete(delList);
                }
            } catch (Exception ex) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
                Database.rollback(sp);
                return;
            }
        }
        doneFlg = true;
        return;

    }

    public void checkckb() {
        if (selectedType == '收货确认' || selectedType == '取消收货确认') {
            for (SummaryInfo sinfo : summaryInfoList){
                if (sinfo.canChange == false) sinfo.isChecked = false;
            }
        } else {
            for (SummaryInfo sinfo : summaryInfoList){
                sinfo.isChecked = sinfo.isChecked;
            }
        }
    }

    public class SummaryInfo{
        public ReceivingNoteSummary__c rns {get;set;}
        public boolean isChecked{get;set;}
        public Integer fileCnt{get;set;}
        public Boolean canChange {get;set;}
        public SummaryInfo(ReceivingNoteSummary__c rns){
            this.isChecked = false;
            this.rns = rns;
            this.fileCnt = 0;
            this.canChange = false;
            // 全部明细数据确认后，且还没开始清点才可以编辑
            if (rns.Wei_DataConfirmation_Cnt__c == 0 && rns.Wei_Acceptance_Cnt__c == rns.ReceivingNoteDetail_Cnt__c) {
                //this.isChecked = true;
                this.canChange = true;
            }
        }

    }
}