public without sharing class LoanerPortionReturnController {
	 // 基础Url
    public String baseUrl { get; private set; }
   // public Boolean isNDT {get;private set;}
    // 样机借出申请ID
    public String laId { get; private set; }
    public loaner_application__c lac {get; private set;}
    public loaner_application__c la { get; private set; }
    public boolean isOk {get; private set; }
    public String step { get; private set; }
    public String staticResource { get; private set; }// Update PIPL 20220425 By Chen Yanan

    public String loanerType {get; private set; } 
    // 明细Bean
    public List<DataLineBean> dataLines { get; set; }
    // 明细行数
    public Integer getDatalineSize() {
        return dataLines == null ? 0 : dataLines.size();
    }

    public LoanerPortionReturnController() {
        laId = System.currentPageReference().getParameters().get('id');
        step = System.currentPageReference().getParameters().get('step');
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('loaner_application__c'));// Update PIPL 20220425 By Chen Yanan
    }

    public PageReference init() {
        // 基础Url
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0,path.indexOf('/apex'));
        } else if (path.indexOf('production/') > 0) {
            baseUrl += '/production';
        }
        // 明细Bean
        dataLines = new List<DataLineBean>();

        if (String.isBlank(laId) == true) {
            return null;
        }
        if (String.isBlank(step) == true) {
            return null;
        }

        // 样机借出申请取得
        List<loaner_application__c> laList = [select Id,AWS_Data_Id__c,loaner_request_number__c,Return_Trake_Staff__c,Return_Track_Company__c,Return_Track_Number__c,Status__c,HP_Received_Sign_Date__c,RecordType.DeveloperName,loaner_manage_place__c,Equipment_Type__c from loaner_application__c where Id = :laId];  //Update PIPL 20220425 By Chen Yanan
        if (laList.size() == 0) {
            return null;
        }
        la = laList[0];
        loanerType = la.Equipment_Type__c;
        /*if(la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI'){  
            isNDT = true;
        }else{
            isNDT =false;
        }*/
        lac = new loaner_application__c();
        lac.Return_Track_Company__c = la.Return_Track_Company__c;
        lac.Return_Track_Number__c = la.Return_Track_Number__c;
        lac.AWS_Data_Id__c = la.AWS_Data_Id__c;  //Update PIPL 20220425 By Chen Yanan
        lac.return_Number__c = '';
        if(la.Return_Trake_Staff__c != null){
            lac.Return_Trake_Staff__c = la.Return_Trake_Staff__c;
        }else{
            User temp = [select id,Name from User where id = :UserInfo.getUserId()];
            lac.Return_Trake_Staff__c = temp.Name;
        }
        // 样机借出申请明细取得
        String sql_select = 'select Id, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c,RAESD_Status__c,LOANER__r.Name,LOANER__r.Remarks2__c,LOANER__r.Description ';
        String sql_where = ' where loaner_application__c = :laId ';
        if (step == 'APortionDeliver') {
            sql_where += ' and RAESD_Status__c in (\'申请者已装机确认\',\'申请者收货NG\',\'已出库\',\'申请者已收货\')';
        } else {
            return null;
        }
        String sql_full = sql_select + ' from loaner_application_detail__c ' + sql_where;
        
        List<loaner_application_detail__c> lads = Database.query(sql_full);
        if (lads.size() == 0) {
            return null;
        }
        // 明细Bean作成
        Integer cnt = 0;
        for (loaner_application_detail__c lad : lads) {
            cnt += 1;
            DataLineBean dataLine = new DataLineBean(cnt, lad);
            dataLines.add(dataLine);
        }
      
        return null;
    }

     public PageReference saveBtn() {
        // 根据step更新样机借出申请明细状态
        List<loaner_application_detail__c> updList = new List<loaner_application_detail__c>();
        Boolean isOK = true;
        List<loaner_application__c> lappList = [select id,AllLead_OrderName__c,Equipment_Type__c  from loaner_application__c where  Status__c = '已批准'];
        if(lappList.size() > 0){
            for(loaner_application__c lapp : lappList){
                if(lapp.AllLead_OrderName__c != null){
                    if(lapp.AllLead_OrderName__c.contains(la.loaner_request_number__c) && lapp.Equipment_Type__c == 'BS'){
                       ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '存在已批准的转借申请单，请点击 转借发货'));  
                        return null;
                    }
                }
            }
        }
            
        
        Integer count = 0;
        if(dataLines.size() > 0 ){
            Loaner_Express__c le = this.createExpress();
            for (DataLineBean dataLine : dataLines) {	
                if (dataLine.checkFlag == true) {
                    loaner_application_detail__c lad = dataLine.lad;
                    if (step == 'APortionDeliver') {
                        if( lac.Return_Track_Company__c == null || lac.Return_Track_Company__c =='' ){
                            delete le;
                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '请填写物流公司'));  
                            return null;
                        }
                        if( lac.Return_Trake_Staff__c == null ){
                            delete le;
                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '请填写返品人'));  
                            return null;
                        }
                        if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI'){

                            if(lac.loaner_manage_place__c == null || lac.loaner_manage_place__c == ''){
                                delete le;
                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '请填写样机管理地'));  
                                return null;
                            }
                            if(lac.return_Number__c == null || lac.return_Number__c == ''){
                                delete le;
                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '请填写返品人电话'));  
                                return null;
                            }


                        }
                        lad.Return_Express__c = le.id;
                        lad.Asset_Return_Date__c = Date.today();
                        lad.RAESD_Status__c = '已回寄';
                        lad.Return_Track_Company__c = lac.Return_Track_Company__c;
                        lad.Return_Track_Number__c = lac.Return_Track_Number__c;
                        lad.Return_Trake_Staff__c = lac.Return_Trake_Staff__c;
                        lad.loaner_manage_place__c = lac.loaner_manage_place__c;
                        lad.return_Number__c = lac.return_Number__c;
                        //lad.inTime__c = Datetime.now();
                        count++;
                    }

                    updList.add(lad);

                }
            }

            le.Asset_Return_Date__c = Date.today();
            le.Return_LogisticsCompany__c =lac.Return_Track_Company__c;
            le.Return_LogisticsNumber__c = lac.Return_Track_Number__c;
            le.Return_Sender__c = lac.Return_Trake_Staff__c;
            le.return_Number__c = lac.return_Number__c;
            le.NotReceivingNum__c = count;

            Savepoint sp = Database.setSavepoint();
            try {
                if (updList.size() > 0) {
                	update updList;
                    update le;
                    if(la.Status__c != '完毕'){
                        la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
                        if(la.Status__c == '全部回寄') la.Asset_Return_Date_All__c = Date.today();
                        la.Asset_Return_Date__c = Date.today();
                	   update la;
                    }
                }else{
                    delete le;
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '请选择需要回寄的样机'));
                    return null;
                }
               
            } catch (Exception ex) {
                Database.rollback(sp);
                delete le;
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
                return null;
            }
        }
        // 返回样机借出申请画面
        String url = baseUrl;
        url += '\\' + laId;
        return new Pagereference(url);
    }

    public Loaner_Express__c createExpress(){
        Date temp = Date.today();
        Loaner_Express__c le = new Loaner_Express__c();
        le.loaner_application__c = laId;
        le.IsDeliveryLogistics__c = false;
        le.Name = temp.day()+ '日回寄物流单';
        try{
            insert le;
        }catch(Exception ex){
             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
        }

        return le;
    }
    public Pagereference getIsOk(){
        isOk = false;
        if(la.RecordType.DeveloperName == 'RVI' || la.RecordType.DeveloperName == 'NDT' || la.RecordType.DeveloperName == 'ANI'){
            return null;
        }
        if(dataLines.size() > 0 ){
            for (DataLineBean dataLine : dataLines) {   
                if (dataLine.checkFlag == true) {
                    loaner_application_detail__c lad = dataLine.lad;
                    if(lad.RAESD_Status__c == '申请者已收货' || lad.RAESD_Status__c == '已出库'){
                        isOk = true;
                        break;
                    }
                }
            }
        }
        return null;
    }

    

    public PageReference cancelBtn() {
        // 返回样机借出申请画面
        String url = baseUrl;
        url += '\\' + laId;
        return new Pagereference(url);
    }

    public class DataLineBean {
        // 是否选择
        public boolean checkFlag { get; set; }
        // 行号
        public Integer lineNo { get; private set; }
        // 样机借出申请明细
        public loaner_application_detail__c lad { get; set; }

        public DataLineBean(Integer in_no, loaner_application_detail__c in_lad) {
            checkFlag = false;
            lineNo = in_no;
          	lad = in_lad;      	 
        }
    }

}