//仿 EquipmentSetShippmentReceived6Controller.cls
public without sharing class ReceivingNoteExaminationController {
    public List<EsdInfo> esdList { get; set; }
    public boolean done_flg {get;set;}
    public Boolean saveBtnDisabled { get; private set; }
    private String Id;
    
    public ReceivingNoteExaminationController() {
        Id = ApexPages.currentPage().getParameters().get('id');
    }
    /**
    @description 初始化
    */
    public PageReference init() {
        done_flg = false;
        esdList = new List<EsdInfo>();
        Set<Id> rnsIds = new Set<Id>();
        saveBtnDisabled = false;
        if (Id != null) {
            List<String> ids = Id.split(',');
            // 当前User
            String userid = Userinfo.getUserId();
            User user = [select Id,Name from User where Id = :userid];
            // 收货清单一览
            List<ReceivingNoteSummary__c> rnsList = [select Fixture_Model_No__c, Id, ReceivingNote__c
                                            from ReceivingNoteSummary__c
                                           where (ReceivingNoteSummaryNo__c in :ids or Id in :ids)
                                             ];

            if (rnsList.size() > 0) {
                for (ReceivingNoteSummary__c rns : rnsList) {
                    rnsIds.add(rns.Id);
                }
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '收货清单一览不存在'));
                saveBtnDisabled = true;
                return null;
            }
            
        }

        // 收货一览明细
        List<ReceivingNoteDetail__c> rndList = [
                SELECT Name
                     , AcceptanceResult__c
                     , Arrival_in_wh__c
                     , Inspection_result_after__c
                     , Check_Result_Sum__c
                     , After_Inspection_time__c
                     , Inspection_staff_After__c
                     , Inspection_Comment__c
                     , ReceivingNoteSummary__r.Fixture_Set__r.Name
                     , ReceivingNoteSummary__r.ReceivingNoteSummaryNo__c
                     , ReceivingNoteDetailNo__c
                     , RNDAssert__r.Pre_Reserve_RAES_Detail__c
                     , RNDAssert__r.Pre_Reserve_RAES_Detail__r.After_Inspection_time__c
                     , RNDAssert__r.Name
                     , RNDAssert__r.Product_Name__c
                     , RNDAssert__r.Fixture_Model_No_F__c
                     , RNDAssert__r.NMPA_Approbation_No__c
                     , RNDAssert__r.ProductionDate__c
                     , RNDAssert__r.Consumable_Guaranteen_end__c
                     , RNDAssert__r.ProduceCompany__c
                     , RNDAssert__r.Product2.VenderNameFormal__c
                     , Product_Name_Check__c
                     , Model_Check__c
                     , NMPA_Approbation_No_Check__c
                     , Production_Date_Check__c
                     , Guarantee_End_Check__c
                     , Produce_Company_Check__c
                     , Vender_Check__c
                     , SerialNumber_F__c
                     , Fixture_QRCode_F__c
                     , Barcode_F__c
                     , ReceivingNoteSummary__r.First_RND__c
                     , ReceivingNoteSummary__r.Received_Confirm_Date__c
                     , DataConfirmationAgain__c
                     , Product_Name_F__c
                     , Inspection_Cnt__c
                     , Packing_list_Fixture_F__c
                     , ReceivingNoteSummary__r.Inspection_result_F__c
                     , Fixture_Arrival_Process__c
                     , Fixture_Arrival_Product__r.Name
                     , PeriodOfUse_Final__c
                     , PeriodOfUse__c

                  FROM ReceivingNoteDetail__c
                 WHERE ReceivingNoteSummary__c IN :rnsIds AND Delete_Flag__c = false AND Change_Point__c != '删除'
              ORDER BY ReceivingNoteSummary__r.Name, ReceivingNoteSummary__c ASC, Is_Body_F__c DESC, passNo2__c, passNo3__c];

        for (ReceivingNoteDetail__c rnd : rndList) {
            EsdInfo ei = new EsdInfo(rnd);
            esdList.add(ei);
        }


        if (esdList.size() <= 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有收货一览明细'));
            saveBtnDisabled = true;
            return null;
        }
        //Step_status = '检测';
        //SR_status = 'Excamination';

        return null;
    }

    /**
    @param originRnd 数据库中明细
    @param pageRnd 页面上的明细
    @return 值一样时返回true,不一样时返回false
    @description 判断页面上的明细和数据库中的明细是否一致
    */
    @TestVisible private Boolean detailEquals(ReceivingNoteDetail__c originRnd, ReceivingNoteDetail__c pageRnd){
        Boolean isEqual = true;
        // 检测结果
        if(!stringEquals(originRnd.Inspection_result_after__c, pageRnd.Inspection_result_after__c)){
            return false;
        }
        // 检测备注
        if (!stringEquals(originRnd.Inspection_Comment__c, pageRnd.Inspection_Comment__c)){
            return false;
        }
        if (!stringEquals(originRnd.Product_Name_Check__c, pageRnd.Product_Name_Check__c)){
            return false;
        }
        if (!stringEquals(originRnd.Model_Check__c, pageRnd.Model_Check__c)){
            return false;
        }
        if (!stringEquals(originRnd.NMPA_Approbation_No_Check__c, pageRnd.NMPA_Approbation_No_Check__c)){
            return false;
        }
        if (!stringEquals(originRnd.Production_Date_Check__c, pageRnd.Production_Date_Check__c)){
            return false;
        }
        if (!stringEquals(originRnd.Guarantee_End_Check__c, pageRnd.Guarantee_End_Check__c)){
            return false;
        }
        if (!stringEquals(originRnd.Produce_Company_Check__c, pageRnd.Produce_Company_Check__c)){
            return false;
        }
        if (!stringEquals(originRnd.Vender_Check__c, pageRnd.Vender_Check__c)){
            return false;
        }
        return true;
    }
    /**
    @param s1 字符串1
    @param s2 字符串2
    @return 一样则返回true, null和'' 也为true
    @description
    */
    @TestVisible private Boolean stringEquals(String s1, String s2){
        if (String.isBlank(s1) && String.isBlank(s2)){
            return true;
        }
        else if(s1!=null){
            return s1.equals(s2);
        }
        else{
            return s2.equals(s1);
        }
    }
    /**
    @description 保存
    */
    public PageReference save() {
        Map<Id,ReceivingNoteDetail__c> pageRndMap = new Map<Id,ReceivingNoteDetail__c>();
        for(EsdInfo esd : esdList){
            if (esd.editable) {
                pageRndMap.put(esd.rnd.Id,esd.rnd);
            }
        }

        // 数据库读出明细
        List<ReceivingNoteDetail__c> originRndList = [
                select Id
                     , Inspection_result_after__c
                     , After_Inspection_time__c
                     , Inspection_staff_After__c
                     , Inspection_Comment__c
                     , Product_Name_Check__c
                     , Model_Check__c
                     , NMPA_Approbation_No_Check__c
                     , Production_Date_Check__c
                     , Guarantee_End_Check__c
                     , Produce_Company_Check__c
                     , Vender_Check__c
                     , Inspection_Cnt__c
                     , ReceivingNoteSummary__r.Wei_Acceptance_Cnt__c
                     , AcceptanceResult__c
                     , Name
                     , DataConfirmationAgain__c

                from ReceivingNoteDetail__c 
                where Id in :pageRndMap.keySet()
                for update
                ];

        // 存放需要被更新的明细
        List<ReceivingNoteDetail__c> updateRndList = new List<ReceivingNoteDetail__c>();
        for(ReceivingNoteDetail__c originRnd : originRndList){

            ReceivingNoteDetail__c pageRnd = pageRndMap.get(originRnd.Id);
            // 页面上填写值与数据库不一致时,加入待更新列表
            if (!detailEquals(originRnd, pageRnd)){
                if(originRnd.AcceptanceResult__c != 'OK'){
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【'+originRnd.Name +'】未清点完成，不可以验收，请刷新画面重试。'));
                    return null;
                }
                if(originRnd.DataConfirmationAgain__c){
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【'+originRnd.Name +'】已再数据确认，不可以修改验收结果，请刷新画面重试。'));
                    return null;
                }
                if (String.isNotBlank(pageRnd.Inspection_result_after__c)) {
                    pageRnd.After_Inspection_time__c = System.now();
                    pageRnd.Inspection_staff_After__c = Userinfo.getUserId();
                    pageRnd.Received_Quantity__c = 1;
                } else {
                    pageRnd.After_Inspection_time__c = null;
                    pageRnd.Inspection_staff_After__c = null;
                    pageRnd.Received_Quantity__c = 0;
                }
                // 医疗器械名称
                if (String.isNotBlank(pageRnd.Product_Name_Check__c)) {
                    pageRnd.Product_Name_Check_Text__c = pageRnd.RNDAssert__r.Product_Name__c;
                } else {
                    pageRnd.Product_Name_Check_Text__c = null;
                }
                // 规格（型号）
                if (String.isNotBlank(pageRnd.Model_Check__c)) {
                    pageRnd.Model_Check_Text__c = pageRnd.RNDAssert__r.Fixture_Model_No_F__c;
                } else {
                    pageRnd.Model_Check_Text__c = null;
                }
                // 注册证号或备案凭证编号
                if (String.isNotBlank(pageRnd.NMPA_Approbation_No_Check__c)) {
                    pageRnd.NMPA_Approbation_No_Check_Text__c = pageRnd.RNDAssert__r.NMPA_Approbation_No__c;
                } else {
                    pageRnd.NMPA_Approbation_No_Check_Text__c = null;
                }
                // 生产日期
                if (String.isNotBlank(pageRnd.Production_Date_Check__c) && pageRnd.RNDAssert__r.ProductionDate__c != null) {
                    pageRnd.Production_Date_Check_Text__c = pageRnd.RNDAssert__r.ProductionDate__c.format();
                } else {
                    pageRnd.Production_Date_Check_Text__c = null;
                }
                // 有效期（或者失效期）
                if (String.isNotBlank(pageRnd.Guarantee_End_Check__c) && pageRnd.RNDAssert__r.Consumable_Guaranteen_end__c != null) {
                    pageRnd.Guarantee_End_Check_Text__c = pageRnd.RNDAssert__r.Consumable_Guaranteen_end__c.format();
                } else {
                    pageRnd.Guarantee_End_Check_Text__c = null;
                }
                // 生产企业
                if (String.isNotBlank(pageRnd.Produce_Company_Check__c)) {
                    pageRnd.Produce_Company_Check_Text__c = pageRnd.RNDAssert__r.ProduceCompany__c;
                } else {
                    pageRnd.Produce_Company_Check_Text__c = null;
                }
                // 供货者
                if (String.isNotBlank(pageRnd.Vender_Check__c)) {
                    pageRnd.Vender_Check_Text__c = pageRnd.RNDAssert__r.Product2.VenderNameFormal__c;
                } else {
                    pageRnd.Vender_Check_Text__c = null;
                }

                if (pageRnd.Received_Quantity__c == 1 
                    && pageRnd.Inspection_result_after__c == 'OK') {
                    pageRnd.Inspection_Cnt__c = 1;
                } else {
                    pageRnd.Inspection_Cnt__c = 0;
                }
                updateRndList.add(pageRnd);
            }
        }
        if (updateRndList.size()>0){
            Savepoint sp = Database.setSavepoint();
            try {
                FixtureUtil.withoutUpsertObjects(updateRndList);
                done_flg = true;
                return null;
            } catch (Exception ex) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
                Database.rollback(sp);
                done_flg = false;
                return null;
            }
        }
        return null;
    }

    public class EsdInfo {
        public ReceivingNoteDetail__c rnd { get; set; }
        public boolean quickCheck { get; set; }
        public boolean editable { get; set; }
        public boolean isChecked { get; set; }

        public EsdInfo(ReceivingNoteDetail__c rnd) {
            this.rnd = rnd;
            this.editable = false;
            this.quickCheck = false;
            this.isChecked = false;
            // 清点OK 再数据确认前才可编辑
            if(rnd.AcceptanceResult__c == 'OK' && rnd.DataConfirmationAgain__c == false) {
                this.editable = true;
            }
        }
    }
}