//仿 EquipmentSetShippmentReceived6Controller.cls
public without sharing class ReceivingNoteAcceptanceController {

    public ReceivingNoteSummary__c rns { get; set; }
    public List<EsdInfo> esdList { get; set; }
    public Boolean saveBtnDisabled { get; private set; }
    public boolean ReturnRefuse {get;private set;}
    public String ErrorMessage {get; set;}
    //public String CDSFinished {get;set;}
    //public boolean LostFlg {get;set;}
    public boolean done_flg {get;set;}
    public String SR_status { get; private set; }
    public String Step_status { get; private set; }
    //public Boolean needCDS { get; private set; }
    //public String open_type { get; private set; }
    public Boolean forceSave { get; set; }
    public String rnId {get;set;}
    //public String AccessoryId {get;set;}
    //public String AccessorySetId {get;set;}
    //public String UnCheckedId {get;set;}
    private String rnsIdsStr;
    
    public ReceivingNoteAcceptanceController() {
        // Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        //传入一览的Id或No
        rnsIdsStr = 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');
        }
    }
    
    // 画面初始化
    public PageReference init() {
        forceSave = false;
        done_flg = false;
        rns = new ReceivingNoteSummary__c();
        esdList = new List<EsdInfo>();
        Set<Id> rnsIdSet = new Set<Id>();
        saveBtnDisabled = false;
        ReturnRefuse = true;
        ErrorMessage = '';
        List<String> rnsIdList = rnsIdsStr.split(',');

        if (rnsIdsStr != null) {
            // 当前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 :rnsIdList or Id in :rnsIdList)
                                                    ];
            if (rnsList.size() > 0) {
                for (ReceivingNoteSummary__c rns : rnsList) {
                    rnsIdSet.add(rns.Id);
                    rnId = rns.ReceivingNote__c;
                }
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '备品不存在'));
                saveBtnDisabled = true;
                return null;
            }

        }

        // 收货明细
        List<ReceivingNoteDetail__c> rndList = [
                SELECT ReceivingNoteSummary__r.ReceivingNoteSummaryNo__c
                     , Name
                     , ReceivingNoteSummary__c
                     , ReceivingNoteDetailNo__c
                     , AcceptanceResult__c
                     , AcceptanceComments__c
                     , Fixture_QRCode_F__c
                     , Barcode_F__c
                     , Change_Point__c
                     , SerialNumber_F__c
                     , SerialNumber_Origin__c
                     , unknow_serial_NO_product__c
                     , SerialNumber__c
                     , DataConfirmation__c
                     , Inspection_result_after__c
                     , ReceivingNoteSummary__r.Package_Status__c
                     , Product_Name_F__c
                     , After_Inspection_time__c
                     , Packing_list_Fixture_F__c
                     , Fixture_Set_Detail__r.Fixture_Set__c
                     , Fixture_Arrival_Process__c
                     , Fixture_Arrival_Product__r.Name
                     , Fixture_Arrival_Product__r.Fixture_Model_No_T__c
                     , Fixture_Model_No_F__c
                     , PeriodOfUse_Final__c
                     , PeriodOfUse__c
                     , PeriodOfUse_Old_F__c
                     , Asset_loaner_category_F__c
                  FROM ReceivingNoteDetail__c
                 WHERE ReceivingNoteSummary__c IN :rnsIdSet AND Delete_Flag__c = false
              ORDER BY ReceivingNoteSummary__r.Name, ReceivingNoteSummary__c asc, Is_Body_F__c desc, passNo2__c, passNo3__c
        ];
        for(ReceivingNoteDetail__c rnd:rndList){
            esdList.add(new EsdInfo(rnd));
        }


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

        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.AcceptanceResult__c, pageRnd.AcceptanceResult__c)){
            return false;
        }
        //验收备注
        else if (!stringEquals(originRnd.AcceptanceComments__c, pageRnd.AcceptanceComments__c)){
            return false;
        }
        // QRcode
        else if (!stringEquals(originRnd.Fixture_QRCode_F__c, pageRnd.Fixture_QRCode_F__c)){
            return false;
        }
        // Barcode
        else if (!stringEquals(originRnd.Barcode_F__c, pageRnd.Barcode_F__c)){
            return false;
        }
        // 无编号设备
        else if (!stringEquals(originRnd.unknow_serial_NO_product__c, pageRnd.unknow_serial_NO_product__c)){
            return false;
        }
        // 机身编号
        else if (!stringEquals(originRnd.SerialNumber__c, pageRnd.SerialNumber__c)){
            return false;
        }
        // 使用日期
        else if (!stringEquals(String.valueOf(originRnd.PeriodOfUse_Final__c), String.valueOf(pageRnd.PeriodOfUse_Final__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() {
        // Id-->面面明细
        Map<Id,ReceivingNoteDetail__c> pageRndMap = new Map<Id,ReceivingNoteDetail__c>();
        for(EsdInfo esd : esdList){
            pageRndMap.put(esd.rnd.Id,esd.rnd);
        }

        // 数据库读出明细
        List<ReceivingNoteDetail__c> originRndList = [
                SELECT Id
                     , AcceptanceStaff__c
                     , AcceptanceTime__c
                     , AcceptanceResult__c
                     , AcceptanceComments__c
                     , Fixture_QRCode_F__c
                     , Barcode_F__c
                     , unknow_serial_NO_product__c
                     , SerialNumber__c
                     , Name
                     , ReceivingNoteSummary__r.Package_Status__c
                     , DataConfirmation__c
                     , After_Inspection_time__c
                     , Change_Point__c
                     , PeriodOfUse_Final__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.Change_Point__c != '删除') {
                    if (originRnd.ReceivingNoteSummary__r.Package_Status__c != 'OK'){
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【' + originRnd.Name + '】未收货确认，无法保存，请刷新画面重试。'));
                    }
                    if (originRnd.DataConfirmation__c == false){
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【' + originRnd.Name + '】未数据确认，无法保存，请刷新画面重试。'));
                    }
                    if (originRnd.After_Inspection_time__c != null ){
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '【' + originRnd.Name + '】已验收完成，无法保存，请刷新画面重试。'));
                    }
                    if (ApexPages.hasMessages()) {
                        done_flg = false;
                        return null;
                    }
                }
                // 检查页面值的有效性
                if (pageRnd.unknow_serial_NO_product__c == 'FALSE') {
                    if(String.isBlank(pageRnd.SerialNumber__c) && String.isBlank(pageRnd.SerialNumber_F__c)){
                        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'origin'+originRnd));
                        //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'page'+pageRnd));
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, pageRnd.Name+':请填写【机身编码】或勾选【无机身号码设备】'));
                        done_flg = false;
                        return null;
                    }
                } else {
                    pageRnd.SerialNumber__c = null;
                }
                if (String.isBlank(pageRnd.AcceptanceResult__c)) {
                    pageRnd.AcceptanceStaff__c = null;
                    pageRnd.AcceptanceTime__c = null;
                } else {
                    pageRnd.AcceptanceStaff__c = Userinfo.getUserId();
                    pageRnd.AcceptanceTime__c = System.Now();
                }
                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 isChecked { get; set; }
        public Boolean canChange {get;set;}

        public EsdInfo(ReceivingNoteDetail__c rnd) {
            this.rnd=rnd;
            this.isChecked=false;
            this.canChange = false;
            // 数据确认完成，包装OK，未验收，未删除才可编辑
            if(this.rnd.ReceivingNoteSummary__r.Package_Status__c == 'OK'
                && this.rnd.DataConfirmation__c == true
                && this.rnd.After_Inspection_time__c == null
                && this.rnd.Change_Point__c != '删除' ) {
                this.canChange = true;
            }
        }
    }
}