// FIXME 見積もり商品の Asset_Model_No__c ですが、数式になっています。トランザクションデータとして、項目を持つべきかと思います。by katsu 20130216
// 商談商品のId__c を PricebookEntry.Product2Idに変更すべき
// 見積もり可否 ですが、保存時みていますが、Sales_Possibilityを見ないですか？いいえ、js側で見ています
public class NewQuoteIraiController {
    public Integer quoteEntryMaxLine {get; private set;}
    public Id quoId {get;set;}
    public String oppid;
    public String leadid;
    //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
    public String tenderid;
    //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
    public Boolean productStatusUpdated {get;set;}               // 状態更新、{!$Label.Status_Update} を押下したかどうか
    public Boolean changedAfterPrint {get;set;}                  // true の場合、画面に confirm メッセージが表示します。quoIdを新しいinsert。判定はjsにて実施

    //lastbuy  2022/3/10 fy start
    public Boolean filg { get; set; }
    public Integer flglastbuy { get; set; }
    public String errorProductmodel { get; set; }
    public Boolean is_changed_opp { get; set; }
    //lastbuy  2022/3/10 fy end
    //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start
    public String erroraxsdmodel { get; set; }
    //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 end
    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 QuoteIrai__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;
    //obsap 新增经销商1字段 fy satrt
    public Decimal Salesprofit1 { get; set; }
    public Decimal SalesCalculation1 { get; set; }
    public Boolean displayFlg { get; set; }
    //obsap 新增经销商1字段 fy end

    // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
    public QuoteBean qb { get; set; }
    // CHAN-BJQ4VZ 精琢技术 2019/12/11 End

    // 经销商询价报价委托 2020-02-28 update by vivek start
    public Map<Id,Id> userProfileId;
    // 经销商询价报价委托 2020-02-28 update by vivek end

    // obsap对应 obsap人员检索 2022-04-27 ssm start
    public class UserSelect {
        public String user_name { get; set; }
        public User user { get; set; }
        public UserSelect(User u) {
            this.user_name = u.Alias;
            this.user = u;
        }
    } 
    public String obsap_mail { get; set; }
    //obsap obsap人员检索 fy satrt
    // public String selectObsapUsers { get; set; }
    public List<SelectOption> ObsapUsers { get; set; }
    public boolean obsflag { get; set; }
    //obsap obsap人员检索 fy end
    // obsap对应 obsap人员检索 2022-04-27 ssm end

    public NewQuoteIraiController() {
        quoteEntryMaxLine = Integer.valueOf(System.Label.QuoteEntryMaxLine);
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        changedAfterPrint = false;
        productStatusUpdated = false;
    }

    public NewQuoteIraiController(ApexPages.StandardController controller) {
        this();
    }
    
    public PageReference checkIraiUser() {
        system.debug('============' + quo.IraiUser__c + '============');
        return null;
    }

    public PageReference init() {
        system.debug('============start init==============');
        obsap_mail = System.Label.OBSAP_Group_Mail;
        errorflg = false;
        pdf_button = true;
        obsflag = false;
        //loginUser
        loginUser = [select Id, ProfileId, State_Hospital__c, Salesdepartment_text__c from User where Id = :UserInfo.getUserId()];
        if (loginUser.ProfileId == System.Label.ProfileId_SystemAdmin) {
            pdf_button = false;
        }
        String obsap_Login_area=System.Label.obsap_Login_area;
        List<String> obsaplogareaList =obsap_Login_area.split(',');
        if(obsaplogareaList.contains(loginUser.Salesdepartment_text__c)){
            obsflag = true;
        }
        // obsap对应 obsap人员检索 2022-04-27 ssm start
        // if (loginUser != null && String.isNotBlank(loginUser.Salesdepartment_text__c) && (loginUser.Salesdepartment_text__c == '5.华东' || loginUser.Salesdepartment_text__c == '6.华南')) {
        //fy 20220512
        if (loginUser != null && String.isNotBlank(loginUser.Salesdepartment_text__c) && obsflag) {

            // obsflag = true;
            // 这里做了个比较2的修改
            // 由于客户不想给公共小组的每个人都创建一个任务，只能用队列
            // 这样才能实现一个任务，小组成员都能看到，谁完成都算完成
            // 又由于需要发送邮件，工作流里发送邮件只能到公共小组，不能发给队列
            // 所以把公共小组当作队列成员扔进去
            // 这里只能取两次才能取到小组里的某一个人
            String obsap_group_id = System.Label.obsap_group_opp;
            List<GroupMember> queue =  [SELECT Id, GroupId, UserOrGroupId FROM GroupMember where GroupId = :obsap_group_id];
            system.debug('queue++'+queue);
            if (queue != null && queue.size() > 0) {
                List<GroupMember> members =  [SELECT Id, GroupId, UserOrGroupId FROM GroupMember where GroupId = :queue[0].UserOrGroupId];
                GroupMember member = members != null && members.size() > 0 ? members[0] : new GroupMember();
                User obsap_user = [SELECT Id, Name, Alias FROM User WHERE Id =: member.UserOrGroupId];
                ObsapUsers = new List<SelectOption>();
                // ObsapUsers.add(new SelectOption('',''));
                // for (User u : obsaps) {
                //     ObsapUsers.add(new SelectOption(u.Id,u.Alias));
                // }
                ObsapUsers.add(new SelectOption(obsap_user.Id, 'OBSAP小组'));
            }
        }
        // obsap对应 obsap人员检索 2022-04-27 ssm end
        //Quote
        quo = new QuoteIrai__c();
        // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
        qb = new QuoteBean();
        // CHAN-BJQ4VZ 精琢技术 2019/12/11 End

        //quoid
        if (quoId==null){
            quoId = System.currentPageReference().getParameters().get('copyid');
            if (quoId==Null){
                quoId = System.currentPageReference().getParameters().get('id');
            }
        }
        
        // 潜在客户id
        // String leadid = System.currentPageReference().getParameters().get('leadid');
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy start
        leadid = System.currentPageReference().getParameters().get('leadid');
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy end
        // 经销商询价报价委托 2020-02-28 update by vivek start
        // 经销商询价
        String agencyoppid = System.currentPageReference().getParameters().get('agencyoppid');
        // 经销商询价报价委托 2020-02-28 update by vivek start

        // 招投标报价委托 2021-06-21 update by gzw start
        // 招投标
        //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        // String tenderid = System.currentPageReference().getParameters().get('tenderid');
        tenderid = System.currentPageReference().getParameters().get('tenderid');
        //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy end

        // 招投标报价委托 2021-06-21 update by gzw start

        // 询价id
        oppid = System.currentPageReference().getParameters().get('oppid');
        QuoteIrai__c quoteiraiobj = new QuoteIrai__c();
        //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        if(oppid==null&&quoId!=null&&leadid==null&&agencyoppid==null){
            // if(oppid==null&&tenderid==null&&quoId!=null&&leadid==null&&agencyoppid==null){
        //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            quoteiraiobj = [select id,Note__c,Noteplus__c from QuoteIrai__c where id=:quoId];
            if(quoteiraiobj.Note__c!=null){
                String[] quosub=quoteiraiobj.Note__c.split('/');
                //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
                oppid=quosub[quosub.size()-1].substring(0,15);
                //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
                // oppid=quosub[quosub.size()-1];
            }
        }
        system.debug('oppid:++++'+oppid);
        system.debug('leadid:++++'+leadid);
        system.debug('tenderid:++++'+tenderid);
        // 报价id
        String oppquoid = System.currentPageReference().getParameters().get('oppquoid');
        //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
        List<Opportunity> oppList = [Select id,CurrencyIsoCode, If_Account_Change__c from Opportunity where id =:oppid];
        // lastbuy变更用户询价判断
        // 如果取得了询价，则取询价上的是否变更用户，否则false
        is_changed_opp = oppList != null && oppList.size() > 0 ? oppList[0].If_Account_Change__c : false;
        
