// FIXME 見積もり商品の Asset_Model_No__c ですが、数式になっています。トランザクションデータとして、項目を持つべきかと思います。by katsu 20130216
// 商談商品のId__c を PricebookEntry.Product2Idに変更すべき
// 見積もり可否 ですが、保存時みていますが、Sales_Possibilityを見ないですか？いいえ、js側で見ています
public class ConsumableSampleApplyController {

    public Id quoId {get;set;}
    public Boolean productStatusUpdated {get;set;}               // 状態更新、{!$Label.Status_Update} を押下したかどうか
    public Boolean changedAfterPrint {get;set;}                  // true の場合、画面に confirm メッセージが表示します。quoIdを新しいinsert。判定はjsにて実施

    public String excel_text {get;set;}
    public Integer select_index {get;set;}                       // excelImport専用ですが、jsにて制御することになるので、TODO katsu 削除予定
    public String Product_text {get;set;}
    public String setProduct_text {get;set;}

    public List<QELine> activities {get;set;}
    private List<QELine> activitiesbk;
    public List<QELine> tmpactivities {get;set;}
    public QELine active_activity {get;set;}
    //画面制御判定用
    public Boolean displayCost {get;set;}
    //ボタン制御用
    public Boolean Save_button {get;set;}
    public Boolean pdf_button {get;set;}
    //見積
    public ConsumableSample__c quo {get;set;}
    public Decimal total_ListPrice {get;set;}

    public boolean errorflg {get;set;}
    public String errorMessage {get;set;}
    public String baseUrl {get;set;}
    public boolean Messageflg {get;set;}
    public String Message {get;set;}
    
    public User loginUser {get;set;}
    
    private Map<Id, Product2> prd2LatestValMap;
    
    public ConsumableSampleApplyController() {
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        changedAfterPrint = false;
        productStatusUpdated = false;
    }

    public ConsumableSampleApplyController(ApexPages.StandardController controller) {
    }

    public PageReference init() {
        system.debug('============start init==============');
        errorflg = false;
        
        if (String.isBlank(ApexPages.currentPage().getParameters().get('completion')) == false) {
            if (ApexPages.currentPage().getParameters().get('completion') == '1') {
                errorflg = true;
                errorMessage = System.Label.Message_002;
            } else if (ApexPages.currentPage().getParameters().get('completion') == '2') {
                errorflg = true;
                errorMessage = '审批提交成功。';
            }
        }
        
        loginUser = [select Id from User where Id = :Userinfo.getUserId()];
        
        //Quote
        quo = new ConsumableSample__c();

        //quoid
        if (quoId==null){
            quoId = System.currentPageReference().getParameters().get('copyid');
            if (quoId==Null){
                quoId = System.currentPageReference().getParameters().get('id');
            }
        }

        //Quote
        Integer i;
        if (quoId==null){
            quo.CurrencyIsoCode = 'CNY';
            quo.Process_Status__c = '草案中';
            quo.PIC__c = loginUser.Id;
            //新規リストコントローラの取得
            if (activities==null){
                activities = new List<QELine>();
                activitiesbk = new List<QELine>();
                for (i=0;i<150;i++){
                    QELine active_activity = new QELine(i);
                    activities.add(active_activity);
                }
            }
        }else{
            List<ConsumableSample__c> quoList = 
                [SELECT Id,Name,CurrencyIsoCode,Process_Status__c,Contact__c,Account__c,Expect_Arrive_Date__c,Expect_Use_Date__c,Purpose__c,Reason__c,
                        PIC__c,CreatedDate,Contact__r.Hospital_name__c,Contact__r.AccountId
                   FROM ConsumableSample__c 
                  Where Id =:quoId];
            List<ConsumableSampleLineItem__c> items = 
                [Select Id,Asset_Model_No__c,Serial_Lot__c,SFDA_Status__c,Name__c,
                        Qty_Unit__c,Quantity__c,Product2__r.SFDA_Status__c,ProductCode__c,ListPrice__c,
                        Product2__r.Sales_Possibility__c,Product2__r.Name,Product2__c,Product2__r.Asset_loaner_category__c,Product2__r.Packing_list_manual__c
                   From ConsumableSampleLineItem__c 
                  where ConsumableSample__c = :quoId 
                  Order by Item_Order__c, Id];
            String copyQuoId = System.currentPageReference().getParameters().get('copyid');
            
            if (copyQuoId == null) {
            } else {
                // copyの場合、quoIdをnullに戻す
                quoId = null;
            }
            if (quoList.size() > 0){
                if (copyQuoId == null) {
                    quo = quoList[0];
                } else {
                    quo.CurrencyIsoCode = 'CNY';
                    quo.Process_Status__c = '草案中';
                    quo.PIC__c = loginUser.Id;
                    quo.Contact__c = null;
                    quo.Account__c = null;
                    quo.Expect_Arrive_Date__c = null;
                    quo.Expect_Use_Date__c = null;
                    quo.Purpose__c = '';
                    quo.Reason__c = '';
                }
            }

            activities = new List<QELine>();
            activitiesbk = new List<QELine>();
            i=0;
            QELine c = new QELine(i);
            QELine bk = new QELine(i);
            if(items.size()>0){
                for (ConsumableSampleLineItem__c o:items){
                    c = new QELine(o,i,copyQuoId);
                    activities.add(c);
                    bk = new QELine(o,i,copyQuoId);
                    activitiesbk.add(bk);
                    i++;
                }
      
                for (integer j=i;j<150;j++){
                    c = new QELine(j);
                    activities.add(c);
                }
                //マスタ最新情報の取得
                settingProduct2();
            }else{
                activities = new List<QELine>();
                for (i=0;i<150;i++){
                    QELine active_activity = new QELine(i);
                    activities.add(active_activity);
                }
            }
        }

        //--Savebutton
        Save_button = true;
        pdf_button = true;
        if (quo.Process_Status__c == '草案中' || quo.Process_Status__c == '不批准') {
        	Save_button = false;
        }
        if (quo.Process_Status__c == '批准') {
            pdf_button = false;
        }

        return null;
     }

