// 2023-12-04 update by dzk start 事件或日报涉及询价,不允许用户查询出自己无权限的数据
/* 备品智能化 add by dzk
   事件copy日报组件,将without sharing 改为 with sharing
*/
global with sharing class ControllerUtilEvent {
// global with sharing class ControllerUtil {

    public static Boolean EventOpportunityPileUpExeFlg = false;
    // EventC⇒Event処理後、逆更新をスルー用
    public static Boolean NotUpdEventCFlg = false;
    // 積み上げ処理後、トリガをスルー用
    public static Boolean EscapeNFM001Trigger = false;
    public static Boolean EscapeNFM001AgencyContractTrigger = false;
    public static Boolean EscapeNFM007Trigger = false;
    public static Boolean EscapeOpportunityBefUpdTrigger = false;
    public static Boolean EscapeOpportunityHpDeptUpdTrigger = false;
    public static Boolean EscapeSyncOpportunityTrigger = false;
    public static Boolean EscapeMaintenanceContractAfterUpdateTrigger = false;
    public static Boolean EscapeSyncProduct2Trigger = false;
    
    // 商談の更新不可項目リスト
    public static List<String> oppColumnList = System.Label.Opportunity_Columns.split(',');
    
    // 削除対象のEvent
    public static Set<Id> delEventIdSet = new Set<Id>();     

    // 100日定数
    public static Integer ReportDayRange = 100;
    
    // 商談レコードタイプ
    public static String[] oppRecordTypeDevNames = new String[] {'Opportunity'};
    
    public static final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    

    public ControllerUtilEvent() {
    }
    
    @AuraEnabled(cacheable=true)
    public static ContactRecord getRecordForContact(String recordId,List<String> fields) {
        System.debug('getRecordForContact');
        System.debug('recordId:' +recordId);
        System.debug('fields:' +fields);
        ContactRecord returnData = new ContactRecord();
        List<Sobject> queryResult = new List<sObject>();
        String querySql = 'Select Id, Name,AWS_Data_Id__c from Contact  where id= \'' +recordId + '\' ';
        queryResult = Database.query(querySql);
        if(queryResult.size()>0 ) {
            returnData.id = recordId;
            returnData.Name = (String)queryResult[0].get('Name');
            returnData.AWS_Data_Id = (String)queryResult[0].get('AWS_Data_Id__c');
        }
        System.debug('returnData:' +returnData);
        return returnData;
    }

    public class ContactRecord {
        @AuraEnabled public String id;
        @AuraEnabled public String Name;
        @AuraEnabled public String AWS_Data_Id;
    }
    @AuraEnabled(cacheable=true)
    public static Record getRecordForLwc(String recordId,List<String> fields) {
        System.debug('getRecordForLwc');
        System.debug('recordId:' +recordId);
        System.debug('fields:' +fields);
        Record returnData = new Record();
        if(fields.size()>0) {
            String obj = fields[0];
            List<String> fieldsList = obj.split('\\.');
            System.debug(fieldsList);
            if(fieldsList.size()>0) {
                obj = fieldsList[0];
                List<Sobject> queryResult = new List<sObject>();
                String querySql = 'Select Id, Name from ' + obj +'  where id= \'' +recordId + '\' ';
                queryResult = Database.query(querySql);
                if(queryResult.size()>0 ) {
                    returnData.Id = recordId;
                    returnData.Name = (String)queryResult[0].get('Name');
                }
            }
        }
        System.debug('returnData:' +returnData);
        return returnData;
    }
    public class Record {
        @AuraEnabled public String Id;
        @AuraEnabled public String Name;
    }

    // 省単位 or 全国の診療科を検索，最初の50件
    public static Map<Id, Account> selectDepartByHospitalState(String nameCondition, String reporterState, Integer limitCnt) {
        User loginUser = [Select Id, State_Hospital__c, Job_Category__c from User where Id =: UserInfo.getUserId()];
        String queryString = 'select Id, Name, Department_Class__c, Department_Class__r.Name, Hospital__c, Hospital__r.Name from Account where' + nameCondition + ' Hospital__r.RecordType.DeveloperName = \'HP\' and Is_Active__c <> \'無効\'';
        if (loginUser.Job_Category__c == 'GI市场'
                || loginUser.Job_Category__c == 'SP市场'
                || loginUser.Job_Category__c == '服务本部'
                || loginUser.Job_Category__c == '培训'
        ) {
            // 全国範囲、なにもしない
        } else {
            // 省単位の条件追加
            system.debug('selectDepartByHospitalState reporterState=' + reporterState);
            queryString += ' and Parent.Parent.State_Master__r.Name = :reporterState';
        }
        queryString += ' order by Name limit :limitCnt';
        system.debug('selectDepartByHospitalState queryString=' + queryString);
        return new Map<Id, Account>((List<Account>) Database.query(queryString));
    } 

    //检索询价
    public static String getOppSearchSQOLforLwc(String visitorPlaceId,Date starttoday,Date lastDate) {
        Account a = new Account();
        List<Account> accountList = [select Id, Hospital__c, Agent_Ref__c, Parent.Parent.RecordType.DeveloperName, Parent.RecordType.DeveloperName, RecordType.DeveloperName from Account where Id=:visitorPlaceId];
        if(accountList.size()>0) {
            a = accountList[0];
        }
        
        
        // 検索
        String queryString = ' ';
        // String temptoday = Date.today().format().replace('/', '-');
        // String tempLastDate = Date.today().addDays(-365).format().replace('/', '-');
        // Date today = Datetime.now().date();
        // Date lastDate = Datetime.now().date().addyears(-1);
        String  todaynew = String.valueOf(Date.newInstance(starttoday.year(), starttoday.month(), starttoday.day())).substring(0,10);
        String  lastDatenew = String.valueOf(Date.newInstance(lastDate.year()-1, lastDate.month(), lastDate.day())).substring(0,10);
        // 病院
        if (a.Parent.Parent.RecordType.DeveloperName == 'HP') {



        // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition 
            // + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > '+tempLastDate+' and Shipping_Finished_Day__c <= '+temptoday+' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';


            queryString +=  '  and Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > ' + lastDatenew + '  and Shipping_Finished_Day__c <= ' + todaynew + ' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\''+System.Label.RecordType_Opportunity_ControllerUtil.split(',')[0]+'\',\''+System.Label.RecordType_Opportunity_ControllerUtil.split(',')[1]+'\') order by Name, Opportunity_No__c, Department_Name__c '; 
            // queryString +=  ' and   Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and CALENDAR_YEAR(Created_Day__c) <> 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c '; 
        }
        // 販売店
        else if (a.RecordType.DeveloperName == 'Agency') {
            queryString +=  ' and Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > ' + lastDatenew + ' and Shipping_Finished_Day__c <= ' + todaynew + ' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\''+System.Label.RecordType_Opportunity_ControllerUtil.split(',')[0]+'\',\''+System.Label.RecordType_Opportunity_ControllerUtil.split(',')[1]+'\') order by Name, Opportunity_No__c, Department_Name__c';
            // queryString +=  ' and  Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\'  CALENDAR_YEAR(Created_Day__c) <> 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c ';
           
        }
        return queryString;
    }

    public static List<Sobject> getOpportunitys(String querySql) {
        return  Database.query(querySql);
    }

}