        //Quote
        Integer i;
        if (quoId==null){
            // System.debug('进到这里了---');
            // if(oppList.size()>0){
            //     quo.CurrencyIsoCode = oppList[0].CurrencyIsoCode;
            //     system.debug('币种1：'+quo.CurrencyIsoCode);
            // }
            //注释原逻辑 wql
            quo.CurrencyIsoCode = 'CNY';
            //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
            if (String.isNotBlank(leadid)) {
                quo.Note__c = Lead.sObjectType.getDescribe().getLabel() + '：' + baseUrl + '/' + leadid;
            }
            // 经销商询价报价委托 2020-02-28 update by vivek start
            if (String.isNotBlank(agencyoppid)) {
                quo.Note__c = Agency_Opportunity__c.sObjectType.getDescribe().getLabel() + '：' + baseUrl + '/' + agencyoppid;
            }
            // 经销商询价报价委托 2020-02-28 update by vivek end
            // 招投标报价委托 2021-06-21 update by gzw start
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            // if (String.isNotBlank(tenderid)) {
            if (String.isNotBlank(tenderid)&&String.isBlank(leadid)) {
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
                quo.Note__c = Tender_information__c.sObjectType.getDescribe().getLabel() + '：' + baseUrl + '/' + tenderid;
            }
            // 招投标报价委托 2021-06-21 update by gzw end
            if (String.isNotBlank(oppid)) {
                quo.Note__c = Opportunity.sObjectType.getDescribe().getLabel() + '：' + baseUrl + '/' + oppid;
            }
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
            quo.Noteplus__c = quo.Note__c;
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
            //新規リストコントローラの取得
            if (activities==null){
                activities = new List<QELine>();
                activitiesbk = new List<QELine>();
                for (i=0;i<quoteEntryMaxLine;i++){
                    QELine active_activity = new QELine(i);
                    activities.add(active_activity);
                }
            }
            
            if (String.isNotBlank(oppid)) {
                //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                // 询价信息
                List<Opportunity> oppl = [select Id,AccountId,Account.Name,Name,CurrencyIsoCode from Opportunity where Id = :oppid];
                if (oppl.size() > 0) {
                    quo.IraiSubject__c = oppl[0].Account.Name;
                    quo.Account__c = oppl[0].AccountId;
                    quo.IraiName__c = oppl[0].Name ;
                    //更新币种相同 wql
                    //quo.CurrencyIsoCode = oppl[0].CurrencyIsoCode;

                }
                //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                List<Quote> ql =  [select Id,OpportunityId From Quote Where OpportunityId =:oppId];
                // 不经存在报价
                if (ql.size() <= 0){
                    // CHAN-BHNBX6 2019/11/20 START
                    List<OpportunityLineItem> olis = [Select Id,Quantity,PricebookEntry.Product2Id,CurrencyIsoCode,GuaranteePeriod__c From OpportunityLineItem Where OpportunityId =:oppId Order by Item_Order__c, Id];
                    // CHAN-BHNBX6 2019/11/20 END
                    List<String> productids = new List<String>();
                    for (OpportunityLineItem oli : olis) {
                        productids.add(oli.PricebookEntry.Product2Id);
                    }
                    // 商品最新信息取得
                    Map<Id, Product2> items = new Map<Id, Product2>();
                    // CHAN-BHNBX6 2019/11/20 START
                    //2021/1/5 liying start NoDiscount_Foreign__c
                    List<Product2> products = [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,Sales_Possibility__c,Estimation_Entry_Possibility__c,NoDiscount_Foreign__c,
                            SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Entend_gurantee_period_all__c,Intra_Trade_Service_RMB__c
                            FROM Product2 Where Id IN :productIds
                            And Manual_Entry__c = false];
                    //2021/1/5 liying END
                    // CHAN-BHNBX6 2019/11/20 END
                    for (Product2 product : products) {
                        items.put(product.Id, product);
                    }
                    
                    // 明细行做成
                    for (Integer j = 0; j < olis.size(); j++) {
                        OpportunityLineItem oli = olis[j];
                        Product2 p = items.get(oli.PricebookEntry.Product2Id);
                        Integer Quantity_c = oli.Quantity > 0 ? Integer.valueOf(oli.Quantity) : 1;
                        // CHAN-BHNBX6 2019/11/20 START
                        //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                        //更新币种相同 wql
                        //quo.CurrencyIsoCode = oli.CurrencyIsoCode;
                        //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                        //2021/1/5 liying start NoDiscount_Foreign__c
                        if (oli.CurrencyIsoCode == 'USD') {
                            activities[j] = new QELine(j, null, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                       Quantity_c, p.Foreign_Trade_List_US__c, p.Foreign_Trade_List_US__c, p.Foreign_Trade_Cost_US__c,p.Entend_gurantee_period_all__c,p.NoDiscount_Foreign__c);
                        } else if (oli.CurrencyIsoCode == 'CNY') {
                            activities[j] = new QELine(j, null, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                       Quantity_c, p.Intra_Trade_List_RMB__c, p.Intra_Trade_List_RMB__c, p.Intra_Trade_Cost_RMB__c,p.Entend_gurantee_period_all__c,p.Intra_Trade_Service_RMB__c);
                        } else {
                            activities[j] = new QELine(j, null, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                       Quantity_c, 0, 0, 0,p.Entend_gurantee_period_all__c,0);
                        }
                        //2021/1/5 liying END
                        // CHAN-BHNBX6 2019/11/20 END
                    }
                } else {
                    // 已经存在报价
                    if (String.isNotBlank(oppquoid)) {
                        //DB202302464682【报价委托】报价委托改善224 fy start
                        Quote quo2 = new Quote();
                        List<Quote> quote =  [select Id,Agency1__c,Agency2__c From Quote Where Id =:oppquoid];
                        if(quote.size()>0){
                            quo2=quote[0];
                        }
                        quo.Agency1_entrust__c = quo2.Agency1__c;
                        quo.Agency2_entrust__c = quo2.Agency2__c;
                        //DB202302464682【报价委托】报价委托改善224 fy end
                        // 报价商品取得
                        // CHAN-BHNBX6 2019/11/20 START//fy lastbuy 20220310 PricebookEntry.Product2.LastbuyProductFLG__c
                        List<QuoteLineItem> qlis = [select id,PricebookEntry.Product2Id,PricebookEntry.Product2.LastbuyProductFLG__c,Quantity__c,CurrencyIsoCode,GuaranteePeriod__c from QuoteLineItem where QuoteId = :oppquoid];
                        // CHAN-BHNBX6 2019/11/20 END
                        List<String> productids = new List<String>();
                        for (QuoteLineItem qli : qlis) {
                            productids.add(qli.PricebookEntry.Product2Id);
                        }
                        // 商品最新信息取得
                        Map<Id, Product2> items = new Map<Id, Product2>();
                        // CHAN-BHNBX6 2019/11/20 START
                        //liying 2021/01/06 start
                        List<Product2> products = [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,Sales_Possibility__c,Estimation_Entry_Possibility__c,
                                SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Entend_gurantee_period_all__c,Intra_Trade_Service_RMB__c,NoDiscount_Foreign__c
                                FROM Product2 Where Id IN :productIds
                                And Manual_Entry__c = false];
                                  //liying 2021/01/06 end
                        // CHAN-BHNBX6 2019/11/20 END
                        for (Product2 product : products) {
                            items.put(product.Id, product);
                        }
                        // 明细行做成
                        for (Integer j = 0; j < qlis.size(); j++) {
                            QuoteLineItem qli = qlis[j];
                            Product2 p = items.get(qli.PricebookEntry.Product2Id);
                            Integer Quantity_c = qli.Quantity__c > 0 ? Integer.valueOf(qli.Quantity__c) : 1;
                            // CHAN-BHNBX6 2019/11/20 START
                            //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                            //更新币种相同 wql
                            //quo.CurrencyIsoCode = qli.CurrencyIsoCode;
                            //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                             //2021/1/5 liying start NoDiscount_Foreign__c
                            if (qli.CurrencyIsoCode == 'USD') {
                                activities[j] = new QELine(j, qli.PricebookEntryId, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                           Quantity_c, p.Foreign_Trade_List_US__c, p.Foreign_Trade_List_US__c, p.Foreign_Trade_Cost_US__c,p.Entend_gurantee_period_all__c,p.NoDiscount_Foreign__c);
                            } else if (qli.CurrencyIsoCode == 'CNY') {
                                activities[j] = new QELine(j, qli.PricebookEntryId, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                           Quantity_c, p.Intra_Trade_List_RMB__c, p.Intra_Trade_List_RMB__c, p.Intra_Trade_Cost_RMB__c,p.Entend_gurantee_period_all__c,p.Intra_Trade_Service_RMB__c);
                            } else {
                                activities[j] = new QELine(j, qli.PricebookEntryId, p.Asset_Model_No__c, p.ProductCode, p.Id, p.SFDA_Status__c, p.Sales_Possibility__c, p.Name, p.BSSCategory__c,
                                                           Quantity_c, 0, 0, 0,p.Entend_gurantee_period_all__c,0);
                            }
                             //2021/1/5 liying end
                            // CHAN-BHNBX6 2019/11/20 END
                        }
                    }
                }
            } else if (String.isNotBlank(leadid)) {
                // 购买意向信息
                List<Lead> leadl = [select Id,Hospital_Name__c,Hospital_Name__r.Name from Lead where Id = :leadid];
                if (leadl.size() > 0) {
                    quo.IraiSubject__c = leadl[0].Hospital_Name__r.Name;
                    quo.Account__c = leadl[0].Hospital_Name__c;
                }
            }
            // 经销商询价报价委托 2020-02-28 update by vivek start 
            else if(String.isNotBlank(agencyoppid)) {
                // 经销商询价
                List<Agency_Opportunity__c> agencyOppL = [select id,Agency_Hospital__c,Agency_Hospital__r.Name,Department_Cateogy__c,Department_Name_Text__c from Agency_Opportunity__c where Id = :agencyoppid];
                if(agencyOppL.size() > 0){
                    String department = agencyOppL[0].Department_Cateogy__c;
                    String departmentE = '';
                    if(department == 'BF'){
                        departmentE = '呼吸科';
                    }
                    if(department == 'ENT'){
                        departmentE = '耳鼻喉科';
                    }
                    if(department == 'ET'){
                        departmentE = 'ET耗材';
                    }
                    if(department == 'GI'){
                        departmentE = '消化科';
                    }
                    if(department == 'GS'){
                        departmentE = '普外科';
                    }
                    if(department == 'GYN'){
                        departmentE = '妇科';
                    }
                    if(department == 'OTH'){
                        departmentE = '其他';
                    }
                    if(department == 'URO'){
                        departmentE = '泌尿科';
                    }
                    if(agencyOppL[0].Department_Name_Text__c == null){
                        agencyOppL[0].Department_Name_Text__c = '';
                    }
                    quo.IraiSubject__c = agencyOppL[0].Agency_Hospital__r.Name+' '+departmentE+' '+agencyOppL[0].Department_Name_Text__c;
                    quo.Agency_Hospital_Link__c = agencyOppL[0].Agency_Hospital__c;
                }
            }
            // 经销商询价报价委托 2020-02-28 update by vivek end

            // 招投标报价委托 2021-06-21 update by gzw start
            else if(String.isNotBlank(tenderid)) {
                // 经销商询价
                List<Tender_information__c> tenderL = [select id,Hospital__c,Hospital__r.Name from Tender_information__c where Id = :tenderid];
                if(tenderL.size() > 0){
                    quo.IraiSubject__c = tenderL[0].Hospital__r.Name;
                    quo.Tender_information__c = tenderL[0].Id;
                    quo.Account__c = tenderL[0].Hospital__c;
                }
            }
            // 招投标报价委托 2021-06-21 update by gzw end
        }else{
            // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
            List<QuoteIrai__c> quoList = //obsap 新增经销商1字段 fy satrt Agency1_entrust__c ,SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start cancelMultiyearInsurance__c,
                [ SELECT Id,Name,Cancel_Decide__c,Agency_Hospital_Link__c,CreatedDate, PriceRefreshDate__c,Quote_Print_Date__c,Agency1_entrust__c,cancelMultiyearInsurance__c,
                        Quote_Date__c,QuoteToName__c,Quote_Expiration_Date__c,Quote_Comment__c,Tender_information__c,Noteplus__c,Lead__c,Opportunity__c,
                        TOTAL__c,Discount__c,Pricing__c,Preferential_Trading_Price__c,Contract__c,LastIraiUser__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,
                        Agency2_entrust__c,//DB202302464682【报价委托】报价委托改善224 fy
                        Print_HP_Name__c,Account__c,IraiUser__c,IraiSubject__c,CurrencyIsoCode,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                        , urgent__c  //20230104 lt DB202212427301
                        FROM QuoteIrai__c Where Id =:quoId];
            // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
            // CHAN-BHNBX6 2019/11/20 START
            List<QuoteIraiLineItem__c> items = //lastbuy  2022/3/10 fy start LastbuyProductFLG__c //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start Is_DangerousChemicals__c,CanNotCancelledGurantee__c
                [Select Id,Asset_Model_No__c,SFDA_Status__c,Name__c,BSS_Category__c,QuoteIrai__r.Quote_Print_Date__c,
                    Qty_Unit__c,Quantity__c,Product2__r.SFDA_Status__c,ProductCode__c,ListPrice__c,Product2__r.LastbuyProductFLG__c,Product2__r.Is_DangerousChemicals__c,CanNotCancelledGurantee__c,
                    Product2__r.Sales_Possibility__c,Product2__r.Name,Product2__c,ServicePrice__c,NoDiscountTotal__c,GuaranteePeriod__c
                    From QuoteIraiLineItem__c where QuoteIrai__c = :quoId Order by Item_Order__c, Id];
            // CHAN-BHNBX6 2019/11/20 END
            String copyQuoId = System.currentPageReference().getParameters().get('copyid');
            
            if (copyQuoId == null) {
            } else {
                // copyの場合、quoIdをnullに戻す
                quoId = null;
            }
            if (quoList.size() > 0){
                if (copyQuoId == null) {
                    //system.debug('进到这里了1----');
                    quo = quoList[0];
                    //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                    // system.debug('进到这里了2----');
                    // if(oppList.size()>0){
                    //     quo.CurrencyIsoCode = oppList[0].CurrencyIsoCode;
                    // }
                    //注释原逻辑 wql
                    //quo.CurrencyIsoCode = 'CNY';
                    //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                } else {
                    //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 start
                    // system.debug('进到这里了2----');
                    // if(oppList.size()>0){
                    //     quo.CurrencyIsoCode = oppList[0].CurrencyIsoCode;
                    // }
                    //注释原逻辑 wql
                    quo.CurrencyIsoCode = 'CNY';
                    //将报价委托的币种与外贸币种一致 防止后续外贸有需要用USD判断显示的地方 精琢技术 wql 2021/01/06 end
                    quo.Cancel_Decide__c = false;
                    quo.IraiSubject__c = '';
                    quo.Account__c = null;
                    quo.IraiName__c = '';
                    quo.QuoteProportion__c = 0;
                    quo.PriceRefreshDate__c = Date.today();
                    quo.Quote_Date__c = null;
                    quo.Quote_Print_Date__c = null;
                    quo.Note__c = '';
                    quo.IraiComment__c = '';
                }
                // CHAN-BJQ4VZ 精琢技术 2019/12/10 Start 
                system.debug('标准价格：'+quo.Estimation_List_Price__c);
                 qb.Estimation_List_Price = quo.Estimation_List_Price__c;
                 qb.QuoteTotal_Page = quo.QuoteTotal_Page__c;
                 qb.MultiYearWarrantyTotalPrice  = quoList[0].MultiYearWarrantyTotalPrice__c;
                // CHAN-BJQ4VZ 精琢技术 2019/12/10 End

            }

            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 (QuoteIraiLineItem__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<quoteEntryMaxLine;j++){
                    c = new QELine(j);
                    activities.add(c);
                }
                //マスタ最新情報の取得
                settingProduct2();
            }else{
                activities = new List<QELine>();
                for (i=0;i<quoteEntryMaxLine;i++){
                    QELine active_activity = new QELine(i);
                    activities.add(active_activity);
                }
            }
        }

        if (quo.Quote_Expiration_Date__c==null){
            quo.Quote_Expiration_Date__c = Date.today() + 30;
        }
        //--Savebutton
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        this.Save_button=false;
        if(quo.QuoteIrai_Status__c != '草案中'&& String.isNotBlank(quo.QuoteIrai_Status__c)){
            this.Save_button=true;
        }
        // Save_button=true;
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
        system.debug('===fff==='+quo.QuoteIrai_Status__c);
        system.debug('===ccc==='+this.Save_button);
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
        // if( quo.Note__c!=''){
        if(String.isNotBlank(quo.Note__c)){
            system.debug('===111==='+quo.Note__c.split('\r\n'));
            List<String> str=quo.Note__c.split('\r\n');
            if(str.size()==1){
                quo.Note__c=''; 
            }else{
                quo.Note__c=str[1]; 
            }
        }
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
        system.debug('===000==='+quo);
        return null;
     }


    //Search Events============================================================
    // TODO ManualEntryと同様、jsにて解決できる、ここでwebserviceだけを実装、今後 by katsu
    public PageReference setProductEntry() {
System.debug('-----:start');
system.debug('○○○○○○○○○○○○○○○Welcome to setProductEntry!!');
system.debug('▼▼▼▼▼setProduct_text:' + setProduct_text);
        List<String> productIDLIST = new List<String>();
        //既存データ数の確認
        Integer currentDetailNumber = 0;
        system.debug('wwwwwwwww:'+activities);
        for (QELine s:activities){
            //データ判定にAsset_Model_Noを使用
            if ((s.Asset_Model==null) || (s.Asset_Model=='')){
                break;
            }
            currentDetailNumber++;
        }

        //既存データ数が150以上？
        if (currentDetailNumber >= quoteEntryMaxLine) {
            PageArrange();
System.debug('-----:強制終了:00');
            return null;
        }

        // SearchSetProductから、セット品コードは渡ってきたか？
        if (setProduct_text == null) {
            // セット品コードが渡ってこなかった場合
            // 終了
            PageArrange();
System.debug('-----:強制終了:01');
            return null;
        }else{
            productIDLIST = setProduct_text.split(',');
        }

        // セット品明細の ProductId一覧を格納する
        // pricebookEntry + product2へのクエリのWhere句で使用する
        List<Id> productIds = null;

        // ----------------------------------------------------------------------------------------
        // 該当するセット品明細のレコードを取得
        // ----------------------------------------------------------------------------------------
System.debug('-----:Product_Set_Detail__c select start');
        List<Product_Set_Detail__c> productSetDetails = [SELECT Id, Product__c, Quantity__c, Product_Set__r.Name FROM Product_Set_Detail__c Where Product_Set__c in :productIDLIST];
System.debug('-----:Product_Set_Detail__c select end');
        if (productSetDetails.size() == 0) {
            PageArrange();
            return null;
        }
        else {
            productIds = new List<Id>();
            for (Product_Set_Detail__c local : productSetDetails) {
                productIds.add(local.Product__c);
            }
        }

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

        //=======Initialize=========
        activities = new List<QELine>();

        boolean lineflg = false;

        // ----------------------------------------------------------------------------------------
        // Product2へのクエリを実行
        // 一度Listで結果を受けた後に、Product2Idの Mapにする
        // ----------------------------------------------------------------------------------------
System.debug('-----:Product2 select start');
        Map<Id, Product2> items = new Map<Id, Product2>();
        List<Product2> products = [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,Sales_Possibility__c,Estimation_Entry_Possibility__c,NoDiscount_Foreign__c,
                SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Entend_gurantee_period_all__c,Intra_Trade_Service_RMB__c
                FROM Product2 Where Id IN :productIds
                And Manual_Entry__c = false];
        for (Product2 product : products) {
            items.put(product.Id, product);
        }
System.debug('-----:Product2 select end');
System.debug('-----:PricebookEntry select start');
        Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>();
        List<PricebookEntry> workEntries = [
                SELECT Id,Product2Id
                FROM PricebookEntry Where Product2Id IN :productIds
                AND CurrencyIsoCode = :quo.CurrencyIsoCode
                AND IsActive = true
        ];
        for (PricebookEntry workEntry : workEntries) {
            entries.put(workEntry.Product2Id, workEntry);
        }
System.debug('-----:PricebookEntry select end');

        // ----------------------------------------------------------------------------------------
        // 画面の明細行のループ
        // ----------------------------------------------------------------------------------------
        Integer i = 0;
        Integer rightcnt = 0; // 成功した数をカウント
        for (QELine t:tmpactivities){

            QELine a = New QELine(i);

System.debug('-----:i=' + i + ', currentDetailNumber=' + currentDetailNumber);

            if (i == currentDetailNumber) {
                // ----------------------------------------------------------------------------------------
                // 一回だけ実行されるコード
                // ----------------------------------------------------------------------------------------
System.debug('-----:items.size()=' + items.size());
                if (items.size() > 0) {
                    // ----------------------------------------------------------------------------------------
                    // セット品明細のループ
                    // ----------------------------------------------------------------------------------------
System.debug('-----:セット品明細のループスタート');
                    for (Integer l = 0; l < productSetDetails.size(); l++) {
                        Product_Set_Detail__c nowDetail = productSetDetails[l];
                        Product2 prd = items.get(nowDetail.product__c);
                        PricebookEntry pbe = entries.get(nowDetail.product__c);

                        Schema.DescribeFieldResult dfr = QuoteIraiLineItem__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;
                            }
                        }

                        if (pbe == null) {
system.debug('This Productid(' + nowDetail.product__c +  ') is not exist PricebookEntry');
                            // ----------------------------------------------------------------------------------------
                            // 取得済みの Product2のリストの中に、セット品明細の情報がみつからない場合
                            // なにもしないでスルーする
                            // ----------------------------------------------------------------------------------------
                        }
                        else {
                            // ----------------------------------------------------------------------------------------
                            // 取得済みの Product2のリストの中に、セット品明細の情報がみつかった
                            // 明細のその Product2の情報をセットする？
                            // ----------------------------------------------------------------------------------------
                            QELine c = null;
                            Integer Quantity_c = nowDetail.Quantity__c > 0 ? Integer.valueOf(nowDetail.Quantity__c) : 1;
                            system.debug('quo.CurrencyIsoCode:+++++++++'+quo.CurrencyIsoCode);
                            // CHAN-BHNBX6 2019/11/20 START
                            //2021/01/08 liying start
                            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.ProductCode, nowDetail.product__c, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                            Quantity_c, price, price, prd.Foreign_Trade_Cost_US__c,prd.Entend_gurantee_period_all__c,prd.NoDiscount_Foreign__c);
                                } else {
                                    continue;
                                }
                            } else if (quo.CurrencyIsoCode == 'CNY') {
                                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.ProductCode, nowDetail.product__c, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                            Quantity_c, price, price, prd.Intra_Trade_Cost_RMB__c,prd.Entend_gurantee_period_all__c,prd.Intra_Trade_Service_RMB__c);
                                } else {
                                    continue;
                                }
                            } else {
                                continue;
                                // c = new QELine(i, pbe.Id, prd.Asset_Model_No__c, prd.ProductCode, nowDetail.product__c, prd.SFDA_Status__c, prd.Sales_Possibility__c, prd.Name, prd.BSSCategory__c,
                                //        Quantity_c, 0, 0, 0);
                            }
                            //2021/01/08 liying end

                            // CHAN-BHNBX6 2019/11/20 END
                            activities.add(c);

                            if (i == 149) {
                                // 明細行の最大値に達したら、処理を終了する
                                PageArrange();
System.debug('-----:強制終了:98');
                                return null;
                            }

                            i++;
                            rightcnt++;
                            lineflg = true;
                        }
                    }
