public without sharing class LoanerPortionDeliverController {
     // 基础Url
    public String baseUrl { 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; }
    /* 画面步骤
     * 下架:StockDown
     *
     */
    public String step { get; private set; }
    // 明细Bean
    public List<DataLineBean> dataLines { get; set; }
    // 明细行数
    public Integer getDatalineSize() {
        return dataLines == null ? 0 : dataLines.size();
    }

    public LoanerPortionDeliverController() {
        laId = System.currentPageReference().getParameters().get('id');
        step = System.currentPageReference().getParameters().get('step');
    }

    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,pickup_time__c,delivery_company__c,Return_to_wh_staff__c,Tracking_Number__c,Status__c,Agent__r.Name,Agent__c,Rental_Start_Date__c,Rental_End_Date__c,Equipment_Type__c,Owner.Name from loaner_application__c where Id = :laId];
        if (laList.size() == 0) {
            return null;
        }
        la = laList[0];
        System.debug(la.Owner.Name);
        lac = new loaner_application__c();
        lac.delivery_company__c = la.delivery_company__c;
        lac.Tracking_Number__c = la.Tracking_Number__c;
        if(la.Return_to_wh_staff__c != null){
            lac.Return_to_wh_staff__c = la.Return_to_wh_staff__c;
        }else{
            lac.Return_to_wh_staff__c = UserInfo.getUserId();
        }
       

        // 样机借出申请明细取得
        String sql_select = 'select Id, SerialNumber__c, Internal_Asset_number__c, OTCODE__c, ECCode__c,LOANER__c,LOANER__r.RecordType.Id,LOANER__r.Name,LOANER__r.Remarks2__c ';
        String sql_where = ' where loaner_application__c = :laId ';
        if (step == 'LPortionDeliver') {
            sql_where += ' and RAESD_Status__c = \'出库前已检测\'';
        } 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>();
        List<Asset> assList = new List<Asset>();
       
        if(dataLines.size() >0){
            Loaner_Express__c le = this.createExpress();
            Integer count = 0;
            for (DataLineBean dataLine : dataLines) {   
                if (dataLine.checkFlag == true) {
                    loaner_application_detail__c lad = dataLine.lad;
                    Asset loa = new Asset(id = lad.LOANER__c);
                    if(la.pickup_time__c == null){
                        if(lac.delivery_company__c == null || lac.delivery_company__c == ''){
                            delete le;
                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '请填写物流公司'));
                            return null;
                        }
                        if(lac.Return_to_wh_staff__c == null ){
                            delete le;
                            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '请填写发货人'));
                            return null;
                        }
                        lad.Shipment_Request_Date__c = Date.today();
                        lad.outTime__c = Datetime.now();
                        lad.RAESD_Status__c = '已出库';
                        //如果是个体管理,则改变样机状态
                        if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
                            loa.status = '出借';
                            if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'BS'){
                                loa.Loaner__c = la.Owner.Name;
                                loa.Rental_Customer__c = la.Agent__c;
                                loa.Rental_Start_Date__c = la.Rental_Start_Date__c;
                                loa.Rental_end_Date__c = la.Rental_end_Date__c;
                            }
                        }        
                        lad.Loaner_Express__c = le.id;    
                        lad.Return_to_wh_staff__c = lac.Return_to_wh_staff__c;
                        lad.delivery_company__c = lac.delivery_company__c;
                        lad.Tracking_Number__c = lac.Tracking_Number__c;
                        updList.add(lad);
                        if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
                            assList.add(loa);
                        }
                        count++;
                    }else{
                        lad.Shipment_Request_Date__c = Date.today();
                        lad.outTime__c = Datetime.now();
                        lad.Receipt_Date__c = Date.today();
                        lad.Receipt_Status__c = 'OK';
                        lad.RAESD_Status__c = '申请者已收货';
                        //如果是个体管理,则改变样机状态
                        if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
                            loa.status = '出借';
                            if(la.Equipment_Type__c== 'NDT' || la.Equipment_Type__c == 'ANI' || la.Equipment_Type__c == 'BS'){
                                loa.Loaner__c = la.Owner.Name;
                                loa.Rental_Customer__c = la.Agent__c;
                                loa.Rental_Start_Date__c = la.Rental_Start_Date__c;
                                loa.Rental_end_Date__c = la.Rental_end_Date__c;
                            }
                        }
                        updList.add(lad); 
                        if(lad.LOANER__r.RecordType.Id == System.label.Asset_Record_Type1){
                            assList.add(loa);
                        }       
                    }
                }
            }
            if(la.pickup_time__c == null){
                le.Consignor_LogisticsNumber__c = lac.Tracking_Number__c;
                le.Consignor_LogisticsCompany__c = lac.delivery_company__c;
                le.consignor__c =lac.Return_to_wh_staff__c;
                le.Shipment_Request_Date__c = Date.today();       
                le.NotReceivingNum__c = count;
            }else{
                delete le;
            }

            Savepoint sp = Database.setSavepoint();
            try {
                if (updList.size() > 0) {
                    if(la.pickup_time__c == null){
                        update le;
                    }
                    update updList;
                    update assList;
                    if(la.Status__c != '完毕'){
                        la.Status__c =  LoanerOrderState.getOrderStater(la.Id);
                        if(la.Status__c == '全部发货')  la.Shipping_Finished_Date_All__c = Date.today();
                        la.Shipping_Finished_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.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 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;
        }
    }

   






































































































   public PageReference sos(){
        Integer i=0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        return null;
    }

}