    //excelImport
    public PageReference excelImport() {
        system.debug('○○○○○○○○○○○○○○○Welcome to excelImport!!');
        system.debug('▼▼▼▼▼excel_text:' + excel_text);

        errorflg = false;
        errormessage = null;

        //既存データ数の確認
        Integer j = 0;
        for (QELine s:activities){
            //データ判定にAsset_Model_Noを使用
            if ((s.Asset_Model==null) || (s.Asset_Model=='')){
                break;
            }
            j++;
        }

        //=======Temporary=====
        tmpactivities = activities;

        //=======Initialize=========
        activities = new List<QELine>();
        Integer i = 0;
        Integer xlscnt = 0;
        Integer rightcnt = 0; // 成功した数をカウント

        string[] xlslists = excel_text.split('\n',-1);
        List<string> xlslist = New List<string>();
        List<string> codelist = New List<string>();
        List<Integer> Quantitylist = New List<Integer>();

        Map<String, Integer> mp = new Map<String, Integer>();
        string xlscode;
        Integer xlsQuantity;

        try {
            for (string xls:xlslists){
                if(xls==null || xls==''){
                    //null
                }else{
                    xlscode = null;
                    xlsQuantity = null;
                    xlslist = xls.split('\t',-1);
                    for (String s:xlslist){
                        //odd number or even number
                        if (math.mod(i, 2) != 0){
                            //odd number
                            if (s=='' || s==null){
                                errorflg = true;
                                errormessage = System.Label.Error_Message31;
                                activities = tmpactivities;
                                pageArrange();
                                return null;
                            }else{
                                s = s.trim();
                                xlsQuantity = Integer.valueOf(s);
                                Quantitylist.add(xlsQuantity);
                            }
                        }else{
                            //even number
                            if (s=='' || s==null){
                                errorflg = true;
                                errormessage = System.Label.Error_Message31;
                                activities = tmpactivities;
                                pageArrange();
                                return null;
                            }else{
                                s = s.trim();
                                codelist.add(s);
                                xlscode = s;
                            }
                        }
                        i++;
                    }
                    //mp.put(xlscode, xlsQuantity);
                    xlscnt++;
                }
            }
        } catch(Exception ex) {
            activities = tmpactivities;
            errorflg = true;
            errormessage = System.Label.Error_Message31;
            pageArrange();
            return null;
        }

system.debug(j);
system.debug('xlscnt:::::' + xlscnt);

        if (codelist.size()==0 || Quantitylist.size()==0){
            activities = tmpactivities;
            errorflg = true;
            errormessage = System.Label.Error_Message31;
            pageArrange();
            return null;
        }

        xlscnt = j + xlscnt;
        if (xlscnt>150){
            activities = tmpactivities;
            errorflg = true;
            errormessage = System.Label.Error_Message32;
            pageArrange();
            return null;
        }

        i = 0;
        boolean lineflg = false;
        for (QELine t:tmpactivities){
            if(i==j){
                Map<String, Product2> mpProduct2 = new Map<String, Product2>();                     // keyがProductCodeです。
                List<Product2> items = [select Id,Name,ProductCode,
                        Foreign_Trade_Cost_US__c,Foreign_Trade_List_US__c,Intra_Trade_Cost_RMB__c,Intra_Trade_List_RMB__c,
                        Asset_Model_No__c,Serial_Lot_No__c,Asset_loaner_category__c,Sales_Possibility__c,Estimation_Entry_Possibility__c,
                        SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Packing_list_manual__c
                        FROM Product2 Where ProductCode In :codelist
                        And Manual_Entry__c = false];
                for (Product2 prd:items) {
system.debug('prd.ProductCode:::::' + prd.ProductCode);
                    mpProduct2.put(prd.ProductCode, prd);
                }
                Map<String, PricebookEntry> entries = new Map<String, PricebookEntry>();            // keyがProductCodeです。
                List<PricebookEntry> pbes = [
                    select Id, PricebookEntry.Product2.ProductCode
                    FROM PricebookEntry Where PricebookEntry.Product2.ProductCode IN :codelist
                    AND CurrencyIsoCode = :quo.CurrencyIsoCode
                    AND IsActive = true];
                for (PricebookEntry pbe:pbes) {
system.debug('pbe.Product2.ProductCode:::::' + pbe.Product2.ProductCode);
                    entries.put(pbe.Product2.ProductCode, pbe);
                }

                for (Integer l=0;l<codelist.size();l++){
system.debug('codelist[l]:::::' + codelist[l]);
                    Product2 prd = mpProduct2.get(codelist[l]);
                    if (prd != null){
                        PricebookEntry pbe = entries.get(codelist[l]);
                        
                        Schema.DescribeFieldResult dfr = ConsumableSampleLineItem__c.ListPrice__c.getDescribe();
                        Boolean cansee = dfr.isAccessible();
                        Decimal price = 0;
                        if (cansee) {
                            if (quo.CurrencyIsoCode == 'USD') {
                                price = prd.Foreign_Trade_List_US__c;
                            } else if (quo.CurrencyIsoCode == 'CNY') {
                                price = prd.Intra_Trade_List_RMB__c;
                            }
                        }
                        
                        QELine c = null;
                        if (pbe != null && (quo.CurrencyIsoCode=='USD' || quo.CurrencyIsoCode=='CNY')) {
                            if (quo.CurrencyIsoCode == 'USD') {
                                if (prd.Foreign_Trade_List_US__c > 0 && prd.Foreign_Trade_Cost_US__c > 0) {
                                    c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.Serial_Lot_No__c, prd.Asset_loaner_category__c, prd.ProductCode, prd.Id, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                            Quantitylist[l], price, price, prd.Foreign_Trade_Cost_US__c, prd.Packing_list_manual__c);
                                } else {
                                    continue;
                                }
                            } else {
                                if (prd.Intra_Trade_List_RMB__c > 0 && prd.Intra_Trade_Cost_RMB__c > 0) {
                                    c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.Serial_Lot_No__c, prd.Asset_loaner_category__c, prd.ProductCode, prd.Id, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                            Quantitylist[l], price, price, prd.Intra_Trade_Cost_RMB__c, prd.Packing_list_manual__c);
                                } else {
                                    continue;
                                }
                            }
                        } else {
                            continue;
                            // c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.Serial_Lot_No__c, prd.Asset_loaner_category__c, prd.ProductCode, prd.Id, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                            //        Quantitylist[l], 0, 0, 0);              // pbe ない時も追加する、setProductEntry() のロジックと違います。
                        }
                        activities.add(c);
                        i++;
                        rightcnt++;
                        lineflg = true;
                    }
                }
                if (lineflg==true){
                    i--;
                }
            }else{
                QELine a = New QELine(t, i);
                activities.add(a);
            }
            i++;
            if (i>149){
                break;
            }
        }
        // messageを出す
        errorflg = true;
        errormessage = '数据导入结束，导入 ' + codelist.size() + ' 件，成功' + rightcnt + ' 件';
        pageArrange();

        return null;

    }
    
    //Button Ivents============================================================

    //approval button
    public PageReference approvalBtn(){
    	system.debug('○○○○○○○○○○○○○○○Welcome to approvalButton!!');
    	
        List<String> productidList = new List<String>();
        if (activities.size()>0){
            for (QELine a:activities){
                String productid = a.PageObject.Product2__c;
                if (productid != null && productid.trim().length() > 0) {
                    productidList.add(productid);
                }
            }
        }
        if (productidList.size() <= 0) {
            errorflg = true;
            errorMessage = '没有选择产品。';
            pageArrange();
            return null;
        }
        
        Savepoint sp = Database.setSavepoint();
        try {
            //データチェック
            if (dataCheck() == false){
                return null;
            }
            if (dataEntry() == false){
                return null;
            }
            // 承認プロセス
	        Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
	        psr.setObjectId(quoId);
	        Approval.ProcessResult submitResult = Approval.process(psr);
	        
	        //msg
            errorflg = true;
            errorMessage = '审批提交成功。';
            //return null;
            PageReference pageRef = new PageReference('/apex/ConsumableSampleApply?id=' + this.quoId + '&completion=2');
            pageRef.setRedirect(true);
            return pageRef;
            
        } catch (DmlException de) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = de.getDmlMessage(0);           // １件目のエラーのみ表示
            System.debug(Logginglevel.ERROR, de.getMessage());
            System.debug(Logginglevel.ERROR, de.getStackTraceString());
        } catch (Exception e) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = e.getMessage();
            System.debug(Logginglevel.ERROR, e.getMessage());
            System.debug(Logginglevel.ERROR, e.getStackTraceString());
        }
        
        return null;
    }

    //Save button
    public PageReference Save(){

        errorflg = false;
        errormessage = null;
        Savepoint sp = Database.setSavepoint();
        try {
            //データチェック
            if (dataCheck() == false){
                return null;
            }
            if (dataEntry() == false){
                return null;
            }else{
                //msg
                errorflg = true;
                errorMessage = System.Label.Message_002;
                //return null;
                PageReference pageRef = new PageReference('/apex/ConsumableSampleApply?id=' + this.quoId + '&completion=1');
	            pageRef.setRedirect(true);
	            return pageRef;
            }
        } catch (DmlException de) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = de.getDmlMessage(0);           // １件目のエラーのみ表示
            System.debug(Logginglevel.ERROR, de.getMessage());
            System.debug(Logginglevel.ERROR, de.getStackTraceString());
        } catch (Exception e) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = e.getMessage();
            System.debug(Logginglevel.ERROR, e.getMessage());
            System.debug(Logginglevel.ERROR, e.getStackTraceString());
        }
        
        return null;
    }

    //OppReflection button
    public PageReference OppReflection(){

        Savepoint sp = Database.setSavepoint();
        try {
            errorflg = false;
            errormessage = null;

            //データチェック
            if (dataCheck() ==false){
                return null;
            }

            PageReference pageRef = new PageReference('/');
            if (dataEntry()==false){
                return null;
            }else{
                return pageRef;
            }
        } catch (DmlException de) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = de.getDmlMessage(0);           // １件目のエラーのみ表示
            System.debug(Logginglevel.ERROR, de.getMessage());
            System.debug(Logginglevel.ERROR, de.getStackTraceString());
        } catch (Exception e) {
            Database.rollback(sp);
            errorflg = true;
            errormessage = e.getMessage();
            System.debug(Logginglevel.ERROR, e.getMessage());
            System.debug(Logginglevel.ERROR, e.getStackTraceString());
        }
        
        return null;
    }
    
    //BackButton
    public PageReference Back(){
        return new Pagereference('/');
    }

    // TODO 削除する。商品最新状態は、sqlからすでにproductの最新状態を取得するして、コンストラクタで設定するようにします。このメソッドはいらない
    private void settingProduct2(){
        system.debug('○○○○○○○○○○○○Welcome to settingProduct2 class!!○○○○○○○○○○○○');

        pageArrange();
    }
    
    // 0表示 対策
    private void pageArrange(){
        if (activities.size()>0){
            for (QELine a:activities){
                if ((a.Asset_Model==null) || (a.Asset_Model=='')){
system.debug('○○○○○○○○○○○○Welcome to pageArrange Asset_Model is △');
                    a.ListPrice_Page = null;
                    a.ListPriceTotal_Page = null;
                } else {
system.debug('○○○○○○○○○○○○Welcome to pageArrange Asset_Model=[' + a.Asset_Model + ']');
                }
            }
        }
    }

    public boolean dataCheck(){
        system.debug('○○○○○○○○○○○○Welcome to dataCheck class!!○○○○○○○○○○○○');
        errorflg = false;
        errormessage = null;
        Boolean error = false;
        List<String> product2Ids = New List<String>();
        if (activities.size()>0){
            for (QELine a:activities){
                if (String.isBlank(a.PageObject.Product2__c) == false) {
                    product2Ids.add(a.PageObject.Product2__c);
                }
            }
            
            prd2LatestValMap = new Map<Id, Product2>();
            for (Product2 prd2: [Select Id, Estimation_Entry_Possibility__c, SFDA_Status__c From Product2 Where Id IN :product2Ids]) {
                if (prd2.Estimation_Entry_Possibility__c != '○') {
                    error = true;
                }
                prd2LatestValMap.put(prd2.Id, prd2);
            }
            
            if (error == true){
                if (quoId != null) {
                    Map<String,ConsumableSampleLineItem__c> itemmap = new Map<String,ConsumableSampleLineItem__c>();
                    for (ConsumableSampleLineItem__c item : [
                        Select Id,Product2__r.SFDA_Status__c,Product2__r.Name,Product2__c
                        From ConsumableSampleLineItem__c where ConsumableSample__c = :quoId Order by Item_Order__c, Id]) {
                        itemmap.put(item.Product2__c,item);
                    }
                    for (QELine a:activities){
                        if (a.PageObject.Product2__c != null) {
                            if (itemmap.containskey(a.PageObject.Product2__c)) {
                                a.pageObject.SFDA_Status__c = itemmap.get(a.PageObject.Product2__c).Product2__r.SFDA_Status__c;
                                a.pageObject.Name__c = itemmap.get(a.PageObject.Product2__c).Product2__r.Name;
                            }
                        }
                    }
                }
            }
        }
        
        if (error==true){
            PageArrange();
            errorflg = true;
            errorMessage = System.Label.Error_Message37 + System.Label.Error_Message48;
            return false;
        }
        
        PageArrange();
        errorflg = false;
        errorMessage = null;
        return true;
    }

    public boolean dataEntry(){
system.debug('○○○○○○○○○○○○Welcome to dataEntry class!!○○○○○○○○○○○○');
        Boolean error = false;
        if(quo.Contact__c == null){
            quo.Contact__c.addError(System.Label.Error_Message3);
            error = true;
            errormessage = System.Label.Error_Message3;
        }
        for (QELine a : activities) {
            if ((a.Asset_Model!=null) && (a.Asset_Model!='')){
                if (a.PageObject.Quantity__c==null || a.PageObject.Quantity__c==0){
                    a.PageObject.Quantity__c.addError(System.Label.Error_Message3);
                    error = true;
                    errormessage = System.Label.Error_Message3;
                }
            }
        }

        if (error==true){
            PageArrange();

            errorflg = true;
            return false;
        }

        //Quote-------------------------------------------------------------
        //商談Id、価格表Id
        //見積名称、標準定価合計、見積金額合計(積上)、病院の契約金額、原価、
        //値引金額計算、値引き金額金額、見積調整金額計算、見積調整金額金額
        //第一販売店名称、金額、利益、％、第二販売店名称、金額、利益、％
        //优惠成交价、优惠折扣、优惠价格、单价、报价金额、Total
        //契約内訳、印刷病院名称、見積有効期限日、見積表記コメント
        ConsumableSample__c q = New ConsumableSample__c();
        
        if (changedAfterPrint) {
            quoId = null;
        }
        if (quoId==null){
            q = New ConsumableSample__c();
        }else{
            List<ConsumableSample__c> qs = New List<ConsumableSample__c>();
            qs = [SELECT Id,Name,CurrencyIsoCode,Contact__c,Account__c,Expect_Arrive_Date__c,Expect_Use_Date__c,Purpose__c,Reason__c,
                         PIC__c,CreatedDate,Contact__r.Hospital_name__c
                    FROM ConsumableSample__c 
                   Where Id =:quoId];
            if (qs.size()>0){
                q = qs[0];
            }
        }
        
        List<Contact> cont = [select Id,AccountId from Contact where Id = :quo.Contact__c];
        String accid = null;
        if (cont.size() > 0) {
        	accid = cont[0].AccountId;
        }

        q.CurrencyIsoCode = quo.CurrencyIsoCode;
        q.PIC__c = quo.PIC__c;
        if (quoId==null){
            q.Contact__c = quo.Contact__c;
        }
        q.Account__c = accid;
        q.Expect_Arrive_Date__c = quo.Expect_Arrive_Date__c;
        q.Expect_Use_Date__c = quo.Expect_Use_Date__c;
        q.Purpose__c = quo.Purpose__c;
        q.Reason__c = quo.Reason__c;

        if (quoId==null){
            insert q;
        }else{
            update q;
        }

system.debug('○○○○○Save1○○○○○');

        //QuoteLineItem;
        List<ConsumableSampleLineItem__c> qlist = New List<ConsumableSampleLineItem__c>();
        qlist=[Select Id From ConsumableSampleLineItem__c Where ConsumableSample__c =:quoId];
        if (qlist.size()>0){
            //delete
            delete qlist;
        }

        //QuoteLineItem--------------------------------------------
        //製品型番、品目コード、SFDAステータス、品目名、ListPrice、数量
        //価格、単位、小計、OCM売上予測金額（税抜）、価格表
        qlist = New List<ConsumableSampleLineItem__c>();
        //Sap送信,Printに合わせて1～
        Integer i=1;
system.debug('○○○○○'+activities.size()+'○○○○○');
        activitiesbk = new List<QELine>();
        if (activities.size()>0){
            for (QELine s:activities){
                if (s.Asset_Model != null && s.Asset_Model != ''){
system.debug('○○○○○'+s.pageObject.Product2__c+'○○○○○');
                    if (s.pageObject.Product2__c != null){
                        // TODO katsu なぜclone()しますか？意味不明。
                        ConsumableSampleLineItem__c ql = s.pageObject.clone();
                        ql.ConsumableSample__c = q.Id;
                        ql.ListPrice__c = s.ListPrice_Page;
                        ql.SFDA_Status__c = prd2LatestValMap.get(s.pageObject.Product2__c).SFDA_Status__c;
                        //並び順
                        ql.Item_Order__c = i;
                        qlist.add(ql);
                        
                        activitiesbk.add(new QELine(ql, s.lineNo, null));
                    }
                }
                i++;
            }
            insert qlist;

        }

        //保存時引合Pageに戻らない処理とした為にQuoteIdをここでセット
        if (quoId==null){
            quoId = q.Id;
            
        }

        return true;
    }
    
    public class QELine {
        public Integer lineNo { get; set; }                                // 画面の順序
        public String Asset_Model {get;set;}
        public String Serial_Lot {get;set;}
        public String Asset_loaner_category {get;set;}
        public String Sales_Possibility {get;set;}                         // 販売可否○×判断用、使ってないようです。TODO 削除
        public ConsumableSampleLineItem__c pageObject { get; set; }                      // Id__cは空行判断用、SFDA_Status__c など、翻訳される項目表示するため使う必要があります
        //public Decimal Cost_c { get; set; }
        //public Decimal Cost_Subtotal_c { get; set; }
        public Decimal ListPrice_Page { get; set; }
        public Decimal ListPriceTotal_Page { get; set; }
        public Decimal Packing_list_manual { get; set; }

        // TODO ほんとうはいらない、使うところのロジックを修正しなければいけない、削除するようにしたいです。
        public QELine(Integer i) {
            pageObject = New ConsumableSampleLineItem__c();
            this.lineNo = i;
        }
        // tmp 直接使う場合のパターン
        public QELine(QELine tmp, Integer i) {
            pageObject = tmp.pageObject;
            this.lineNo = i;
            this.Asset_Model = tmp.Asset_Model;
            this.Serial_Lot = tmp.Serial_Lot;
            this.Asset_loaner_category = tmp.Asset_loaner_category;
            this.Sales_Possibility = tmp.Sales_Possibility;
            //this.Cost_Subtotal_c = tmp.Cost_Subtotal_c;
            //this.Cost_c = tmp.Cost_c;
            this.ListPrice_Page = tmp.ListPrice_Page;
            this.ListPriceTotal_Page = tmp.ListPriceTotal_Page;
            this.Packing_list_manual = tmp.Packing_list_manual;
        }
        public QELine(ConsumableSampleLineItem__c qli, Integer i, String copyQuoId) {
            pageObject = qli.clone();
            pageObject.Product2__c = qli.Product2__c;
            pageObject.Quantity__c = qli.Quantity__c;
            if(copyQuoId != null) {
                pageObject.SFDA_Status__c = qli.Product2__r.SFDA_Status__c;
                pageObject.Name__c = qli.Product2__r.Name;
            }
            this.lineNo = i;
            this.Asset_Model = qli.Asset_Model_No__c;
            this.Serial_Lot = qli.Serial_Lot__c;
            this.Asset_loaner_category = qli.Product2__r.Asset_loaner_category__c;
            this.ListPrice_Page = qli.ListPrice__c;
            this.ListPriceTotal_Page = qli.Quantity__c * qli.ListPrice__c;
            this.Packing_list_manual = (qli.Product2__r.Packing_list_manual__c == null || qli.Product2__r.Packing_list_manual__c <= 0) ? 1 : qli.Product2__r.Packing_list_manual__c;
        }
        
        // TODO Subtotal__c、以前のロジックを確認
        public QELine(Integer i, String PricebookEntryId, String Asset_Model, String Serial_Lot, String Asset_loaner_category, String ProductCode, String Id_c, String SFDA_Status_c, String Sales_Possibility_c, String Name_c, String BSS_Category_c, Integer Quantity, Decimal ListPrice_c, Decimal UnitPrice_c, Decimal Cost_c, Decimal Packing_list_manual_c) {
            pageObject = New ConsumableSampleLineItem__c();
            pageObject.Quantity__c = Quantity;
            this.lineNo = i;
            this.Asset_Model = Asset_Model;
            this.Serial_Lot = Serial_Lot;
            this.Asset_loaner_category = Asset_loaner_category;
            this.Sales_Possibility = Sales_Possibility_c;
            pageObject.Product2__c = Id_c;
            pageObject.SFDA_Status__c = SFDA_Status_c;
            pageObject.Name__c = Name_c;
            this.ListPrice_Page = ListPrice_c;
            this.ListPriceTotal_Page = Quantity * ListPrice_c;
            //this.Cost_c = Cost_c;
            // TODO katsu なぜここ > 0 の判断はいらない？
            //this.Cost_Subtotal_c = Cost_c * Quantity;
            this.Packing_list_manual = (Packing_list_manual_c == null || Packing_list_manual_c <= 0) ? 1 : Packing_list_manual_c;
        }
    }

   
}