System.debug('-----:セット品明細のループ終了');
                    if (lineflg==true){
                        i--;
                    }
                }
                else {
                    // ----------------------------------------------------------------------------------------
                    // Product2へのクエリが結果を返さなかった時に実行されるコード
                    // ----------------------------------------------------------------------------------------
                    a = t;
                    a.lineNo = i;
                    activities.add(a);
                }
            }
            else {
                // ----------------------------------------------------------------------------------------
                // Product2へクエリを投げない時に実行されるコード
                // ----------------------------------------------------------------------------------------
                a = t;
                a.lineNo = i;
                activities.add(a);
            }

            i++;
            if (i > 149) {
                break;
            }
        }

        PageArrange();
        if (productSetDetails.size() > 0) {
            errorflg = true;
            errormessage = productSetDetails[0].Product_Set__r.Name + ' 导入结束，导入 ' + productSetDetails.size() + ' 件，成功' + rightcnt + ' 件';
        }
system.debug('-----:終了:' + errormessage);
        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>quoteEntryMaxLine){
            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です。
                //2021/01/07 liying start excel导入按钮
                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,Sales_Possibility__c,Estimation_Entry_Possibility__c,NoDiscount_Foreign__c,
                        SFDA_Status__c,Qty_Unit__c,BSSCategory__c,Entend_gurantee_period_all__c,Intra_Trade_Service_RMB__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 = QuoteIraiLineItem__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')) {
                            // CHAN-BHNBX6 2019/11/20 START
                            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.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.Entend_gurantee_period_all__c,prd.NoDiscount_Foreign__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.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.Entend_gurantee_period_all__c,prd.Intra_Trade_Service_RMB__c);
                                } else {
                                    continue;
                                }
                            }
                            // CHAN-BHNBX6 2019/11/20 END
                            //2021/01/07 liying end
                        } else {
                            continue;
                            // c = new QELine(i, pbe.Id, prd.Asset_Model_No__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============================================================

    //irai button
    public PageReference quoteIrai(){
        List<String> productidList = new List<String>();
        Map<String,String> productCodeMap = new Map<String,String>();
        system.debug('○○○○○○○○○○○○○○○Welcome to QuoteIraiButton!!');
        
        System.debug('quo.Agency_Hospital_Link__c======'+quo.Agency_Hospital_Link__c);
        // System.debug('quo.IraiUser__c======'+quo.IraiUser__r.ProfileId);
        if (quo.IraiUser__c == null) {
            errorflg = true;
            errorMessage = '请选择委托人员。';
            pageArrange();
            return null;
        }
        // 经销商询价报价委托 2020-02-28 update by vivek start
        // 经销商询价报价委托验证委托人必须为营业助理
        if(!String.isBlank(quo.Agency_Hospital_Link__c)){
            userProfileId = new Map<Id,Id>();
            userProfileId.put('00e10000000xnpRAAQ', '00e10000000xnpRAAQ');
            userProfileId.put('00e10000000xyK6AAI', '00e10000000xyK6AAI');
            List<User> userProL = [select id,ProfileId from User where id = :quo.IraiUser__c];
            System.debug('userProL[0].ProfileId======'+userProL[0].ProfileId);
            if(!userProfileId.containsKey(userProL[0].ProfileId)){
                errorflg = true;
                errorMessage = '委托人员只能为营业助理';
                pageArrange();
                return null;
            }
        }
        
        // 经销商询价报价委托 2020-02-28 update by vivek end
        list<String> descriptions = 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);
                }
            }
        }
        Product2[] pro = [select Id,ProductCode from Product2 where Id in :productidList];
        for (Product2 p : pro) {
            productCodeMap.put(p.id,p.ProductCode);
        }
        if (activities.size()>0){
            for (QELine a:activities){
                String productid = a.PageObject.Product2__c;
                if (productid != null && productid.trim().length() > 0) {
                    descriptions.add(productCodeMap.get(productid) + '\t' + a.pageObject.Quantity__c);
                }
            }
        }
        // System.debug('---lt123---descriptions---'+descriptions);
        if (descriptions.size() <= 0) {
            errorflg = true;
            errorMessage = '没有要委托的产品。';
            pageArrange();
            return null;
        }
        Savepoint sp = Database.setSavepoint();
        try {
            //データチェック
            if (dataCheck() ==false){
                return null;
            }
            if (dataEntry()==false){
                return null;
            }
            
            String description = '';
            //20230116 fy start
            String descriptionsendEmailp = '';
            String descriptionsendEmailbody = '';
            //20230116 fy end
            Integer i = 1;
            for (String d : descriptions) {
                if (i == 1) {
                    description += d;
                    //20230116 fy start
                    descriptionsendEmailp += d;
                    //20230116 fy end
                } else {
                    description += '\r\n' + d;
                    //20230116 fy start
                    descriptionsendEmailp += '\r\n' + d;
                    //20230116 fy end
                }
                i += 1;
            }
            // System.debug('---lt123---description---'+description);
            //obsap 新增经销商1字段 fy start
            if (!String.isBlank(quo.Agency1_entrust__c)) {
                Account  quoteAeName = [select Id,Name from Account where Id =:quo.Agency1_entrust__c];
                description += '\r\n' + '第一经销商名称' + '：' + quoteAeName.Name;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '第一经销商名称' + '：' + quoteAeName.Name;
                //20230116 fy end
            }
            //DB202302464682【报价委托】报价委托改善224 fy start
            if (!String.isBlank(quo.Agency2_entrust__c)) {
                Account  quoteAeName2 = [select Id,Name from Account where Id =:quo.Agency2_entrust__c];
                description += '\r\n' + '第二经销商名称' + '：' + quoteAeName2.Name;
                descriptionsendEmailbody += '\r\n' + '第二经销商名称' + '：' + quoteAeName2.Name;
            }
            //DB202302464682【报价委托】报价委托改善224 fy end
            if (quo.QuoteProportion__c!=null) {
                description += '\r\n' + '报价比例' + '：' + quo.QuoteProportion__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '报价比例' + '：' + quo.QuoteProportion__c;
                //20230116 fy end
            }
            if (!String.isBlank(quo.IraiComment__c)) {
                description += '\r\n' + '报价备注' + '：' + quo.IraiComment__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '报价备注' + '：' + quo.IraiComment__c;
                //20230116 fy end
            }
            //obsap 新增经销商1字段 fy end
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
            String node;
            if(!String.isBlank(quo.Note__c)){
                node=quo.Noteplus__c+'\r\n'+quo.Note__c;
            }else{
                node=quo.Noteplus__c;
            }
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
            if (!String.isBlank(node)) {
                //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
                description += '\r\n' + node;
                //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
                // description += '\r\n' + quo.Note__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + node;
                //20230116 fy end
            }
            if (!String.isBlank(quo.Account__c)) {
                description += '\r\n' + Account.sObjectType.getDescribe().getLabel() + '：' + baseUrl + '/' + quo.Account__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + Account.sObjectType.getDescribe().getLabel() + '：' + baseUrl + '/' + quo.Account__c;
                //20230116 fy end
            }
            // 经销商询价报价委托 2020-02-28 update by vivek start
            if (!String.isBlank(quo.Agency_Hospital_Link__c)) {
                description += '\r\n' + Agency_Hospital_Link__c.sObjectType.getDescribe().getLabel() + '：' + baseUrl + '/' + quo.Agency_Hospital_Link__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + Agency_Hospital_Link__c.sObjectType.getDescribe().getLabel() + '：' + baseUrl + '/' + quo.Agency_Hospital_Link__c;
                //20230116 fy end
            }
            // 经销商询价报价委托 2020-02-28 update by vivek end
            //obsap 新增经销商1字段 fy start
            if (!String.isBlank(quo.Agency1_entrust__c)) {
                description += '\r\n' + '第一经销商' + '：' + baseUrl + '/' + quo.Agency1_entrust__c;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '第一经销商' + '：' + baseUrl + '/' + quo.Agency1_entrust__c;
                //20230116 fy end
            }
            //DB202302464682【报价委托】报价委托改善224 fy start
            if (!String.isBlank(quo.Agency2_entrust__c)) {
                description += '\r\n' + '第二经销商' + '：' + baseUrl + '/' + quo.Agency2_entrust__c;
                descriptionsendEmailbody += '\r\n' + '第二经销商' + '：' + baseUrl + '/' + quo.Agency2_entrust__c;
            }
            //DB202302464682【报价委托】报价委托改善224 fy end
            //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            if (!String.isBlank(tenderid)&&!description.contains('招标项目') ) {
                description += '\r\n' + '招标项目' + '：' + baseUrl + '/' + tenderid;
                //20230116 fy start
                descriptionsendEmailbody += '\r\n' + '招标项目' + '：' + baseUrl + '/' + tenderid;
                //20230116 fy end
            }
            //SWAG-CKDATG【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
            //obsap 新增经销商1字段 fy end
            // 招投标报价委托 2020-06-21 update by gzw start
            // if (!String.isBlank(quo.Tender_information__c)) {
            //     description += '\r\n' + Tender_information__c.sObjectType.getDescribe().getLabel() + '：' + baseUrl + '/' + quo.Tender_information__c;
            // }
            // 招投标报价委托 2020-06-21 update by gzw end
            // obsap 委托人按公共小组区分，检索数量增加 2022-05-09 ssm start
            List<String> irai_userids = new List<String>();
            // if (loginUser != null && String.isNotBlank(loginUser.Salesdepartment_text__c) && (loginUser.Salesdepartment_text__c == '5.华东' || loginUser.Salesdepartment_text__c == '6.华南')) {
            //fy 20220512
            if (loginUser != null && String.isNotBlank(loginUser.Salesdepartment_text__c) && obsflag) {

                // obsflag = true;
                // String obsap_group_id = System.Label.obsap_group_opp;
                // List<GroupMember> members =  [SELECT Id, GroupId, UserOrGroupId FROM GroupMember where GroupId = :obsap_group_id];
                // system.debug('members++'+members);
                // if (members != null && members.size() > 0) {
                //     for (GroupMember member : members) {
                        // irai_userids.add(member.UserOrGroupId);
                //     }
                // }
                irai_userids.add(System.Label.obsap_group_opp);
            }else{
                irai_userids.add(quo.IraiUser__c);
            }
            // 把委托上绑定的人加到list里
            //20220512 lt add
            // Map<String,String> iuMap = new Map<String,String>();
            // for(String iu : irai_userids){
            //     iuMap.put(iu,iu);
            // }
            // if(!iuMap.containsKey(quo.IraiUser__c)){
            //     irai_userids.add(quo.IraiUser__c);
            // } 
            //irai_userids.add(quo.IraiUser__c);
            // Task[] tasks = [select Id,Subject,OwnerId,Description,ActivityDate,QuoteIraiId__c
            //                 from Task
            //                 where QuoteIraiId__c = :quoId and OwnerId = :quo.IraiUser__c];
            Task[] tasks = [select Id,Subject,OwnerId,Description,ActivityDate,QuoteIraiId__c
                            from Task
                            where QuoteIraiId__c = :quoId and OwnerId in :irai_userids];
            //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start      
            List<String>  HeadquartersArray= quo.Headquarters__c.split('\\.');
            String Headquarters = '';
            if(HeadquartersArray.size()>0){
                Headquarters = HeadquartersArray.size()>=2 ? HeadquartersArray[1]:HeadquartersArray[0];
            }
            // String todoSubject = '报价委托：' + quo.IraiSubject__c;
            String todoSubject = Headquarters+'报价委托：' + quo.IraiSubject__c;
            //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
            // 20230104 lt DB202212427301 start
            if(quo.Urgent__c){
                todoSubject = '【紧急】' + todoSubject;
            }
            
            // 20230104 lt DB202212427301 end
            if (!String.isBlank(quo.IraiName__c)) {
                todoSubject += '， ' + quo.IraiName__c;
            }
            if (!String.isBlank(quo.IraiComment__c)) {
                todoSubject += '， ' + quo.IraiComment__c;
            }
            if (quo.QuoteProportion__c != null) {
                todoSubject += '， ' + quo.QuoteProportion__c + '%';
            }
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            todoSubject += quo.cancelMultiyearInsurance__c=='不要' ?'，取消多年保':'，需要多年保';
            // if (quo.cancelMultiyearInsurance__c=='不要') {
            //     todoSubject += '，取消多年保';
            // }else{
            //     todoSubject += '，需要多年保';
            // }
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
            // String taskid = '';
            // 改成对多人的
            // if (tasks.size() > 0) {
            //     Task task = tasks[0];
            //     task.Subject = todoSubject;
            //     task.Description = description;
            //     task.ActivityDate = Date.today();
                
            //     Database.DMLOptions dmlo = new Database.DMLOptions();
            //     dmlo.EmailHeader.triggerUserEmail = true;
            //     Database.update(task, dmlo);
            //     taskid = task.Id;
            // } else {
            //     Task task = new Task();
            //     task.Subject = todoSubject;
            //     task.OwnerId = quo.IraiUser__c;
            //     task.Description = description;
            //     task.ActivityDate = Date.today();
            //     task.QuoteIraiId__c = quoId;
                
            //     Database.DMLOptions dmlo = new Database.DMLOptions();
            //     dmlo.EmailHeader.triggerUserEmail = true;
            //     Database.insert(task, dmlo);
            //     taskid = task.Id;
            // }
            List<String> new_task_users = new List<String>();
            //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
            List<String> taskIdL = new List<String>();
            //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
            if (tasks.size() > 0) {
                List<String> task_users = new List<String>();
                for (Task task : tasks) {
                    task_users.add(task.OwnerId);
                    //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
                    taskIdL.add(task.Id);
                    //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
                    task.Subject = todoSubject;
                    task.Description = description;
                    task.ActivityDate = Date.today();
                }
                //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
                // Database.DMLOptions dmlo = new Database.DMLOptions();
                // dmlo.EmailHeader.triggerUserEmail = true;
                // Database.update(tasks, dmlo);
                update tasks;
                if(taskIdL.size()>0){
                    sendEmail(todoSubject,descriptionsendEmailp,descriptionsendEmailbody,taskIdL[0],Headquarters);
                }
                //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
                for (String uid : irai_userids) {
                    if (!task_users.contains(uid)) {
                        new_task_users.add(uid);
                    }
                }

            } else {
                new_task_users = irai_userids;
            }
            if (new_task_users.size() > 0) {
                List<Task> new_tasks = new List<Task>();
                for (String uid : new_task_users) {
                    Task new_task = new Task();
                    new_task.Subject = todoSubject;
                    new_task.OwnerId = uid;
                    new_task.Description = description;
                    new_task.ActivityDate = Date.today();
                    new_task.QuoteIraiId__c = quoId;
                    // 20230109 lt DB202212427301 start
                    if(quo.Urgent__c){
                        new_task.Priority = '高';
                    }
                    // 20230109 lt DB202212427301 start

                    new_tasks.add(new_task);
                }
                system.debug('new_tasks++'+new_tasks);
                //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
                // Database.DMLOptions dmlo = new Database.DMLOptions();
                // dmlo.EmailHeader.triggerUserEmail = true;
                // Database.insert(new_tasks, dmlo);
                insert new_tasks;
                sendEmail(todoSubject,descriptionsendEmailp,descriptionsendEmailbody,new_tasks[0].Id,Headquarters);
                //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end
            }
            // obsap 委托人按公共小组区分，检索数量增加 2022-05-09 ssm end
            
            User u = [select Id,Name from user where Id = :quo.IraiUser__c];
            quo.LastIraiUser__c = u.Name;
            QuoteIrai__c qi = new QuoteIrai__c(Id = quoId);
            qi.LastIraiUser__c = quo.LastIraiUser__c;
            qi.Urgent__c = quo.Urgent__c;     //20230104 lt DB202212427301 shart
            //报价委托状态更新  已经委托
            qi.QuoteIrai_Status__c = '已经委托';
            //DB202211607582 fy 【报价委托】报价委托页面需求 start
            qi.EntrustmentDate__c = Date.today();
            //DB202211607582 fy 【报价委托】报价委托页面需求 end
            update qi;

            if(String.isNotBlank(quoId)){
                // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
                quo =[ SELECT Id,Name,Cancel_Decide__c,CreatedDate, PriceRefreshDate__c,Quote_Print_Date__c,//obsap 新增经销商1字段 fy satrt Agency1_entrust__c,SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start cancelMultiyearInsurance__c,
                        Quote_Date__c,QuoteToName__c,Quote_Expiration_Date__c,Quote_Comment__c,Tender_information__c,Agency1_entrust__c,Noteplus__c,Lead__c,Opportunity__c,cancelMultiyearInsurance__c,
                        TOTAL__c,Discount__c,Pricing__c,Preferential_Trading_Price__c,Contract__c,LastIraiUser__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,Agency2_entrust__c,//DB202302464682【报价委托】报价委托改善224 fy
                        Print_HP_Name__c,Account__c,Agency_Hospital_Link__c,IraiUser__c,IraiSubject__c,CurrencyIsoCode,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                        , urgent__c  //20230104 lt DB202212427301
                        FROM QuoteIrai__c Where Id =:quoId];
                // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
            }

            // 招投标报价委托 2020-06-21 update by gzw start
            if (!String.isBlank(quo.Tender_information__c)) {
                Tender_information__c tender = new Tender_information__c(Id = quo.Tender_information__c);
                tender.QuoteIrai__c = quoId;
                update tender;
            }
            // 招投标报价委托 2020-06-21 update by gzw end
            errorflg = true;
            errorMessage = '邮件发送完成。';
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            this.Save_button=true;
            //XLIU-CHY4KW 20220907 lt start  --- 报价委托发送邮件成功之后 反向更新意向  报价委托字段为1
            Lead lea = new Lead();
            if(String.isNotBlank(leadid)){
                lea.Id = leadid;
                lea.OfferToEntrust__c = 1;
                //20230227 lt DB202302251962 start
                List<Lead> leadlist = [select Id,Firsttime_Quote_Irai__c from Lead where Id = :leadid];
                System.debug('lt123日期1'+ leadlist[0].Firsttime_Quote_Irai__c);
                System.debug('lt123日期2'+ lea.Firsttime_Quote_Irai__c);
                if(leadlist.size() > 0){
                    if(leadlist[0].Firsttime_Quote_Irai__c == null){
                        lea.Firsttime_Quote_Irai__c = Date.today();
                    }
                }
                //20230227 lt DB202302251962 end
                update lea;
            }
            //XLIU-CHY4KW 20220907 lt end  

            pageArrange();
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
            // if(quo.Note__c!=''){
            if(String.isNotBlank(quo.Note__c)){
                system.debug('===555==='+quo.Note__c.split('\r\n'));
                List<String> str=quo.Note__c.split('\r\n');
                if(str.size()==1){
                    quo.Note__c=''; 
                }else{
                    quo.Note__c=str[1]; 
                }
            }
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
            return null;
            //报价委托状态更新  已经委托
        } 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;
    }

    public String getoppId(){
        String opptext = null;
        if(String.isNotBlank(quoId)){
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
            QuoteIrai__c getnote = [ SELECT Id,Name,Note__c,Noteplus__c,Lead__c,Opportunity__c FROM QuoteIrai__c Where Id =:quoId];
            if(String.isNotBlank(getnote.Note__c) && getnote.Note__c.indexOf( 'com/') > 0){
                opptext = getnote.Note__c.SubString(getnote.Note__c.LastIndexOf('/')+1,getnote.Note__c.LastIndexOf('/')+16);
            }
        }
        return opptext;
    }
    //Save button
    public PageReference Save(){

        errorflg = false;
        errormessage = null;
        Savepoint sp = Database.setSavepoint();
        try {
            //データチェック
            if (dataCheck() ==false){
                return null;
            }
            
            if (dataEntry()==false){
                //msg
                return null;
            }else{
                //msg
                errorflg = true;
                errorMessage = System.Label.Message_002;
                
                return null;
            }
        } 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){
                //msg
                return null;
            }else{
                //msg
                if(String.isBlank(oppid)){
                    oppid = getoppId();
                }
                if(String.isBlank(oppid)){
                    pageRef = new PageReference('/');
                    return pageRef;
                }else{
                    pageRef = new PageReference('/' +oppid);
                    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(){
        if(String.isBlank(oppid)){
            oppid = getoppId();
        }
        if(String.isBlank(oppid)){
            PageReference pageRef = new PageReference('/');
            return pageRef;
        }else{
            PageReference pageRef = new PageReference('/' +oppid);
            return pageRef;
        }
        //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;
                    // CHAN-BHNBX6 2019/11/20 START
                    a.NoDiscount_Page = null;
                    a.NoDiscountTotal_Page = null;
                    a.pageObject.GuaranteePeriod__c = null;
                    // CHAN-BHNBX6 2019/11/20 END
                } else {
system.debug('○○○○○○○○○○○○Welcome to pageArrange Asset_Model=[' + a.Asset_Model + ']');
                }
            }
        }
    }

    public boolean dataCheck(){
        //20220310 fy lastbuy start 
        // 增加变更用户询价判断
        // if (quoId!=null){
        if (String.isNotBlank(this.oppid) && !is_changed_opp){
            if(!ReservedProductVerification()){
                if(flglastbuy==1){
                  errorflg = true;
                  errormessage =  '预留产品表中没有该询价，请通过本部窗口联系营业管理课' ;
                  return false;
                }else if(flglastbuy==2){
                  errorflg = true;
                  errormessage =  errorProductmodel+'产品数量不可超过产品预留数量' ;
                  return false;
                }else if(flglastbuy==3){
                  errorflg = true;
                  errormessage =  '预留产品'+errorProductmodel+'未录入预留产品表';
                  return false;
                }
                // else if(flglastbuy==4){
                //     errorflg = true;
                //     errormessage =  '该报价委托存在预留产品';
                //     return false;
                // }
            }
        }
      
      //20220310 fy lastbuy end
        //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start
        String resalt = assdproductCheck();
        if(resalt!='OK'){
            errorflg = true;
            errormessage = resalt ;
            return false;
        }
        //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 end
        system.debug('○○○○○○○○○○○○Welcome to dataCheck class!!○○○○○○○○○○○○');
        errorflg = false;
        errormessage = null;
        Boolean error = false;
        List<String> product2Ids = New List<String>();
        system.debug('wuwuwuwuwu:'+activities);
        if (activities.size()>0){
            for (QELine a:activities){
                if (String.isBlank(a.PageObject.Product2__c) == false) {
                    product2Ids.add(a.PageObject.Product2__c);
                }
            }
            system.debug('mmmmmmmm'+product2Ids);
            prd2LatestValMap = new Map<Id, Product2>();
            for (Product2 prd2: [Select Id, Estimation_Entry_Possibility__c, SFDA_Status__c,SFDA_Approbated_Status__c,StorageStatusNo__c,Entend_gurantee_period_all__c  From Product2 Where Id IN :product2Ids]) {
                if (prd2.Estimation_Entry_Possibility__c != '○') {
                    error = true;
                }
                prd2LatestValMap.put(prd2.Id, prd2);
                system.debug('qqqqqqqq:'+prd2LatestValMap);
            }
            if (error == true){
                if (quoId != null) {
                    Map<String,QuoteIraiLineItem__c> itemmap = new Map<String,QuoteIraiLineItem__c>();
                    for (QuoteIraiLineItem__c item : [//lastbuy  2022/3/10 fy start LastbuyProductFLG__c //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start Product2__r.Is_DangerousChemicals__c
                        Select Id,Product2__r.SFDA_Status__c,Product2__r.Name,Product2__c,Product2__r.LastbuyProductFLG__c,Product2__r.Is_DangerousChemicals__c
                        From QuoteIraiLineItem__c where QuoteIrai__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.IraiSubject__c == null) || (quo.IraiSubject__c =='')){
            quo.IraiSubject__c.addError(System.Label.Error_Message3);
            error = true;
            errormessage = System.Label.Error_Message3;
        }
        if(quo.Quote_Expiration_Date__c == null) {
            quo.Quote_Expiration_Date__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
        //契約内訳、印刷病院名称、見積有効期限日、見積表記コメント
        QuoteIrai__c q = New QuoteIrai__c();
        
        List<QELine> acts = new List<QELine>();
        for (QELine act : activities) {
            if (act.Asset_Model != null && act.Asset_Model != ''){
                acts.add(act);
            }
        }
        if (acts.size() != activitiesbk.size()) {
            quo.LastIraiUser__c = '';
        } else {
            for (Integer i = 0; i < acts.size(); i++) {
                // CHAN-BHNBX6 2019/11/20 START
                if (activitiesbk[i].Asset_Model != acts[i].Asset_Model
                    || activitiesbk[i].pageObject.SFDA_Status__c != acts[i].pageObject.SFDA_Status__c
                    || activitiesbk[i].pageObject.Name__c != acts[i].pageObject.Name__c
                    || activitiesbk[i].pageObject.Quantity__c != acts[i].pageObject.Quantity__c
                    || activitiesbk[i].pageObject.Product2__c != acts[i].pageObject.Product2__c
                    || activitiesbk[i].ListPrice_Page != acts[i].ListPrice_Page
                    || activitiesbk[i].NoDiscount_Page != acts[i].NoDiscount_Page
                    || activitiesbk[i].pageObject.GuaranteePeriod__c != acts[i].pageObject.GuaranteePeriod__c
                ) {
                    // CHAN-BHNBX6 2019/11/20 END
                    quo.LastIraiUser__c = '';
                    break;
                }
            }
        }
        if (changedAfterPrint) {
            quoId = null;
        }
        if (quoId==null){
            q = New QuoteIrai__c();
        }else{
            // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
            List<QuoteIrai__c> qs = New List<QuoteIrai__c>();//obsap 新增经销商1字段 fy satrt Agency1_entrust__c,SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start cancelMultiyearInsurance__c,
            //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
            //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
            qs = [select Id,Account__c,Agency_Hospital_Link__c,Name,IraiUser__c,IraiSubject__c,Tender_information__c,Agency1_entrust__c,Noteplus__c,Lead__c,Opportunity__c,cancelMultiyearInsurance__c,
                Preferential_Trading_Price__c,Discount__c,Pricing__c,Unit_Price__c,Offer_Amount__c,TOTAL__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,Agency2_entrust__c,//DB202302464682【报价委托】报价委托改善224 fy
                Contract__c,Print_HP_Name__c,Quote_Expiration_Date__c,Quote_Comment__c,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                , urgent__c  //20230104 lt DB202212427301
                From QuoteIrai__c Where Id =:quoId];
            // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
            if (qs.size()>0){
                q = qs[0];
            }
        }

        if (quoId==null){
            q.PriceRefreshDate__c = Date.today();
        }
        if (productStatusUpdated) {
            q.PriceRefreshDate__c = Date.today();
        }
        q.IraiSubject__c = quo.IraiSubject__c;
        q.Account__c = quo.Account__c;
        // 经销商询价报价委托 2020-02-28 update by vivek start
        q.Agency_Hospital_Link__c = quo.Agency_Hospital_Link__c;
        // 经销商询价报价委托 2020-02-28 update by vivek end
        // 招投标报价委托 2020-06-21 update by gzw start
        q.Tender_information__c = quo.Tender_information__c;
        // 招投标报价委托 2020-06-21 update by gzw end
        q.IraiUser__c = quo.IraiUser__c;
        q.IraiName__c = quo.IraiName__c;
        //obsap 新增经销商1字段 fy staty
        q.Agency1_entrust__c = quo.Agency1_entrust__c;
        //obsap 新增经销商1字段 fy staty
        //DB202302464682【报价委托】报价委托改善224 fy start
        q.Agency2_entrust__c = quo.Agency2_entrust__c;
        //DB202302464682【报价委托】报价委托改善224 fy end
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        q.cancelMultiyearInsurance__c = quo.cancelMultiyearInsurance__c;
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
        q.QuoteProportion__c = quo.QuoteProportion__c;
        q.CurrencyIsoCode = quo.CurrencyIsoCode;
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
        q.Noteplus__c=quo.Noteplus__c;
        if(!String.isBlank(quo.Note__c)){
            q.Note__c = quo.Noteplus__c+'\r\n'+quo.Note__c;
        }else {
            q.Note__c = quo.Noteplus__c;
        }
        
        System.debug('===222==='+quo.Noteplus__c+'  ===333===   '+q.Note__c);
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
        // q.Note__c = quo.Note__c;
        q.IraiComment__c = quo.IraiComment__c;
        //----checkbox は印刷直前に保存
        q.Quote_Expiration_Date__c = quo.Quote_Expiration_Date__c;
        q.Quote_Comment__c = quo.Quote_Comment__c;
        q.LastIraiUser__c = quo.LastIraiUser__c;
        q.Urgent__c = quo.Urgent__c;   //20230104 lt DB202212427301 shart
        system.debug('标准价格2：'+qb.Estimation_List_Price);
        // CHAN-BJQ4VZ 精琢技术 2019/12/10 Start 
         q.Estimation_List_Price__c = qb.Estimation_List_Price;
         q.MultiYearWarrantyTotalPrice__c = qb.MultiYearWarrantyTotalPrice;
         q.QuoteTotal_Page__c = qb.QuoteTotal_Page;
        // CHAN-BJQ4VZ 精琢技术 2019/12/10 END
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy start
        q.Lead__c=leadid;
        q.Opportunity__c=oppid;
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy end
        if (quoId==null){
            insert q;
        }else{
            update q;
        }
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy  Noteplus__c
        //SWAG-CF589P【委托】【P:OBSAP】报价委托相关新需求评估 fy Lead__c,Opportunity__c,
        quo =[ SELECT Id,Name,Cancel_Decide__c,CreatedDate, PriceRefreshDate__c,Quote_Print_Date__c,//obsap 新增经销商1字段 fy satrt Agency1_entrust__c,SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start cancelMultiyearInsurance__c,
                    Quote_Date__c,QuoteToName__c,Quote_Expiration_Date__c,Quote_Comment__c,Tender_information__c,Agency1_entrust__c,Noteplus__c,Lead__c,Opportunity__c,cancelMultiyearInsurance__c,Headquarters__c,//DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy Headquarters__c
                    TOTAL__c,Discount__c,Pricing__c,Preferential_Trading_Price__c,Contract__c,LastIraiUser__c,MultiYearWarrantyTotalPrice__c,QuoteTotal_Page__c,Estimation_List_Price__c,Agency2_entrust__c,//DB202302464682【报价委托】报价委托改善224 fy
                    Print_HP_Name__c,Account__c,Agency_Hospital_Link__c,IraiUser__c,IraiSubject__c,CurrencyIsoCode,IraiName__c,QuoteIrai_Status__c,QuoteProportion__c,Note__c,IraiComment__c
                    , urgent__c  //20230104 lt DB202212427301
                    FROM QuoteIrai__c Where Id =:q.Id];

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

        //QuoteLineItem;
        List<QuoteIraiLineItem__c> qlist = New List<QuoteIraiLineItem__c>();
        qlist=[Select Id From QuoteIraiLineItem__c Where QuoteIrai__c =:quoId];
        system.debug('qqqqq'+qlist);
        if (qlist.size()>0){
            //delete
            delete qlist;
        }

        //QuoteLineItem--------------------------------------------
        //製品型番、品目コード、SFDAステータス、品目名、ListPrice、数量
        //価格、単位、小計、OCM売上予測金額（税抜）、価格表
        qlist = New List<QuoteIraiLineItem__c>();
        //Sap送信,Printに合わせて1～
        Integer i=1;
system.debug('○○○○○'+activities.size()+'○○○○○');
system.debug('xxxxxx'+activities+'xxxxxxx');
        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()しますか？意味不明。
                        s.pageObject.GuaranteePeriod__c = prd2LatestValMap.get(s.pageObject.Product2__c).Entend_gurantee_period_all__c;
                        QuoteIraiLineItem__c ql = s.pageObject.clone();
                        ql.QuoteIrai__c = q.Id;
                        ql.ListPrice__c = s.ListPrice_Page;
                        // CHAN-BHNBX6 2019/11/20 START 
                        ql.ServicePrice__c = s.NoDiscount_Page;
                        ql.NoDiscountTotal__c = s.NoDiscountTotal_Page;
                        ql.GuaranteePeriod__c = prd2LatestValMap.get(s.pageObject.Product2__c).Entend_gurantee_period_all__c;
                        // CHAN-BHNBX6 2019/11/20 END
                        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;
            
        }
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy start
        // if(quo.Note__c!=''){
        if(String.isNotBlank(quo.Note__c)){
            system.debug('===444==='+quo.Note__c.split('\r\n'));
            List<String> str=quo.Note__c.split('\r\n');
            if(str.size()==1){
                quo.Note__c=''; 
            }else{
                quo.Note__c=str[1]; 
            }
        }
        //XLIU-CFE8M7 【委托】【P-OBSAP】报价委托任务改善 fy end
        return true;
    }
     //lastbuy  2022/3/10 fy start
  public boolean ReservedProductVerification() {
    filg=true;
    Map<string,QuoteIraiLineItem__c> quotlinitMap = new Map<string,QuoteIraiLineItem__c>();
    List<Id> lastProductFLGListId = new List<Id>();
    List<QuoteIraiLineItem__c> lastProductFLGList = new List<QuoteIraiLineItem__c>();
    List<QuoteIraiLineItem__c> act = new List<QuoteIraiLineItem__c>();
    List<QuoteIraiLineItem__c> act2 = new List<QuoteIraiLineItem__c>();
    Map<string,string> actMap = new Map<string,string>();
    for(QELine aaa :activities){
        System.debug('131313131!!!'+aaa.pageObject.Product2__r.LastbuyProductFLG__c);
      if(aaa.pageObject.Product2__c!=null&&aaa.pageObject.Quantity__c!=null){
        actMap.put(aaa.pageObject.Product2__c,aaa.Asset_Model);
        act.add(aaa.pageObject);
      }
    }
    act2=act.deepClone();
    Map<String,QuoteIraiLineItem__c> map1 = new Map<String,QuoteIraiLineItem__c>();
    System.debug('activities1111111111112为所当为多多!!!'+activities);
    integer i =0;
    for(QuoteIraiLineItem__c pspsc :act2){
      if(pspsc.Product2__c!=null&&pspsc.Quantity__c!=null){
        if(map1.containsKey(pspsc.Product2__c)){
            QuoteIraiLineItem__c quoteLine = map1.get(pspsc.Product2__c);
          quoteLine.Quantity__c =quoteLine.Quantity__c+pspsc.Quantity__c;
          map1.put(pspsc.Product2__c,quoteLine);
          System.debug('2222222!!!'+quoteLine);
        }else{
          map1.put(pspsc.Product2__c,pspsc);
        }
        System.debug('5555555!!!'+pspsc);
        System.debug('34499879!!!'+activities);
      }
    }
    System.debug('3434343!!!'+activities);
    System.debug('5656565!!!'+map1);
    List<Product2> productlist = [select id,LastbuyProductFLG__c from Product2 where id in:map1.keySet()];   
    Map<String,boolean> productMap = new Map<String,boolean>();
    System.debug('9999999666!!!'+productlist);
    if(productlist!=null&&productlist.size()!=0){
        for(Product2 product : productlist){
            productMap.put(product.id,product.LastbuyProductFLG__c);
        } 
    }
    for (QuoteIraiLineItem__c value : map1.values()) {
      if(productMap.get(value.Product2__c)){
        lastProductFLGListId.add(value.Product2__c);
        quotlinitMap.put(value.Product2__c,value);
        lastProductFLGList.add(value);
      }
    } 
    System.debug('activities++++!!!'+activities);
    System.debug('activities!!!'+map1.values());
    System.debug('oppId!!!'+oppId);
    System.debug('lastProductFLGList!!!'+lastProductFLGListId);
    if(lastProductFLGListId!=null&&lastProductFLGListId.size()!=0){
        // if(oppid==null){
        //     flglastbuy=4;
        //     filg=false;
        //     return filg;
        // }
        List<LastbuyProduct__c> LastbuyObjList=[select id,LastbuyQuantity__c,InquiryCode__c,ProductName__c,effectiveFLG__c from LastbuyProduct__c where InquiryCode__c= : oppid and ProductName__c in :lastProductFLGListId and effectiveFLG__c = true];
        Map<string,LastbuyProduct__c> LastbuyObjMap = new Map<string,LastbuyProduct__c>();
        System.debug('LastbuyObjList+++++!!!'+LastbuyObjList);
        if(LastbuyObjList!=null&&LastbuyObjList.size()!=0){
          for(LastbuyProduct__c lastbuypr :LastbuyObjList){
            LastbuyObjMap.put(lastbuypr.ProductName__c,lastbuypr);
          }
        }else{
          flglastbuy=1;
          filg=false;
          return filg;
        }
        System.debug('LastbuyObjMap!!!'+LastbuyObjMap);
        System.debug('lastProductFLGList+++++++!!!'+lastProductFLGList);
        if(lastProductFLGList!=null&&lastProductFLGList.size()!=0){
          for(QuoteIraiLineItem__c lastbuypr :lastProductFLGList){
            Decimal quoteLItemNum=0;
            if(LastbuyObjMap.containsKey(lastbuypr.Product2__c)){
                quoteLItemNum=LastbuyObjMap.get(lastbuypr.Product2__c).LastbuyQuantity__c;
                System.debug('quoteLItemNum!!!'+quoteLItemNum);
                System.debug('lastbuypr.pageObject.Quantity__c+++!!!'+lastbuypr.Quantity__c);
                if(lastbuypr.Quantity__c>quoteLItemNum){actMap.get(lastbuypr.Product2__c);
                  errorProductmodel=actMap.get(lastbuypr.Product2__c);
                  flglastbuy=2;
                  filg=false;
                  break;
                }
            }else{
              errorProductmodel=actMap.get(lastbuypr.Product2__c);
              flglastbuy=3;
              filg=false;
              break;
            }
          }
        }
    }
    system.debug('filg====='+filg);
    return filg;
  }
 //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 start
  //阿西赛多验证
  public String assdproductCheck(){
    Boolean falg = false;
    String str = 'OK';
    List<Product2> axsdQuoteIItem = new List<Product2>();
    List<Product2> QuoteIItem = new List<Product2>();
    List<Id> Product2List = new List<Id>();
    System.debug('activities111111!!!'+activities);
    for(QELine aaa :activities){
     if(String.isNotBlank(aaa.pageObject.Product2__c)){
        Product2List.add(aaa.pageObject.Product2__c);
     }
    }
    List<Product2> productlist = [select id,Is_DangerousChemicals__c from Product2 where id in:Product2List];  
    for(Product2 pro :productlist){
        System.debug('Is_DangerousChemicals__c111111!!!'+pro.Is_DangerousChemicals__c);
        if(pro.Is_DangerousChemicals__c){
            falg = true;
            axsdQuoteIItem.add(pro);
        }else if(!pro.Is_DangerousChemicals__c){
            QuoteIItem.add(pro);
        }
    }
    if(QuoteIItem.size() > 0 && axsdQuoteIItem.size() > 0){
        str = '阿西赛多产品不能和其他产品一起报价';
    }else{
        if(falg){
            str = OpportunityWebService.checkDangerItem(quo.Agency1_entrust__c);
        }
    }
    return str;
  }
  //SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 end
  //DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy start
  private static void sendEmail(String title , String bodyTextp , String bodyTextbody,String TaskId,String Headquarters) {
    system.debug('bodyText++'+bodyTextp+bodyTextbody);
    bodyTextbody = bodyTextbody.replaceFirst('\r\n', '');
    List<Task> TaskList = [select Id,Request_staff__c,ActivityDate,Priority from Task where Id =:TaskId];
    Task Taskobj = TaskList[0];
    //20230116 fy start
    String bodyTextbu ='新建任务';
    bodyTextbu += '\r\n\r\n'+'到：OBSAP成员';
    if(String.isNotBlank(Headquarters)){
        Headquarters='('+Headquarters+')';
    }
    bodyTextbu += '\r\n'+Taskobj.Request_staff__c +Headquarters+' 已分配给您以下新建任务：';
    bodyTextbu += '\r\n'+'主题: '+title;
    bodyTextbu += '\r\n'+'结束期限: '+Taskobj.ActivityDate;
    bodyTextbu += '\r\n'+'优先级: '+Taskobj.Priority;
    bodyTextbu += '\r\n' +'评论：<pre>'+bodyTextp+'</pre>';
    bodyTextbu += bodyTextbody;
    bodyTextbu += '\r\n\r\n' +'有关更多详细信息，请单击以下链接：'+'\r\n\r\n'+'https://ocsm.my.salesforce.com/'+Taskobj.Id;
    bodyTextbu = bodyTextbu.replace('\r\n', '<br/>');
    bodyTextbu = bodyTextbu.replaceFirst('<br/>', '');
    System.debug('bodyTextbu+++'+bodyTextbu);
    //20230116 fy end
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    List<String> toAddresses = new List<String>();
    toAddresses.add(System.Label.OBSAP_Group_Mail);
    // toAddresses.add('fuyu@prec-tech.com');
    //收件人地址
    mail.setToAddresses(toAddresses);
    String Detection = System.Label.OBSAP_QuoteIrai_Mail_Detection;
    if(!Detection.equals('invalid') && String.isNotBlank(Detection)){
        String[] toccAddresses = System.Label.OBSAP_QuoteIrai_Mail_Detection.split(',');
        //抄送人地址
        mail.setCcAddresses(toccAddresses);
    }
    //邮件主题
    mail.setSubject(title);
    //内容的编码
    mail.setCharset('UTF-8');
    //邮件内容
    mail.setHtmlBody(bodyTextbu);
    //使用电子邮件模板设置对象id
    // mail.setTargetObjectId(TaskId);
    //设置电子邮件模板id
    // EmailTemplate temp =  [
    //     SELECT Id, Name, Subject, HtmlValue, Body, BrandTemplateId
    //     FROM EmailTemplate
    //     WHERE DeveloperName = 'Task_To_Queue'
    //     LIMIT 1
    // ];
    // mail.setTemplateId(temp.Id);
    //发送邮件
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
//DB202301106714 【报价委托改善】OBSAP通知邮件发送邮箱修改 fy end

    // CHAN-BJQ4VZ 精琢技术 2019/12/11 Start
    public class QuoteBean {
    // 产品标准定价总额
    public Decimal Estimation_List_Price { get; set; }
    //报价总额
    public Decimal QuoteTotal_Page { get; set; }
    //NoDiscount price 合计
    public Decimal MultiYearWarrantyTotalPrice { get; set; }
    //obsap 新增经销商1字段 fy
    public Decimal SalesCalculation1 { get; set; }
    }
    // CHAN-BJQ4VZ 精琢技术 2019/12/11 End
    
    public class QELine {
        public Integer lineNo { get; set; }                                // 画面の順序
        public String Asset_Model {get;set;}
        public String Sales_Possibility {get;set;}                         // 販売可否○×判断用、使ってないようです。TODO 削除
        public QuoteIraiLineItem__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; }

        // CHAN-BHNBX6 2019/11/20 START
        public Decimal NoDiscount_Page { get; set; }
        public Decimal NoDiscountTotal_Page { get; set; }
        // CHAN-BHNBX6 2019/11/20 END
        
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
        public String CanNotCancelledGurantee { get; set; }
        // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy end

        // TODO ほんとうはいらない、使うところのロジックを修正しなければいけない、削除するようにしたいです。
        public QELine(Integer i) {
            pageObject = New QuoteIraiLineItem__c();
            this.lineNo = i;
        }
        // tmp 直接使う場合のパターン
        public QELine(QELine tmp, Integer i) {
            pageObject = tmp.pageObject;
            this.lineNo = i;
            this.Asset_Model = tmp.Asset_Model;
            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;
            // CHAN-BHNBX6 2019/11/20 START
            this.NoDiscount_Page =tmp.NoDiscount_Page;
            this.NoDiscountTotal_Page =tmp.NoDiscountTotal_Page;
            this.pageObject.GuaranteePeriod__c = pageObject.GuaranteePeriod__c;
            // CHAN-BHNBX6 2019/11/20 END
        }
        public QELine(QuoteIraiLineItem__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.ListPrice_Page = qli.ListPrice__c;
            this.ListPriceTotal_Page = qli.Quantity__c * qli.ListPrice__c;
            // CHAN-BHNBX6 2019/11/20 START
            pageObject.GuaranteePeriod__c =qli.GuaranteePeriod__c;
            this.NoDiscount_Page =qli.ServicePrice__c;
            if(qli.ServicePrice__c == null){
                this.NoDiscountTotal_Page =0;
            }else{
                this.NoDiscountTotal_Page =qli.Quantity__c * qli.ServicePrice__c;
            }
            
            // CHAN-BHNBX6 2019/11/20 END
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy start
            this.CanNotCancelledGurantee = qli.CanNotCancelledGurantee__c?'true':'false';
            // SWAG-CKDATG 【委托】【OBSAP-报价委托】报价委托项目改善1 fy end
        }
        
        // TODO Subtotal__c、以前のロジックを確認
        public QELine(Integer i, String PricebookEntryId, String Asset_Model, 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 GuaranteePeriod_c,Decimal ServicePrice_c) {
            pageObject = New QuoteIraiLineItem__c();
            pageObject.Quantity__c = Quantity;
            this.lineNo = i;
            this.Asset_Model = Asset_Model;
            this.Sales_Possibility = Sales_Possibility_c;
            pageObject.Product2__c = Id_c;
            pageObject.SFDA_Status__c = SFDA_Status_c;
            pageObject.Name__c = Name_c;
            pageObject.BSS_Category__c = BSS_Category_c;

            this.ListPrice_Page = ListPrice_c;
            this.ListPriceTotal_Page = Quantity * ListPrice_c;
            // CHAN-BHNBX6 2019/11/20 START
            pageObject.GuaranteePeriod__c =GuaranteePeriod_c;
            this.NoDiscount_Page =ServicePrice_c;
            if(ServicePrice_c == null){
                this.NoDiscountTotal_Page =0;
            }else{
                this.NoDiscountTotal_Page =Quantity * ServicePrice_c;
            }
            
            // CHAN-BHNBX6 2019/11/20 END
            this.Cost_c = Cost_c;

            // TODO katsu なぜここ > 0 の判断はいらない？
            this.Cost_Subtotal_c = Cost_c * Quantity;
        }
    }
}