global without sharing class ControllerUtil {
    // トリガ実行回数を制御する、一回目false、二回目（workflow対応用）true
    //public static Boolean XinEventOppotunityPileUpExeFlg = false;
    // 積み上げをIsScheduledフラグ設定の後に実行
    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 ControllerUtil() {
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
                i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
                i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
                i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
                i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
                i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
                i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
    @AuraEnabled
    WebService static String selectCommonSequence(String valueField, String formatField) {
        Boolean insertNew = false;
        //取得共通採番序列
        String soql = 'select id,' + valueField + ',' + formatField + ' from Common_Sequence__c for update';
        List<Common_Sequence__c> csList = Database.query(soql);
        if (csList.size() == 0) {
            //共通採番序列没数据，新建
            Common_Sequence__c newCS = new Common_Sequence__c();
            newCS.Name = '共通採番序列';
            newCS.EvaluationPDF_NextValue__c = 1;
            insert newCS;
            insertNew = true;
            //再取得共通採番序列
            csList = Database.query(soql);
        }
        Common_Sequence__c cs = csList[0];
        //採番编码
        String format = String.valueOf(cs.get(formatField));
        //下个採番值
        Decimal nextValue = Decimal.valueOf(String.valueOf(cs.get(valueField)));
        //採番
        nextValue += 1;
        cs.put(valueField, nextValue);
        update csList;
        //返回採番编码
        return format;
    }
    
    public static String generateRandomStr(Integer len) {
        String randStr = '';
        while (randStr.length() < len) {
           Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
           randStr += chars.substring(idx, idx+1);
        }
        return randStr;
    }
    
    public static List<Document> getPdfBlobForPreview(String docId) {
        return [select Id, Name, Body, CreatedDate from Document where Id = :docId];
    }
    
    public static List<SMARM__c> getSmarmByUser(Map<String, Schema.SObjectField> fieldMap, String fromUserId, String toUserId) {
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' from SMARM__c where Review_Practitioner__c = :fromUserId and Review_Target__c = :toUserId and (Status__c = \'草案中\' or Status__c = \'Delete\')';
        List<SMARM__c> sList = Database.query(sql);
        return sList;
    }
    
    public static void createDocForEmail(List<Document> docList) {
        Folder f = [select Id from Folder where DeveloperName = 'EmailImgFolder'];
        for (Document doc : docList) {
            doc.FolderId = f.Id;
            doc.IsPublic = true;
        }
        insert docList;
    }
    
    public static List<SMARM__c> getSmarmById(String sql) {
        return Database.query(sql);
    }
    
    public static List<Attachment> getSmarmAtts(String smarmId) {
        return [select Id, Name, Body from Attachment where ParentId = :smarmId order by Name];
    }
    
    public static void insertAttachments(List<Attachment> atts) {
        if (atts.size() > 0) insert atts;
    }
    
    public static void updateAttachments(List<Attachment> atts) {
        if (atts.size() > 0) update atts;
    }
    
    public static void deleteAttachments(List<Attachment> atts) {
        if (atts.size() > 0) delete atts;
    }
    
    public static void upsertSMARM(SMARM__c smarm) {
        upsert smarm;
    }
    
    public static void insertSMARMShare(List<SObject> smarmShare) {
        insert smarmShare;
    }
    
    public static List<Account> selectAccountForTrigger(List<String> accIds) {
        return [Select Id, Name, Management_Code__c, OwnerId, ParentId, Parent.ParentId,Parent.Parent.Name, RecordTypeId from Account where Id IN :accIds];
    }
    public static Map<Id, Contact> selectContactAccountForTrigger(List<Id> contactIds) {
        return new Map<Id, Contact>([Select Id, AccountId, Account.ParentId, Account.Parent.ParentId, Account.RecordTypeId from Contact where Id IN :contactIds]);
    }
    public static list<Contact> selectContactForCampaignMember(Set<Id> contactIds) {
        return [Select Id, campaign__c,campaign__r.Lesson_Type__c, campaign__r.TrainingType__c from Contact where Id IN :contactIds];
    }
    public static List<Contact> selectDummyContact() {
        return [select id, Email from Contact where email <> null limit 1];
    }
    
    public static List<Account> selectBossMailAddr(List<String> accIds) {
        return [select Id, Parent.Boss__r.Email, Parent.Sub_Boss__r.Email, Parent.Boss__r.Name, Parent.Sub_Boss__r.Name from Account where Id in : accIds];
    }
    
    public static List<Event> eventSelectById(String id){
        List<Event> eParamList = [select id, ActivityDate, OwnerId, Subject, whatid__c, EventC_ID__c, NextEventC_ID__c, AppCdId__c, SyncCreatedDate__c, 
                                  StartDateTime, DurationInMinutes, Main_Visit_Location__c, Activity_Type2__c, IsScheduled__c, BeforeActivityDate__c,
                                  Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c, Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c,
                                  Purpose_Type__c, Location, Related_Opportunity1__c, Related_Service1__c, Related_Opportunity1_ID__c, Related_Service1_ID__c,
                                  Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,OPDPlan_Flag__c,
                                  Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                                  Activity_Purpose__c, Activity_PurposeFSE__c, Activity_PurposeEscFSE__c, Purpose_TypeFSE__c, Purpose_TypeEscFSE__c
                                  from Event where id = :id];
        return eParamList;
    }
    public static List<Event> eventSelectByDate(Date whereDate, User ur){
        List<Event> calenderList = [select id, ActivityDate, OwnerId, Subject, whatid__c, EventC_ID__c, NextEventC_ID__c, AppCdId__c, SyncCreatedDate__c, 
                                  StartDateTime, DurationInMinutes, Main_Visit_Location__c, Activity_Type2__c, IsScheduled__c, BeforeActivityDate__c,
                                  Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c, Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c,
                                  Purpose_Type__c, Location, Related_Opportunity1__c, Related_Service1__c, Related_Opportunity1_ID__c, Related_Service1_ID__c, WS_flg__c,
                                  Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,OPDPlan_Flag__c,
                                  Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,Opd_Plan__c,
                                  Activity_Purpose__c, Activity_PurposeFSE__c, Activity_PurposeEscFSE__c, Purpose_TypeFSE__c, Purpose_TypeEscFSE__c,EventStatus__c,cancelReason__c,cancelReasonOther__c,cancelReasonSelect__c,cancelReasonSelectFSE__c,delayReason__c,delayReasonOther__c,delayReasonSelect__c,delayReasonSelectFSE__c,delayToDate__c  
                                  from Event where WS_flg__c = false and ActivityDate = :whereDate and OwnerId = :ur.Id and EventStatus__c not in ('04 取消','05 延期','06 关闭','07 未执行') order by StartDateTime];
        return calenderList;
    }
    
    public static List<Daily_Report__c> reportSelectByDate(Date whereDate, String ownerId){
        List<Daily_Report__c> reportList = [select id, name, Reporter__c, Reported_Date__c, Daily_Report_Data_Type__c,
                                            Working_Time_From__c, Working_Time_To__c, Status__c, Mail_Send_Check__c,
                                            Business_Trip__c, Submit_Date_New__c, Submit_DateTime_New__c, Approved_Date__c,
                                            Approved_DateTime__c, CreatedById, Feed_Back_From_Manager__c, FeedbackManager__c,
                                            Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c,
                                            Activity_ID__c, Manager_Mail__c, Status_With_Check__c
                                            from Daily_Report__c where Reported_Date__c =:whereDate and OwnerId =:ownerId];
        return reportList;
    }
    
    public static List<RecordType> recordTypeSelectForTrainingtestResult(){
        List<RecordType> rtList = [select Id, DeveloperName from RecordType where IsActive = true and SobjectType = 'Training_test_Result__c'];
        return rtList;
    }
    
    public static List<Training_test_Result__c> trainingtestResultSelectByContactIds(Set<Id> ids){
        List<Training_test_Result__c> ttrList = [select Id, RecordType.DeveloperName, employee__c from Training_test_Result__c where employee__c in :ids];
        return ttrList;
    }
    
    public static void updateSObjectContact(List<SObject> contactList) {
        if (contactList != null && contactList.size() > 0) update contactList;
    }
    
    public static Map<Id, Contact> selectActiveUserFromContact(List<Id> contactIds) {
        return new Map<Id, Contact>([Select Id, User__c From Contact Where Id IN: contactIds and User__r.isActive = true]);
    }


    /**
     * add      2021/12/23        wangweipeng                 satrt
     * [updateFutureOds 更新ods的user__c字段]
     * @param odsEmployeeNoList [员工编码]
     * @param odsEmployeeNoMap  [员工编码对应的user Id]
     * 
     */
    @future
    public static void updateFutureOds(List<String> odsEmployeeNoList,Map<String,Id> odsEmployeeNoMap) {
        if(odsEmployeeNoList != null && odsEmployeeNoList.size() > 0){
            List<ODS__c> odsData = [select id,name,User__c,Employee_No__c from ODS__c where Employee_No__c in :odsEmployeeNoList];
            if(odsData != null && odsData.size() > 0){
                for(ODS__c ods : odsData){
                    ods.User__c = odsEmployeeNoMap.get(ods.Employee_No__c);
                }
                update odsData;
            }
        }
    }
    //add      2021/12/23        wangweipeng                 end
    
    /*
    https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_non_mix_sobjects.htm
    */
    @future
    public static void upsertFutureContact(List<String> userEmployeeNoList) {
        upsertFutureContactInterface(userEmployeeNoList);
    }
    //@future
    public static void upsertFutureContactInterface(List<String> userEmployeeNoList) {

        // 社内员工のレコードタイプ
        Id rtId = '01210000000Qtky';
        // 现有联系人
        Map<String, Contact> conMap = new Map<String, Contact>();
        // UserToContact の 変更したか にて判断した項目です
        //20220425  LLIU-CCY9TA you 查询post的地方换成 HR_Post__c
        List<User> usrList = [select Id,PositionSubsequence__c,Rank__c, Notes_File_Name__c,FirstName, LastName, Email, Mobile_Phone__c, Employee_No__c, Work_Location__c, HR_Post__c,Post__c, Job_Category__c, Hire_Date__c, Gender__c, Dept__c, Pregnant_Rest__c, Salesdepartment__c, Stay_or_not__c,IsMEBG__c, Work_Location_HR__c from User where Employee_No__c IN :userEmployeeNoList];
        List<Contact> conList = [select Id,Notes_File_Name__c, User__c, Employee_No_manual__c,Isactive__c,IsMEBG__c, Work_Location_HR__c from Contact where Employee_No_manual__c IN :userEmployeeNoList and RecordTypeId = :rtId];
        for (Contact con : conList) {
            //conMap.put(con.Employee_No_manual__c, con);
            conMap.put(con.Employee_No_manual__c.toLowerCase(), con);
        }
        system.debug('youchangtest1');
        List<Contact> upsertList = new List<Contact>();
        for (User local : usrList) {
            //update                          wangweipeng                2021/11/19  
            //不能填写诸如“医生”，“老师”，“护士”，“院长”，“某某”等头衔代称
            if(String.isNotBlank(local.FirstName)){
                if(UserInfo.getProfileId() != '00e10000000Y3o5' && UserInfo.getProfileId() != '00e10000000Y3o5'){
                    if(local.FirstName == '老师' || local.FirstName == '医生' || local.FirstName == '主任' || local.FirstName == '院长' 
                        || local.FirstName == '科长' || local.FirstName == '课长' || local.FirstName == '护士' || local.FirstName == '护士长'
                         || local.FirstName == '先生' || local.FirstName == '女士' || local.FirstName == '等等' || local.FirstName == '某'
                          || local.FirstName == '某某' || local.FirstName == '某某某' || local.FirstName == '大夫')
                    {
                        System.debug('----代码：请填写正确的名字，不能填写诸如“医生”，“老师”，“护士”，“院长”，“某某”等头衔代称!');
                        continue;
                    }
                }
            }
            //由于测试时，发现contact的员工编码为大写，user表为小写，但是新增时falseforce大小写不敏感，所以会报重复值的错误
            // 所以为了避免以上问题，把员工编码都转为小写
            if (conMap.containsKey(local.Employee_No__c.toLowerCase())) {
            //if (conMap.containsKey(local.Employee_No__c)) {
                // 更新现有联系人
                Contact tmp = conMap.get(local.Employee_No__c.toLowerCase());
                tmp.User__c = local.Id;
                tmp.FirstName = local.FirstName;
                tmp.LastName = local.LastName;
                tmp.Email = local.Email;
                tmp.Notes_File_Name__c = local.Notes_File_Name__c;//20170220新增
                tmp.MobilePhone = local.Mobile_Phone__c;
                tmp.Employee_No_manual__c = local.Employee_No__c;
                tmp.Work_Location_manual__c = local.Work_Location__c;
                //用户的工作地（人事）改变更新到联系人上 thh 2022-02-16 start
                tmp.Work_Location_HR__c = local.Work_Location_HR__c;
                //用户的工作地（人事）改变更新到联系人上 thh 2022-02-16 end
                tmp.Post_picklist__c = local.Post__c; //20220426  LLIU-CCY9TA you用户的 Post__c ，还是对应联系人
                tmp.HR_Post__c = local.HR_Post__c;//HR通用职级 //20220425  LLIU-CCY9TA you
                tmp.Job_Category_picklist__c = local.Job_Category__c;
                tmp.Hire_date_text__c = local.Hire_Date__c; 
                tmp.Gender_text__c = local.Gender__c; 
                tmp.Dept__c = local.Dept__c;
                tmp.Pregnant_Rest__c = local.Pregnant_Rest__c;
                tmp.Salesdepartment_Text__c = local.Salesdepartment__c;
                tmp.Stay_or_not__c = local.Stay_or_not__c;
                tmp.IsMEBG__c = local.IsMEBG__c;//是否MEBG
                //20220428 LLIU-CDW5ZW you start 
                tmp.PositionSubsequence__c = local.PositionSubsequence__c;
                //20220428 LLIU-CDW5ZW you end
                //20220512 you LLIU-CDW5ZW start
                tmp.Rank__c = local.Rank__c;
                //20220428 you LLIU-CDW5ZW end
                
                if(String.isNotBlank(local.Stay_or_not__c)){
                    tmp.Isactive__c = local.Stay_or_not__c == '在职' ? '有效':'无效(退休)';
                }
                upsertList.add(tmp);
                system.debug('youchangtest2'+tmp.HR_Post__c);
            } else {
                // 新做联系人
                Contact tmp = new Contact();
                tmp.RecordTypeId = rtId;
                tmp.AccountId = System.Label.Olympus_AccountID_Internal_staff;
                tmp.User__c = local.Id;
                tmp.FirstName = local.FirstName;
                tmp.LastName = local.LastName;
                tmp.Notes_File_Name__c = local.Notes_File_Name__c;//20170220新增
                tmp.Email = local.Email;
                tmp.MobilePhone = local.Mobile_Phone__c;
                tmp.Employee_No_manual__c = local.Employee_No__c;
                tmp.Work_Location_manual__c = local.Work_Location__c;
                //如果根据HR信息新建用户,则把HR信息的工作地传给用户的工作地和工作地（人事） thh 2022-02-16 start
                tmp.Work_Location_HR__c = local.Work_Location__c;
                tmp.Work_Location_picklist__c = local.Work_Location__c;
                //如果根据HR信息新建用户,则把HR信息的工作地传给用户的工作地和工作地（人事） thh 2022-02-16 end
                tmp.Post_picklist__c = local.Post__c;//20220426  LLIU-CCY9TA you用户的 Post__c ，还是对应联系人
                tmp.HR_Post__c = local.HR_Post__c;//HR通用职级 //20220425  LLIU-CCY9TA you
                tmp.Job_Category_picklist__c = local.Job_Category__c;
                tmp.Hire_date_text__c = local.Hire_Date__c; 
                tmp.Gender_text__c = local.Gender__c; 
                tmp.Dept__c = local.Dept__c;
                tmp.Pregnant_Rest__c = local.Pregnant_Rest__c;
                tmp.Salesdepartment_Text__c = local.Salesdepartment__c;
                tmp.Stay_or_not__c = local.Stay_or_not__c;
                tmp.IsMEBG__c = local.IsMEBG__c;//是否MEBG
                //20220428 LLIU-CDW5ZW you start 
                tmp.PositionSubsequence__c = local.PositionSubsequence__c;
                //20220428 LLIU-CDW5ZW you end
                //20220512 you LLIU-CDW5ZW start
                tmp.Rank__c = local.Rank__c;
                //20220428 you LLIU-CDW5ZW end
                if(String.isNotBlank(local.Stay_or_not__c)){
                    tmp.Isactive__c = '在职'.equals(local.Stay_or_not__c) ? '有效':'无效(退休)';
                }
                upsertList.add(tmp);
                system.debug('youchangtest3'+tmp.HR_Post__c);
            }
        }
        upsert upsertList;
    }
// 20220425 you 经查看 此对象应该是没有任何地方用到了，可以注释掉    
    public static void updateFutureUserByContact(List<String> userEmployeeNoList) {
        // 现有用户
        Map<String, User> usrMap = new Map<String, User>();
        // ContactToUser の 変更したか にて判断した項目です
        List<Contact> conList = [select Id, FirstName, LastName, Email, MobilePhone, Employee_No_manual__c, Work_Location_manual__c, Post_picklist__c, Job_Category_picklist__c, Hire_date_text__c, Gender_text__c, Dept__c, Pregnant_Rest__c, Stay_or_not__c from Contact where Employee_No_manual__c IN :userEmployeeNoList];
        List<User> usrList = [select Id, Employee_No__c from User where Employee_No__c IN :userEmployeeNoList];
        for (User usr : usrList) {
            //update                          wangweipeng                2021/11/19 
            //由于测试时，发现contact的员工编码为大写，user表为小写，但是新增时falseforce大小写不敏感，所以会报重复值的错误
            //所以为了避免以上问题，把员工编码都转为小写
            usrMap.put(usr.Employee_No__c.toLowerCase(), usr);
        }
        
        List<User> updateList = new List<User>();
        for (Contact local : conList) {
            //update                          wangweipeng                2021/11/19  
            //由于测试时，发现contact的员工编码为大写，user表为小写，但是新增时falseforce大小写不敏感，所以会报重复值的错误
            // 所以为了避免以上问题，把员工编码都转为小写
            if (usrMap.containsKey(local.Employee_No_manual__c.toLowerCase())) {
                // 更新现有用户
                User tmp = usrMap.get(local.Employee_No_manual__c);
                tmp.FirstName = local.FirstName;
                tmp.LastName = local.LastName;
                tmp.Email = local.Email;
                tmp.Mobile_Phone__c = local.MobilePhone;
                //tmp.Employee_No__c = local.Employee_No_manual__c;
                tmp.Work_Location__c = local.Work_Location_manual__c;
                tmp.Post__c = local.Post_picklist__c;
                tmp.Job_Category__c = local.Job_Category_picklist__c;
                tmp.Hire_Date__c = local.Hire_date_text__c; 
                tmp.Gender__c = local.Gender_text__c; 
                tmp.Dept__c = local.Dept__c;
                tmp.Pregnant_Rest__c = local.Pregnant_Rest__c;
                tmp.Stay_or_not__c = local.Stay_or_not__c;
                updateList.add(tmp);
            }
        }
        update updateList;
    }

    //add   wangweipeng                      2021/11/18               start
    //根据ods的员工编码，更新或新增 user表的数据
    public static void updateFutureOdsByUser(List<String> userEmployeeNoList) {
        //20220426  LLIU-CCY9TA you start 通用职衔和user上的职位互相映射，
        SS_BatchColumnMapping__c mpdMapping = SS_BatchColumnMapping__c.getValues('HR_Post_To_UserAndContact__c');
                  
            Map<String,String> UserAndContactMap = new Map<String,String>();
            for (Integer i = 1; i <= 30; i++) {
                String lpadI = ('00' + i).right(3);
                String fromColumn = 'From_Column_' + lpadI + '__c';
                if(mpdMapping!=null){
                    String apiStr = String.valueOf(mpdMapping.get(fromColumn));
                    if (String.isBlank(apiStr) == false) {
                        String ssColumn = 'SS_Column_' + lpadI + '__c';
                        String ssApiStr = String.valueOf(mpdMapping.get(ssColumn));
                        UserAndContactMap.put(apiStr,ssApiStr);   
                    }
                }      
         } 
         //20220426  LLIU-CCY9TA you end

        //20220721 you LLIU-CGH8EY start 本部分类-岗位子序列，映射 user上的职种
        SS_BatchColumnMapping__c JobmpdMapping = SS_BatchColumnMapping__c.getValues('HR_Post_To_Job_Category__c');
                  
            Map<String,String> Job_CategoryMap = new Map<String,String>();
            for (Integer i = 1; i <= 30; i++) {
                String lpadI = ('00' + i).right(3);
                String fromColumn = 'From_Column_' + lpadI + '__c';
                if(JobmpdMapping!=null){
                    String apiStr = String.valueOf(JobmpdMapping.get(fromColumn));
                    if (String.isBlank(apiStr) == false) {
                        String ssColumn = 'SS_Column_' + lpadI + '__c';
                        String ssApiStr = String.valueOf(JobmpdMapping.get(ssColumn));
                        Job_CategoryMap.put(apiStr,ssApiStr);   
                    }
                }      
         } 
        //20220721 you LLIU-CGH8EY end
        
       //20220823 you LLIU-CHL8FB start 本部是--solution本部的通过映射，更新用户上的 本部(选项)，如果是其他，那么正常走逻辑
        SS_BatchColumnMapping__c DeptMapping = SS_BatchColumnMapping__c.getValues('HR_Category4_To_Dept__c');
                  
            Map<String,String> DeptMap = new Map<String,String>();
            for (Integer i = 1; i <= 30; i++) {
                String lpadI = ('00' + i).right(3);
                String fromColumn = 'From_Column_' + lpadI + '__c';
                if(DeptMapping!=null){
                    String apiStr = String.valueOf(DeptMapping.get(fromColumn));
                    if (String.isBlank(apiStr) == false) {
                        String ssColumn = 'SS_Column_' + lpadI + '__c';
                        String ssApiStr = String.valueOf(DeptMapping.get(ssColumn));
                        DeptMap.put(apiStr,ssApiStr);   
                    }
                }      
         } 
        //20220823 you LLIU-CHL8FB end

        system.debug(mpdMapping+'==UserAndContactMap=='+UserAndContactMap);
        //获取自定义标签，自己定义，用来空更新数据或处理历史数据
        //在处理历史记录时：职位和职种 如果ods的值为空，那么user对象的这两个字段就不需要更新
        Integer buffer = Integer.valueOf(System.Label.ODS_Null_Update_Sign);
        // 现有用户
        Map<String, User> usrMap = new Map<String, User>();
        // ContactToUser の 変更したか にて判断した項目です
        List<ODS__c> conList = [select id,Alias__c,Branch__c,PositionSubsequence__c,Rank__c,Category3__c,Category4__c,Category5__c,Category6__c,Employee_No__c,Hire_Date__c,FirstName__c,LastName__c,Name__c,Email__c,MobilePhone__c,Post__c,Job_Category__c,Job_Type__c,Product_specialist_incharge_product__c,Sales_Speciality__c,Work_Location__c,Stay_or_not__c,LeaveDate__c,UniqueId__c,Null_Update__c,Salesdepartment__c from ODS__c where Employee_No__c in :userEmployeeNoList];

        List<User> usrList = [select Id, PBI_Enable__c ,PBIAuthorizedSetting__c,Employee_No__c from User where Employee_No__c IN :userEmployeeNoList];
        for (User usr : usrList) {
            //usrMap.put(usr.Employee_No__c, usr);
            //由于测试时，发现ods的员工编码和user的员工编码大小写不一致，所有我们在这里把员工编码全部转为小写
            //所以为了避免以上问题，把员工编码都转为小写
            usrMap.put(usr.Employee_No__c.toLowerCase(), usr);
        }
        
        List<User> updateList = new List<User>();
        List<User> insertList = new List<User>();
        List<String> updateId = new List<String>();
        for (ODS__c odsc : conList) {
            //由于测试时，发现ods的员工编码和user的员工编码大小写不一致，所有我们在这里把员工编码全部转为小写
            // 所以为了避免以上问题，把员工编码都转为小写
            if (usrMap.containsKey(odsc.Employee_No__c.toLowerCase())) {
                // 更新现有用户
                User userData = usrMap.get(odsc.Employee_No__c.toLowerCase());

                userData.Group_sales_dept__c = odsc.Category3__c;//统括本部
                if(String.isNotBlank(odsc.Category4__c)){
                    //20220823 you LLIU-CHL8FB start 
                    if(null!=DeptMap && DeptMap.containsKey(odsc.Category4__c)){
                       userData.Dept__c = DeptMap.get(odsc.Category4__c);//本部
                     }else{
                       userData.Dept__c = odsc.Category4__c;//本部
                     }
                     //20220823 you LLIU-CHL8FB end 
                }
                userData.Category5__c = odsc.Category5__c;//部
                //LLIU-CCS8ZB-当新创建的时候接收人事信息中的课信息，之后不进行更新 thh 20220324 start
                // userData.Category6__c = odsc.Category6__c;//课
                //LLIU-CCS8ZB-当新创建的时候接收人事信息中的课信息，之后不进行更新 thh 20220324 end
                //userData.Employee_No__c = odsc.Employee_No__c;//员工编码
                userData.Hire_Date__c = odsc.Hire_Date__c;//入职日期
                //userData.Email = odsc.Email__c;//电子邮件
                userData.Mobile_Phone__c = odsc.MobilePhone__c;//手机号码
                //如果自定义变迁的值为1，那么证明现在是在处理历史数据，而历史数据规定，如果ods的职位为空，那么就不需要更新user的职种
               //20220425  LLIU-CCY9TA you ods 的 通用职衔   对应用户上新创建的 HR通用职级     断开跟职位的关系

                if(String.isNotBlank(odsc.Post__c) || buffer != 1){
                    //userData.Post__c = odsc.Post__c;//职位
                     userData.HR_Post__c = odsc.Post__c;//HR通用职级
                     system.debug(odsc.Post__c+'===='+UserAndContactMap.containsKey(odsc.Post__c));
                     if(null!=UserAndContactMap && UserAndContactMap.containsKey(odsc.Post__c)){
                         userData.Post__c =  UserAndContactMap.get(odsc.Post__c);
                      }
                }
                //20220426  LLIU-CCY9TA you end
                
                //20220428 LLIU-CDW5ZW you start 
                userData.PositionSubsequence__c = odsc.PositionSubsequence__c;
                //20220428 LLIU-CDW5ZW you end
                //20220512 you LLIU-CDW5ZW start
                userData.Rank__c = odsc.Rank__c;
                //20220428 you LLIU-CDW5ZW end
                
                // 20220721 you LLIU-CGH8EY start 注释，依据本部和岗位子序列 给职种赋值
                /**
                String zz = '';
                if(odsc.Job_Category__c == '服务'){
                    zz = '销售服务';
                }else if(odsc.Job_Category__c == '推广'){
                    zz = '销售推广';
                }else{
                    zz = odsc.Job_Category__c;
                }
                //如果自定义变迁的值为1，那么证明现在是在处理历史数据，而历史数据规定，如果ods的职种为空，那么就不需要更新user的职种
                if(String.isNotBlank(zz) || buffer != 1){
                    userData.Job_Category__c = zz;//职种
                }**/
                String bbz=odsc.Category4__c+'-' +odsc.PositionSubsequence__c; //本部-岗位子序列
                String ldbb=odsc.Salesdepartment__c+'-' +odsc.PositionSubsequence__c; //六大本部-岗位子序列
                String bbz1=odsc.Category5__c+'-' +odsc.PositionSubsequence__c;  //部-岗位子序列
                system.debug(bbz+'==='+ldbb+'==Job_CategoryMap=='+Job_CategoryMap);
                //本部不等于空，看本部
                String zz = '';
                if( (String.isNotBlank(odsc.PositionSubsequence__c) && odsc.PositionSubsequence__c=='供应链管理') || ( String.isNotBlank(odsc.Category4__c) && odsc.Category4__c=='战略创新本部')){
                     zz = '管理';
                }else if( String.isNotBlank(odsc.Category4__c) && odsc.Category4__c=='Solution本部'){
                     zz = '市场';
                }else if(String.isNotBlank(odsc.Category4__c)){
                    if(null!=Job_CategoryMap && Job_CategoryMap.containsKey(bbz)){
                       if(Job_CategoryMap.get(bbz) == '服务'){
                         zz = '销售服务';
                       }else if(Job_CategoryMap.get(bbz) == '推广'){
                         zz = '销售推广';
                       }else{
                         zz = Job_CategoryMap.get(bbz);
                       }   
                    }
                    if(null!=Job_CategoryMap && Job_CategoryMap.containsKey(ldbb)){
                       if(Job_CategoryMap.get(ldbb) == '服务'){
                         zz = '销售服务';
                       }else if(Job_CategoryMap.get(ldbb) == '推广'){
                         zz = '销售推广';
                       }else{
                         zz = Job_CategoryMap.get(ldbb);
                       }  
                    } 
                    
                    system.debug('=='+Job_CategoryMap.get(bbz)+'==='+Job_CategoryMap.get(ldbb)+'==='+zz);
                  }else if(String.isBlank(odsc.Category4__c) && String.isNotBlank(odsc.Category5__c)){
                    //本部等于空，看部
                    if(odsc.Category5__c=='华北东北运营管理部' || odsc.Category5__c=='西北西南运营管理部' || odsc.Category5__c=='西北西南运营支援部' || bbz1=='华北东北服务部-综合行政' || bbz1=='华北东北市场部-综合行政'){
                      zz = '支援'; 
                    }else if(bbz1=='华北东北服务部-FSE'){
                      zz = '销售服务';
                    }else if(odsc.Category5__c=='西部战略推进部' || bbz1=='华北东北市场部-推广'){
                      zz = '销售推广';
                    }
                  }
                  userData.Job_Category__c = zz;

                // 20220721 you LLIU-CGH8EY end

                //userData.Product_specialist_incharge_product__c = odsc.Product_specialist_incharge_product__c;//负责产品（主）
                //userData.Sales_Speciality__c = odsc.Sales_Speciality__c;//销售工作内容
                //HR信息上的工作地更新到用户的工作地（人事）上 thh 2022-02-16 start
                userData.Work_Location_HR__c = odsc.Work_Location__c;
                //HR信息上的工作地更新到用户的工作地（人事）上 thh 2022-02-16 end
                userData.Stay_or_not__c = odsc.Stay_or_not__c;//在职/已离职
                //由于user有一个验证规则，如果值为已离职，那么PBI不能为true，所以手动设置为false，并把PBI对象的值设为false
                if(userData.Stay_or_not__c == '已离职' && userData.PBI_Enable__c){//PBI是否启用
                    userData.PBI_Enable__c = false;
                    updateId.add(userData.id);
                }
                userData.Null_Update__c = odsc.Null_Update__c;
                userData.QuitDate__c = odsc.LeaveDate__c;//离职日期
                userData.IsMEBG__c=true;//是否MEBG
                updateList.add(userData);
            }else{
                //如果没有在user表中找到对应的员工编码，那么新增user
                User userData = new User();
                userData.Group_sales_dept__c = odsc.Category3__c;//统括本部
                if(String.isNotBlank(odsc.Category4__c)){
                     //20220823 you LLIU-CHL8FB start 
                    if(null!=DeptMap && DeptMap.containsKey(odsc.Category4__c)){
                       userData.Dept__c = DeptMap.get(odsc.Category4__c);//本部
                     }else{
                       userData.Dept__c = odsc.Category4__c;//本部
                     }
                     //20220823 you LLIU-CHL8FB end 
                }
                userData.Category5__c = odsc.Category5__c;//部
                userData.Category6__c = odsc.Category6__c;//课
                userData.Employee_No__c = odsc.Employee_No__c;//员工编码
                userData.Hire_Date__c = odsc.Hire_Date__c;//入职日期
                userData.Email = odsc.Email__c;//电子邮件,新建时，填写电子邮件
                userData.Username = '_'+odsc.Email__c;//用户名
                userData.Mobile_Phone__c = odsc.MobilePhone__c;//手机号码
                //如果自定义变迁的值为1，那么证明现在是在处理历史数据，而历史数据规定，如果ods的职位为空，那么就不需要更新user的职种
                //20220426  LLIU-CCY9TA you start
                if(String.isNotBlank(odsc.Post__c) || buffer != 1){
                    //userData.Post__c = odsc.Post__c;//职位
                    userData.HR_Post__c = odsc.Post__c;//HR通用职级
                    if(null!=UserAndContactMap && UserAndContactMap.containsKey(odsc.Post__c)){
                         userData.Post__c =  UserAndContactMap.get(odsc.Post__c);
                      }
                }
                //20220426  LLIU-CCY9TA you end
                
                //20220428 LLIU-CDW5ZW you start 
                userData.PositionSubsequence__c = odsc.PositionSubsequence__c;
                //20220428 LLIU-CDW5ZW you end
                //20220512 you LLIU-CDW5ZW start
                userData.Rank__c = odsc.Rank__c;
                //20220428 you LLIU-CDW5ZW end
                // 20220721 you LLIU-CGH8EY start 注释，依据本部和岗位子序列 给职种赋值
                /**
                String zz = '';
                if(odsc.Job_Category__c == '服务'){
                    zz = '销售服务';
                }else if(odsc.Job_Category__c == '推广'){
                    zz = '销售推广';
                }else{
                    zz = odsc.Job_Category__c;
                }
                //如果自定义变迁的值为1，那么证明现在是在处理历史数据，而历史数据规定，如果ods的职种为空，那么就不需要更新user的职种
                if(String.isNotBlank(zz) || buffer != 1){
                    userData.Job_Category__c = zz;//职种
                }**/
                String bbz=odsc.Category4__c+'-' +odsc.PositionSubsequence__c; //本部-岗位子序列
                String ldbb=odsc.Salesdepartment__c+'-' +odsc.PositionSubsequence__c; //六大本部-岗位子序列
                String bbz1=odsc.Category5__c+'-' +odsc.PositionSubsequence__c;  //部-岗位子序列
                //本部不等于空，看本部
                String zz = '';
                if( (String.isNotBlank(odsc.PositionSubsequence__c) && odsc.PositionSubsequence__c=='供应链管理') || ( String.isNotBlank(odsc.Category4__c) && odsc.Category4__c=='战略创新本部')){
                     zz = '管理';
                }else if( String.isNotBlank(odsc.Category4__c) && odsc.Category4__c=='Solution本部'){
                     zz = '市场';
                }else if(String.isNotBlank(odsc.Category4__c)){
                    if(null!=Job_CategoryMap && Job_CategoryMap.containsKey(bbz)){
                       if(Job_CategoryMap.get(bbz) == '服务'){
                         zz = '销售服务';
                       }else if(Job_CategoryMap.get(bbz) == '推广'){
                         zz = '销售推广';
                       }else{
                         zz = Job_CategoryMap.get(bbz);
                       }   
                    }
                    if(null!=Job_CategoryMap && Job_CategoryMap.containsKey(ldbb)){
                       if(Job_CategoryMap.get(ldbb) == '服务'){
                         zz = '销售服务';
                       }else if(Job_CategoryMap.get(ldbb) == '推广'){
                         zz = '销售推广';
                       }else{
                         zz = Job_CategoryMap.get(ldbb);
                       }  
                    } 
                    
                  }else if(String.isBlank(odsc.Category4__c) && String.isNotBlank(odsc.Category5__c)){
                    //本部等于空，看部 LLIU-CKE3UG 增加映射关系
                    if(odsc.Category5__c=='华北东北运营管理部' || odsc.Category5__c=='西北西南运营管理部' || odsc.Category5__c=='西北西南运营支援部' || bbz1=='华北东北服务部-综合行政' || bbz1=='华北东北市场部-综合行政'){
                      zz = '支援'; 
                    }else if(bbz1=='华北东北服务部-FSE'){
                      zz = '销售服务';
                    }else if(odsc.Category5__c=='西部战略推进部' || bbz1=='华北东北市场部-推广'){
                      zz = '销售推广';
                    }
                  }
                  userData.Job_Category__c = zz;

                // 20220721 you LLIU-CGH8EY end
                userData.Null_Update__c = odsc.Null_Update__c;
                userData.Product_specialist_incharge_product__c = odsc.Product_specialist_incharge_product__c;//负责产品（主）
                userData.Sales_Speciality__c = odsc.Sales_Speciality__c;//销售工作内容
                //如果根据HR信息新建用户,则把HR信息的工作地传给用户的工作地和工作地（人事） thh 2022-02-16 start
                userData.Work_Location_HR__c = odsc.Work_Location__c;
                userData.Work_Location__c = odsc.Work_Location__c;
                //如果根据HR信息新建用户,则把HR信息的工作地传给用户的工作地和工作地（人事） thh 2022-02-16 end
                userData.Stay_or_not__c = odsc.Stay_or_not__c;//在职/已离职
                userData.QuitDate__c = odsc.LeaveDate__c;//离职日期
                userData.IsMEBG__c=true;//是否MEBG
                //由于ods的姓和名都是拼音，所以获取name__c的值，并且首字母第一位为姓，其余为名
                if(String.isNotBlank(odsc.Name__c)){
                    if(odsc.Name__c.length() > 1){
                        userData.LastName = odsc.Name__c.substring(0,1);
                        userData.FirstName = odsc.Name__c.substring(1,odsc.Name__c.length());
                        userData.Alias = odsc.Name__c;
                    }
                }
                //以下是系统默认
                userData.FederationIdentifier = odsc.Employee_No__c + '@olympus.com.cn';
                userData.EmailEncodingKey = 'UTF-8';//电子邮件编码
                userData.IsActive = false;
                userData.TimeZoneSidKey = 'Asia/Shanghai';//时区
                userData.LocaleSidKey = 'ja_JP';//区域
                userData.LanguageLocaleKey = 'zh_CN';//语言
                //userData.DefaultCurrencyIsoCode = 'CNY';//默认币种 ISO 代码
                //userData.CurrencyIsoCode = 'CNY';//信息币种
                //默认ods创建的user用户的简档为  999_看不见Profile
                userData.Profileid = '00e10000000dFYJ';

                insertList.add(userData);
            }
        }

        //PBI数据更新
        //由于user有一个验证规则，如果值变为已离职，那么PBI不能为true，所以手动设置为false，并把PBI对象的值设为false
        if(updateId.size() > 0){
            List<PBIAuthorization__c> pbiUpd = [select id,name,PBI_Enable__c,User__c from PBIAuthorization__c where user__c in :updateId and PBI_Enable__c = true];
            if(pbiUpd != null && pbiUpd.size() > 0){
                for(PBIAuthorization__c pc : pbiUpd){
                    pc.PBI_Enable__c = false;
                }
            }
            //首先更新 PBI权限为false
            if(pbiUpd.size() > 0){
                update pbiUpd;
            }
        }
        if(insertList.size() > 0 || updateList.size() > 0){
            ID jobId = system.enqueueJob(new UserUpsertQueueable(insertList,updateList));
            AsyncApexJob jobInfo = [select status,NumberOfErrors from AsyncApexJob where id =:jobId];
            System.debug('--------------------队列日志'+jobInfo);
        }
    }
    //add   wangweipeng                    2021/11/18               start

    @future (callout=true)
    public static void upsertFutureContact(String sessionId, List<Id> userIdList) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/UserToContact');
System.debug('Endpoint ' + req.getEndpoint());
        req.setMethod('POST');

        // header
        String authorizationHeader = 'OAuth ' + sessionId;
System.debug(authorizationHeader);
        req.setHeader('Authorization', authorizationHeader);
        
        // body
        String restBody = '{"userIdList":' + JSON.serialize(userIdList) + '}';
System.debug('JSON ' + restBody);
        req.setBody(restBody);

        // Create a new http object to send the request object
        Http http = new Http();
        HTTPResponse res = http.send(req);
System.debug(res.getBody());
    }
    
    public static List<Daily_Report__c> reportSelectById(String id){
        List<Daily_Report__c> reportList = [select id, name, Reporter__c, Reported_Date__c, Daily_Report_Data_Type__c,
                                            Working_Time_From__c, Working_Time_To__c, Status__c, Mail_Send_Check__c,
                                            Business_Trip__c, Submit_Date_New__c, Submit_DateTime_New__c, Approved_Date__c,
                                            Approved_DateTime__c, CreatedById, Feed_Back_From_Manager__c, FeedbackManager__c,
                                            Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c,
                                            Activity_ID__c, Manager_Mail__c, Status_With_Check__c
                                            from Daily_Report__c where Id = :id];
        return reportList;
    }
    
    public static List<Event> eventSelectByUsers(String soql, List<Date> mdates, List<Id> users) {
        return Database.query(soql);
    }
    public static Map<Id, Daily_Report__c> reportMapSelectByIds(List<Id> ids){
        Map<Id, Daily_Report__c> reportMap = new Map<Id, Daily_Report__c>([select id, Status__c, Submit_Date_New__c
                                            from Daily_Report__c where Id IN :ids]);
        return reportMap;
    }
    
    public static List<Opportunity> oppSelectForPersonTaget(Id rtId, User[] users, String currentPeriod) {
        Opportunity[] opportunitys = [select
                        Id, OwnerId, Opportunity_Category__c, Proportion__c, CloseDate,
                        Amount, Objective__c, Target_category__c,
                        SAP_Province__c, RecordTypeId, OCM_Target_period__c
                 from Opportunity
                where Target_category__c = '担当目标'
                  and RecordTypeId = :rtId
                  and OwnerId in :users
                  and OCM_Target_period__c = :currentPeriod
                ];
        return opportunitys;
    }

    public static List<Opportunity> oppSelectForLock(List<String> oppIds) {
        List<Opportunity> opps = [select Id
                ,Last_Visit_Scheduled_Date__c
                ,Xin_Last_Follow_Up_Date_For_Report__c, Xin_Gross_Follow_Num__c,Visit_President_Count__c,Visit_Head_Doctor_Count__c,Num_Of_NTC__c
                // CHAN-BE6CZZ 最后跟进结果 LHJ 20190724 Start
                ,Follow_up_comment__c 
                // CHAN-BE6CZZ 最后跟进结果 LHJ 20190724 End
                ,Num_Of_OPD__c
            from Opportunity where Id in :oppIds for update];
        return opps;
    }
    
    public static List<Opportunity> oppSelectForCity(List<String> oppIds) {
        List<Opportunity> opps = [select Id, Account.Parent.RecordTypeId, Account.Parent.Parent.RecordTypeId, Account.Parent.Parent.City_Master__r.Name, Account.City_Master__r.Name from Opportunity where Id in :oppIds];
        return opps;
    }
    
    public static void updOppList(List<Opportunity> oppUpdateList){
        if (oppUpdateList != null && oppUpdateList.size() > 0) update oppUpdateList;
    }
    
    public static void updOpp(Opportunity opp) {
        update opp;
    }
    
    public static List<Opportunity2__c> opp2SelectForSync(List<String> oppIds) {
        List<Opportunity2__c> opp2s = [select Id, Opportunity__c from Opportunity2__c where Opportunity__c in :oppIds];
        return opp2s;
    }
    
    public static List<Product2__c> pr2SelectForSync(List<Product2> pr2Ids) {
        List<Product2__c> pr2s = [select Id, Product2__c from Product2__c where Product2__c in :pr2Ids];
        return pr2s;
    }
    
    public static List<Maintenance_Contract__c> mcSelectForLock(List<String> serviceIds) {
        List<Maintenance_Contract__c> mcs = [select Id, Xin_Last_Follow_Day__c from Maintenance_Contract__c where Id in :serviceIds for update];
        return mcs;
    }
    
    public static void delEvent1ForTrigger(List<String> conIds) {
        List<Activity_History_Daily_Report__c> ahdrList = [select Id from Activity_History_Daily_Report__c where Contact__c in :conIds];
        if (ahdrList.size() > 0) delete ahdrList;
    }
    
    public static void delEvent2ForTrigger(List<String> oppIds) {
        List<Event_Oppotunity__c> eoList = [select Id from Event_Oppotunity__c where Opportunity__c in :oppIds];
        if (eoList.size() > 0) delete eoList;
    }
    
    public static void delEvent3ForTrigger(List<String> mcIds) {
        List<Event_Service__c> esList = [select Id from Event_Service__c where Service__c in :mcIds];
        if (esList.size() > 0) delete esList;
    }
    
    public static void upsEventC(List<Event__c> acts) {
        System.debug('Event__c1111' + acts);
        if(acts.size() > 0) upsert acts;
    }
    
    public static void upsEvent(List<Event> acts) {
        if(acts.size() > 0) upsert acts;
    }
    
    public static void delEvent(Set<String> eventCIdSet, Map<Id, Event__c> eventC_eventMap) {
        // 削除する前に、delete_flgをtrueにする
        List<Event> delList = [select Id from Event where EventC_ID__c in :eventCIdSet];
        ControllerUtil.delEventIdSet.addAll((new Map<Id, SObject>(delList)).keySet());
        if (delList.size() > 0) {
            delete delList;
        }
        // Event__cにEventへの参照IDがある
        delList = [select Id from Event where Id in :eventC_eventMap.keySet()];
        ControllerUtil.delEventIdSet.addAll((new Map<Id, SObject>(delList)).keySet());
        if (delList.size() > 0) {
            delete delList;
        }
    }
    
    public static void delEventOnly(String Id) {
        List<Event> delList = [select Id from Event where id = :Id];
        if (delList.size() > 0) {
            delete delList;
        }
    }
    
    public static void insSFDelete(List<SFDelete__c> dlist) {
        if (dlist.size() > 0) insert dList;
    }
    
    public static void upsEventC2Event(Map<Id, Event__c> eventCMap, Map<Id, Event__c> eventC_eventMap) {
        List<Event> unDelList = new List<Event>();
        List<Event> upsList = new List<Event>();
        List<Id> updateEIds = new List<Id>();
        //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 start
        Set<String> idSet = new Set<String>();
        //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 end
        Map<String, String> dupUpdIdMap = new Map<String, String>();
        
        // 日報画面からEvent__cを更新する時
        // ①EventにEvent__cへの参照IDがある
        // IsArchived = false を条件に追加することにより、１年以上の場合Event_CからEventへ同期しません！！
        if (eventCMap.keySet().size() > 0) {
            List<Event> eList = [select Id, EventC_ID__c, IsDeleted from Event where EventC_ID__c in :eventCMap.keySet() and IsArchived = false all rows];
            if (eList.size() > 0) {
                for (Event e : eList) {
                    updateEIds.add(e.Id);
                    Event__c ec = eventCMap.get(e.EventC_ID__c);
System.debug('EventにEvent__cへの参照IDがある:::::' + e.Id + ',' + e.EventC_ID__c);
System.debug('ec.Subject__c:::::'+ec.Subject__c);
System.debug('ec.StartDateTime__c:::::'+ec.StartDateTime__c);
System.debug('ec.EndDateTime__c:::::'+ec.EndDateTime__c);
System.debug('ec.DurationInMinutes:::::' + Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60));
System.debug('ec.Daily_Report__c:::::'+ec.Daily_Report__c);
System.debug('ec.Main_Visit_Location__c:::::'+ec.Main_Visit_Location__c);
System.debug('ec.Activity_Type2__c:::::'+ec.Activity_Type2__c);
System.debug('ec.Purpose_Type__c:::::'+ec.Purpose_Type__c);
System.debug('ec.Location__c:::::'+ec.Location__c);
System.debug('ec.Related_Opportunity1__c:::::'+ec.Related_Opportunity1__c);
System.debug('ec.Related_Opportunity1_ID__c:::::'+ec.Related_Opportunity1_ID__c);
System.debug('ec.Related_Service1__c:::::'+ec.Related_Service1__c);
System.debug('ec.Related_Service1_ID__c:::::'+ec.Related_Service1_ID__c);
System.debug('ec.whatid__c:::::'+ec.whatid__c);
                    e.Subject = (ec.Subject__c==null||ec.Subject__c=='')?ec.Activity_Purpose__c:ec.Subject__c;
                    e.IsAllDayEvent = false;
                    e.ActivityDateTime = ec.StartDateTime__c;
                    e.StartDateTime = ec.StartDateTime__c;
                    e.EndDateTime = ec.EndDateTime__c;
                    e.DurationInMinutes = Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60);
                    e.Main_Visit_Location__c = ec.Main_Visit_Location__c;
                    e.Activity_Type2__c = ec.Activity_Type2__c;
                    e.Purpose_Type__c = ec.Purpose_Type__c;
                    e.Purpose_TypeFSE__c = ec.Purpose_TypeFSE__c;
                    e.Purpose_TypeEscFSE__c = ec.Purpose_TypeEscFSE__c;
                    e.Location = String.isBlank(ec.Location__c) ? ec.Visitor_Place_Free__c : ec.Location__c;
                    e.Related_Opportunity1__c = ec.Related_Opportunity1__c;
                    e.Related_Opportunity1_ID__c = ec.Related_Opportunity1_ID__c;
                    e.Related_Opportunity2__c = ec.Related_Opportunity2__c;
                    e.Related_Opportunity2_ID__c = ec.Related_Opportunity2_ID__c;
                    e.Related_Opportunity3__c = ec.Related_Opportunity3__c;
                    e.Related_Opportunity3_ID__c = ec.Related_Opportunity3_ID__c;
                    e.Related_Opportunity4__c = ec.Related_Opportunity4__c;
                    e.Related_Opportunity4_ID__c = ec.Related_Opportunity4_ID__c;
                    e.Related_Opportunity5__c = ec.Related_Opportunity5__c;
                    e.Related_Opportunity5_ID__c = ec.Related_Opportunity5_ID__c;
                    e.Related_Service1__c = ec.Related_Service1__c;
                    e.Related_Service1_ID__c = ec.Related_Service1_ID__c;
                    e.Visitor1__c = ec.Visitor1__c;
                    e.Visitor2__c = ec.Visitor2__c;
                    e.Visitor3__c = ec.Visitor3__c;
                    e.Visitor4__c = ec.Visitor4__c;
                    e.Visitor5__c = ec.Visitor5__c;
                    e.Visitor1_ID__c = ec.Visitor1_ID__c;
                    e.Visitor2_ID__c = ec.Visitor2_ID__c;
                    e.Visitor3_ID__c = ec.Visitor3_ID__c;
                    e.Visitor4_ID__c = ec.Visitor4_ID__c;
                    e.Visitor5_ID__c = ec.Visitor5_ID__c;
                    e.Activity_Purpose__c = ec.Activity_Purpose__c;
                    e.Activity_PurposeFSE__c = ec.Activity_PurposeFSE__c;
                    e.Activity_PurposeEscFSE__c = ec.Activity_PurposeEscFSE__c;
                    e.whatid__c = ec.whatid__c;
                    e.EventC_ID__c = ec.Id;
                    e.WhatId = ec.Daily_Report__c;
                    e.IsScheduled__c = ec.IsScheduled__c;
                    e.BeforeActivityDate__c = ec.BeforeActivityDate__c;
                    e.AppCdId__c = ec.AppCdId__c;
                    e.SyncCreatedDate__c = ec.SyncCreatedDate__c;
                    e.WS_flg__c = false;
                    if (e.IsDeleted) {
System.debug('e.IsDeleted:::::'+e.IsDeleted);
                        unDelList.add(e);
                    }
                    if (ec.Activity_Type2__c == 'Holiday') {
                        e.ShowAs = 'OutOfOffice';
                    }
                    upsList.add(e);
                    eventCMap.remove(e.EventC_ID__c);  // 更新したものをMapから削除
                    dupUpdIdMap.put(e.Id, e.Id);
                }
            }
        }
        List<Event__c> ecList = eventCMap.values();
        // ②参照IDあるものを除いて、新規
        if (ecList.size() > 0) {
            List<Event> insE = new List<Event>();
            for (Event__c ec : ecList) {
                // Event__cにEvent_ID__cがない、つまり日報画面から作成された時
                if (ec.Event_ID__c == null) {
System.debug('Event__cにEvent_ID__cがない、つまり日報画面から作成された時:::::' + ec.Id);
System.debug('ec.Subject__c:::::'+ec.Subject__c);
System.debug('ec.StartDateTime__c:::::'+ec.StartDateTime__c);
System.debug('ec.EndDateTime__c:::::'+ec.EndDateTime__c);
System.debug('ec.DurationInMinutes:::::' + Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60));
System.debug('ec.Daily_Report__c:::::'+ec.Daily_Report__c);
System.debug('ec.Main_Visit_Location__c:::::'+ec.Main_Visit_Location__c);
System.debug('ec.Activity_Type2__c:::::'+ec.Activity_Type2__c);
System.debug('ec.Purpose_Type__c:::::'+ec.Purpose_Type__c);
System.debug('ec.Location__c:::::'+ec.Location__c);
System.debug('ec.Related_Opportunity1__c:::::'+ec.Related_Opportunity1__c);
System.debug('ec.Related_Opportunity1_ID__c:::::'+ec.Related_Opportunity1_ID__c);
System.debug('ec.Related_Service1__c:::::'+ec.Related_Service1__c);
System.debug('ec.Related_Service1_ID__c:::::'+ec.Related_Service1_ID__c);
System.debug('ec.whatid__c:::::'+ec.whatid__c);
                    Event e = new Event(
                        OwnerId = ec.Reporter__c,
                        Subject = (ec.Subject__c==null||ec.Subject__c=='')?ec.Activity_Purpose__c:ec.Subject__c,
                        IsAllDayEvent = false,
                        ActivityDateTime = ec.StartDateTime__c,
                        StartDateTime = ec.StartDateTime__c,
                        EndDateTime = ec.EndDateTime__c,
                        DurationInMinutes = Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60),
                        Main_Visit_Location__c = ec.Main_Visit_Location__c,
                        Activity_Type2__c = ec.Activity_Type2__c,
                        Purpose_Type__c = ec.Purpose_Type__c,
                        Purpose_TypeFSE__c = ec.Purpose_TypeFSE__c,
                        Purpose_TypeEscFSE__c = ec.Purpose_TypeEscFSE__c,
                        Location = String.isBlank(ec.Location__c) ? ec.Visitor_Place_Free__c : ec.Location__c,
                        Related_Opportunity1__c = ec.Related_Opportunity1__c,
                        Related_Opportunity1_ID__c = ec.Related_Opportunity1_ID__c,
                        Related_Opportunity2__c = ec.Related_Opportunity2__c,
                        Related_Opportunity2_ID__c = ec.Related_Opportunity2_ID__c,
                        Related_Opportunity3__c = ec.Related_Opportunity3__c,
                        Related_Opportunity3_ID__c = ec.Related_Opportunity3_ID__c,
                        Related_Opportunity4__c = ec.Related_Opportunity4__c,
                        Related_Opportunity4_ID__c = ec.Related_Opportunity4_ID__c,
                        Related_Opportunity5__c = ec.Related_Opportunity5__c,
                        Related_Opportunity5_ID__c = ec.Related_Opportunity5_ID__c,
                        Related_Service1__c = ec.Related_Service1__c,
                        Related_Service1_ID__c = ec.Related_Service1_ID__c,
                        Visitor1__c = ec.Visitor1__c,
                        Visitor2__c = ec.Visitor2__c,
                        Visitor3__c = ec.Visitor3__c,
                        Visitor4__c = ec.Visitor4__c,
                        Visitor5__c = ec.Visitor5__c,
                        Visitor1_ID__c = ec.Visitor1_ID__c,
                        Visitor2_ID__c = ec.Visitor2_ID__c,
                        Visitor3_ID__c = ec.Visitor3_ID__c,
                        Visitor4_ID__c = ec.Visitor4_ID__c,
                        Visitor5_ID__c = ec.Visitor5_ID__c,
                        Activity_Purpose__c = ec.Activity_Purpose__c,
                        Activity_PurposeFSE__c = ec.Activity_PurposeFSE__c,
                        Activity_PurposeEscFSE__c = ec.Activity_PurposeEscFSE__c,
                        whatid__c = ec.whatid__c,
                        EventC_ID__c = ec.Id,
                        IsScheduled__c = ec.IsScheduled__c,
                        WhatId = ec.Daily_Report__c,
                        BeforeActivityDate__c = ec.BeforeActivityDate__c,
                        AppCdId__c = ec.AppCdId__c,
                        SyncCreatedDate__c = ec.SyncCreatedDate__c,
                        WS_flg__c = false,
                        EventStatus__c = '02 接受'
                    );
                    if (ec.Activity_Type2__c == 'Holiday') {
                        e.ShowAs = 'OutOfOffice';
                    }
                    upsList.add(e);
                    //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 start
                    //报告一览新建事件时,将事件的Id赋值到报告一览上
                    idSet.add(ec.Id);
                    //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 end
                } else {
                    // シンプルから遷移する場合、Event_ID__c必ずあるから、パス
                }
            }
        }

        // Event__cにEventへの参照IDがある
        if (eventC_eventMap.keySet().size() > 0) {
            List<Event> eList = [select Id, IsDeleted from Event where Id in :eventC_eventMap.keySet() and IsArchived = false all rows];
            if (eList.size() > 0) {
                for (Event e : eList) {
                    if (dupUpdIdMap.containsKey(e.Id)) {
                        continue;
                    }
                    updateEIds.add(e.Id);
                    Event__c ec = eventC_eventMap.get(e.Id);
System.debug('Event__cにEventへの参照IDがある:::::' + e.Id + ',' + ec.Id);
System.debug('ec.Subject__c:::::'+ec.Subject__c);
System.debug('ec.StartDateTime__c:::::'+ec.StartDateTime__c);
System.debug('ec.EndDateTime__c:::::'+ec.EndDateTime__c);
System.debug('ec.DurationInMinutes:::::' + Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60));
System.debug('ec.Daily_Report__c:::::'+ec.Daily_Report__c);
System.debug('ec.Main_Visit_Location__c:::::'+ec.Main_Visit_Location__c);
System.debug('ec.Activity_Type2__c:::::'+ec.Activity_Type2__c);
System.debug('ec.Purpose_Type__c:::::'+ec.Purpose_Type__c);
System.debug('ec.Location__c:::::'+ec.Location__c);
System.debug('ec.Related_Opportunity1__c:::::'+ec.Related_Opportunity1__c);
System.debug('ec.Related_Opportunity1_ID__c:::::'+ec.Related_Opportunity1_ID__c);
System.debug('ec.Related_Service1__c:::::'+ec.Related_Service1__c);
System.debug('ec.Related_Service1_ID__c:::::'+ec.Related_Service1_ID__c);
System.debug('ec.whatid__c:::::'+ec.whatid__c);
                    e.Subject = (ec.Subject__c==null||ec.Subject__c=='')?ec.Activity_Purpose__c:ec.Subject__c;
                    e.IsAllDayEvent = false;
                    e.ActivityDateTime = ec.StartDateTime__c;
                    e.StartDateTime = ec.StartDateTime__c;
                    e.EndDateTime = ec.EndDateTime__c;
                    e.DurationInMinutes = Integer.valueOf((ec.EndDateTime__c.getTime() - ec.StartDateTime__c.getTime()) / 1000 / 60);
                    e.Main_Visit_Location__c = ec.Main_Visit_Location__c;
                    e.Activity_Type2__c = ec.Activity_Type2__c;
                    e.Purpose_Type__c = ec.Purpose_Type__c;
                    e.Purpose_TypeFSE__c = ec.Purpose_TypeFSE__c;
                    e.Purpose_TypeEscFSE__c = ec.Purpose_TypeEscFSE__c;
                    e.Location = String.isBlank(ec.Location__c) ? ec.Visitor_Place_Free__c : ec.Location__c;
                    e.Related_Opportunity1__c = ec.Related_Opportunity1__c;
                    e.Related_Opportunity1_ID__c = ec.Related_Opportunity1_ID__c;
                    e.Related_Opportunity2__c = ec.Related_Opportunity2__c;
                    e.Related_Opportunity2_ID__c = ec.Related_Opportunity2_ID__c;
                    e.Related_Opportunity3__c = ec.Related_Opportunity3__c;
                    e.Related_Opportunity3_ID__c = ec.Related_Opportunity3_ID__c;
                    e.Related_Opportunity4__c = ec.Related_Opportunity4__c;
                    e.Related_Opportunity4_ID__c = ec.Related_Opportunity4_ID__c;
                    e.Related_Opportunity5__c = ec.Related_Opportunity5__c;
                    e.Related_Opportunity5_ID__c = ec.Related_Opportunity5_ID__c;
                    e.Related_Service1__c = ec.Related_Service1__c;
                    e.Related_Service1_ID__c = ec.Related_Service1_ID__c;
                    e.Visitor1__c = ec.Visitor1__c;
                    e.Visitor2__c = ec.Visitor2__c;
                    e.Visitor3__c = ec.Visitor3__c;
                    e.Visitor4__c = ec.Visitor4__c;
                    e.Visitor5__c = ec.Visitor5__c;
                    e.Visitor1_ID__c = ec.Visitor1_ID__c;
                    e.Visitor2_ID__c = ec.Visitor2_ID__c;
                    e.Visitor3_ID__c = ec.Visitor3_ID__c;
                    e.Visitor4_ID__c = ec.Visitor4_ID__c;
                    e.Visitor5_ID__c = ec.Visitor5_ID__c;
                    e.Activity_Purpose__c = ec.Activity_Purpose__c;
                    e.Activity_PurposeFSE__c = ec.Activity_PurposeFSE__c;
                    e.Activity_PurposeEscFSE__c = ec.Activity_PurposeEscFSE__c;
                    e.whatid__c = ec.whatid__c;
                    e.EventC_ID__c = ec.Id;
                    e.IsScheduled__c = ec.IsScheduled__c;
                    e.WhatId = ec.Daily_Report__c;
                    e.BeforeActivityDate__c = ec.BeforeActivityDate__c;
                    e.AppCdId__c = ec.AppCdId__c;
                    e.SyncCreatedDate__c = ec.SyncCreatedDate__c;
                    e.WS_flg__c = false;
                    if (e.IsDeleted) {
System.debug('e.IsDeleted:::::'+e.IsDeleted);
                        unDelList.add(e);
                    }
                    if (ec.Activity_Type2__c == 'Holiday') {
                        e.ShowAs = 'OutOfOffice';
                    }
                    upsList.add(e);
                }
            }
        }
        StaticParameter.NotUpdEventCFlg = true;
        if (unDelList.size() > 0) undelete unDelList;
        if (upsList.size() > 0) {
            List<Event> eList = [select EventC_ID__c, IsDeleted, Related_Opportunity1_ID__c,WhatId, WhoID from Event where Id in :updateEIds and IsArchived = false for update];
System.debug('upsert 直前 start');
            for (Event e : eList) {
System.debug('e.Id:::::'+e.Id);
System.debug('e.EventC_ID__c:::::'+e.EventC_ID__c);
System.debug('e.IsDeleted:::::'+e.IsDeleted);
System.debug('e.Related_Opportunity1_ID__c:::::'+e.Related_Opportunity1_ID__c);
System.debug('e.WhatId:::::'+e.WhatId);
System.debug('e.WhoID:::::'+e.WhoID);
            }
System.debug('upsert 直前 end');
            upsert upsList;
            //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 start
            //根据IdSet 给报告一览的事件Id赋值
            List<Event__c> needUpdateEvent = new List<Event__c>();
            for(event e :upsList){
               if( IdSet.contains(e.EventC_ID__c) ){
                  Event__c ec = new Event__c();
                  ec.Id = e.EventC_ID__c;
                  ec.Event_ID__c = e.Id;
                  needUpdateEvent.add(ec);
               }
            }

            if(needUpdateEvent.size()>0){
                update needUpdateEvent;
            }
            //2021-08-30 mzy SWAG-C5784H 【委托】事件无法延期 start

        }
    }
    
    public static void eventDelIns(Set<Id> actDelListForDelIns, 
            List<Activity_History_Daily_Report__c> ahdrUpSertList, List<Event_Oppotunity__c> eoUpSertList,List<Event_Service__c> esUpSertList){
        // 取引先責任者、引合、サービス契約の活動は delete insert する
        List<Activity_History_Daily_Report__c> ahdrDelList = [select id from Activity_History_Daily_Report__c where EventC_ID__c =:actDelListForDelIns ];
        List<Event_Oppotunity__c> eoDelList = [select id from Event_Oppotunity__c where EventC_ID__c =:actDelListForDelIns ];
        List<Event_Service__c> esDelList = [select id from Event_Service__c where EventC_ID__c =:actDelListForDelIns ];

        if(ahdrDelList.size() > 0){
            delete ahdrDelList;
        }
        if(eoDelList.size() > 0){
            delete eoDelList;
        }
        if(esDelList.size() > 0){
            delete esDelList;
        }
        if(ahdrUpSertList.size() > 0){
            insert ahdrUpSertList;
        }
        if(eoUpSertList.size() > 0){
            insert eoUpSertList;
        }
        if(esUpSertList.size() > 0){
            insert esUpSertList;
        }
    }
    
    public static void eventDel(String delId){
        List<Event__c> ecList = [select id from Event__c where Id =:delId];
        if(ecList.size() > 0){
            delete ecList;
        }
        
        List<Report__c> rList = [select id, Delete_Flg__c from Report__c where Event_Id__c =:delId];
        if(rList.size() > 0){
            delete rList;
        }
        
        List<Visit_Report__c> vrList = [select id, Delete_Flg__c from Visit_Report__c where Event_Id__c =:delId];
        if(vrList.size() > 0){
            delete vrList;
        }
        
        List<QIS_Report__c> qrList = [select id from QIS_Report__c where Event_Id__c =:delId];
        if(qrList.size() > 0){
            delete qrList;
        }
        
        List<Activity_History_Daily_Report__c> e1List = [select id from Activity_History_Daily_Report__c where EventC_Id__c =:delId];
        if(e1List.size() > 0){
            delete e1List;
        }
        
        List<Event_Oppotunity__c> e2List = [select id from Event_Oppotunity__c where EventC_Id__c =:delId];
        if(e2List.size() > 0){
            delete e2List;
        }
        
        List<Event_Service__c> e3List = [select id from Event_Service__c where EventC_Id__c =:delId];
        if(e3List.size() > 0){
            delete e3List;
        }
    }
    
    public static void insOpp2List(List<Opportunity2__c> opp2List){
        if (opp2List != null && opp2List.size() > 0) insert opp2List;
    }
    public static void updOpp2List(List<Opportunity2__c> opp2List){
        if (opp2List != null && opp2List.size() > 0) update opp2List;
    }
    public static void delOpp2List(List<Opportunity2__c> opp2List){
        if (opp2List != null && opp2List.size() > 0) delete opp2List;
    }

    public static void insPr2List(List<Product2__c> pr2List){
        if (pr2List != null && pr2List.size() > 0) insert pr2List;
    }
    public static void updelPr2List(List<Product2__c> updPr2List, List<Product2__c> delPr2List){
        if (updPr2List != null && updPr2List.size() > 0) update updPr2List;
        if (delPr2List != null && delPr2List.size() > 0) delete delPr2List;
    }
    public static void delPr2List(List<Product2__c> pr2List){
        if (pr2List != null && pr2List.size() > 0) delete pr2List;
    }
    
    public static void insMBAccountList(List<MB_Account__c> mbaccList){
        if (mbaccList != null && mbaccList.size() > 0) insert mbaccList;
    }
    public static void delMBAccountList(List<Account> accountIds){
        List<MB_Account__c> mbaccs = [select Id, Account__c from MB_Account__c where Account__c in :accountIds];
        if (mbaccs != null && mbaccs.size() > 0) delete mbaccs;
    }
    
    public static void updMBAccountList(List<Account> accountIds){
        List<MB_Account__c> mbaccs = [select Id, Account__r.HP_146POCM_Category_From_Dept__c, Account__r.Province_formula__c, Account__r.Department_Class_Name__c from MB_Account__c where Account__c in :accountIds];
        if (mbaccs.size() > 0) {
            for (MB_Account__c mbacc : mbaccs) {
                mbacc.Opp_OCM_text__c = mbacc.Account__r.HP_146POCM_Category_From_Dept__c;
                mbacc.State_Text__c = mbacc.Account__r.Province_formula__c;
                mbacc.Opportunity_Category_text__c = mbacc.Account__r.Department_Class_Name__c;
            }
            update mbaccs;
        }
    }
    
    // 診療科配下のMBテーブルを更新
    public static void updMBChildFromDpt(Map<Id, Account> accDptMap) {
        if (accDptMap.keySet().size() == 0) return;
        List<MB_Repair__c> mbRepList = [Select Id, Repair__r.Account__c from MB_Repair__c where Repair__r.Account__c IN :accDptMap.keySet()];
        if (mbRepList.size() > 0) {
            for (MB_Repair__c mb : mbRepList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Repair__r.Account__c).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Repair__r.Account__c).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Repair__r.Account__c).Department_Class_Name__c;
            }
            update mbRepList;
        }
        List<MB_Event__c> mbEvtList = [Select Id, Event__r.Account_ID__c from MB_Event__c where Event__r.Account_ID__c IN :accDptMap.keySet()];
        if (mbEvtList.size() > 0) {
            for (MB_Event__c mb : mbEvtList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Event__r.Account_ID__c).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Event__r.Account_ID__c).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Event__r.Account_ID__c).Department_Class_Name__c;
            }
            update mbEvtList;
        }
        List<MB_Report__c> mbRptList = [Select Id, Report__r.Hospital_Department__c from MB_Report__c where Report__r.Hospital_Department__c IN :accDptMap.keySet()];
        if (mbRptList.size() > 0) {
            for (MB_Report__c mb : mbRptList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Report__r.Hospital_Department__c).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Report__r.Hospital_Department__c).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Report__r.Hospital_Department__c).Department_Class_Name__c;
            }
            update mbRptList;
        }
        List<MB_Maintenance_Contract__c> mbmcList = [Select Id, Maintenance_Contract__r.Department__c from MB_Maintenance_Contract__c where Maintenance_Contract__r.Department__c IN :accDptMap.keySet()];
        if (mbmcList.size() > 0) {
            for (MB_Maintenance_Contract__c mb : mbmcList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Maintenance_Contract__r.Department__c).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Maintenance_Contract__r.Department__c).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Maintenance_Contract__r.Department__c).Department_Class_Name__c;
            }
            update mbmcList;
        }
        List<MB_Asset__c> mbAstList = [Select Id, Asset__r.AccountId from MB_Asset__c where Asset__r.AccountId IN :accDptMap.keySet()];
        if (mbAstList.size() > 0) {
            for (MB_Asset__c mb : mbAstList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Asset__r.AccountId).OCM_Category__c;
                mb.State_Text__c = accDptMap.get(mb.Asset__r.AccountId).State_Text__c;
                mb.Opportunity_Category_text__c = accDptMap.get(mb.Asset__r.AccountId).Department_Class_Name__c;
            }
            update mbAstList;
        }
        // 商談、商談商品、注残について、OCM_Category__c が違う場合のみ 更新対象
        List<MB_Opportunity__c> mboppList = [Select Id, Opportunity__r.AccountId from MB_Opportunity__c where OCM_IsSame__c = false and Opportunity__r.AccountId IN :accDptMap.keySet()];
        if (mboppList.size() > 0) {
            for (MB_Opportunity__c mb : mboppList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Opportunity__r.AccountId).OCM_Category__c;
            }
            update mboppList;
        }
        List<MB_OpportunityLineItem__c> mbOliList = [Select Id, Opportunity__r.AccountId from MB_OpportunityLineItem__c where OCM_IsSame__c = false and Opportunity__r.AccountId IN :accDptMap.keySet()];
        if (mbOliList.size() > 0) {
            for (MB_OpportunityLineItem__c mb : mbOliList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Opportunity__r.AccountId).OCM_Category__c;
            }
            update mbOliList;
        }
        List<MB_Statu_Achievements__c> mbSAList = [Select Id, Statu_Achievements__r.Opportunity__r.AccountId from MB_Statu_Achievements__c where OCM_IsSame__c = false and Statu_Achievements__r.Opportunity__r.AccountId IN :accDptMap.keySet()];
        if (mbSAList.size() > 0) {
            for (MB_Statu_Achievements__c mb : mbSAList) {
                mb.Opp_OCM_text__c = accDptMap.get(mb.Statu_Achievements__r.Opportunity__r.AccountId).OCM_Category__c;
            }
            update mbSAList;
        }
    }
    public static void updMBChildFromOpp(Map<Id, Opportunity> oppMap) {
        if (oppMap.keySet().size() == 0) return;
        List<MB_Opportunity__c> mboppList = [Select Id, Opportunity__c from MB_Opportunity__c where Opportunity__c IN :oppMap.keySet()];
        if (mboppList.size() > 0) {
            for (MB_Opportunity__c mb : mboppList) {
                mb.State_Text__c = oppMap.get(mb.Opportunity__c).SaleProvince_SAP__c;
                mb.Opportunity_Category_text__c = oppMap.get(mb.Opportunity__c).Opportunity_Category__c;
                mb.Distributor_InCharge_opp__c = oppMap.get(mb.Opportunity__c).Distributor_InCharge_opp__c;
                mb.Group_purchase_PCL__c = oppMap.get(mb.Opportunity__c).Group_purchase_PCL__c;
            }
            update mboppList;
        }
        List<MB_OpportunityLineItem__c> mbOliList = [Select Id, Opportunity__c from MB_OpportunityLineItem__c where Opportunity__c IN :oppMap.keySet()];
        if (mbOliList.size() > 0) {
            for (MB_OpportunityLineItem__c mb : mbOliList) {
                mb.State_Text__c = oppMap.get(mb.Opportunity__c).SaleProvince_SAP__c;
                mb.Opportunity_Category_text__c = oppMap.get(mb.Opportunity__c).Opportunity_Category__c;
                mb.Distributor_InCharge_opp__c = oppMap.get(mb.Opportunity__c).Distributor_InCharge_opp__c;
                mb.Group_purchase_PCL__c = oppMap.get(mb.Opportunity__c).Group_purchase_PCL__c;
            }
            update mbOliList;
        }
        List<MB_Statu_Achievements__c> mbSAList = [Select Id, Statu_Achievements__r.Opportunity__c from MB_Statu_Achievements__c where Statu_Achievements__r.Opportunity__c IN :oppMap.keySet()];
        if (mbSAList.size() > 0) {
            for (MB_Statu_Achievements__c mb : mbSAList) {
                mb.State_Text__c = oppMap.get(mb.Statu_Achievements__r.Opportunity__c).SaleProvince_SAP__c;
                mb.Opportunity_Category_text__c = oppMap.get(mb.Statu_Achievements__r.Opportunity__c).Opportunity_Category__c;
                mb.Distributor_InCharge_opp__c = oppMap.get(mb.Statu_Achievements__r.Opportunity__c).Distributor_InCharge_opp__c;
//                mb.Group_purchase_PCL__c = oppMap.get(mb.Statu_Achievements__r.Opportunity__c).Group_purchase_PCL__c;
            }
            update mbSAList;
        }
    }
    public static void updMBChildFromUser(Map<Id, User> userMap) {
        // 目標について、運用側で、目標画面にて再保存すること
        if (userMap.keySet().size() == 0) return;
        List<MB_Daily_Report__c> mbDRList = [Select Id, Daily_Report__r.Reporter__c from MB_Daily_Report__c where Daily_Report__r.Reporter__c IN :userMap.keySet()];
        if (mbDRList.size() > 0) {
            for (MB_Daily_Report__c mb : mbDRList) {
                mb.State_Text__c = userMap.get(mb.Daily_Report__r.Reporter__c).Province__c;
            }
            update mbDRList;
        }
        List<MB_Event__c> mbEvtList = [Select Id, Event__r.Daily_Report__r.Reporter__c from MB_Event__c where Event__r.Hospital_ID__c = null and Event__r.Daily_Report__r.Reporter__c IN :userMap.keySet()];
        if (mbEvtList.size() > 0) {
            for (MB_Event__c mb : mbEvtList) {
                mb.State_Text__c = userMap.get(mb.Event__r.Daily_Report__r.Reporter__c).Province__c;
            }
            update mbEvtList;
        }
    }
    public static void upUserFederationIdentifier(List<User> userList) {
        update userList;
    }

    public static void insMBStatuAchievementList(List<MB_Statu_Achievements__c> ins_mbs){
        if (ins_mbs != null && ins_mbs.size() > 0) insert ins_mbs;
    }
    public static void delMBStatuAchievementList(List<Statu_Achievements__c> del_parents){
        List<MB_Statu_Achievements__c> mbSAList = [select Id, Statu_Achievements__c from MB_Statu_Achievements__c where Statu_Achievements__c in :del_parents];
        if (mbSAList != null && mbSAList.size() > 0) delete mbSAList;
    }

    public static void insMBRepairList(List<MB_Repair__c> mbrepairList){
        if (mbrepairList != null && mbrepairList.size() > 0) insert mbrepairList;
    }
    public static void delMBRepairList(List<Repair__c> del_parents){
        List<MB_Repair__c> mbrepairList = [select Id, Repair__c from MB_Repair__c where Repair__c in :del_parents];
        if (mbrepairList != null && mbrepairList.size() > 0) delete mbrepairList;
    }
    
    public static void insMBEventList(List<MB_Event__c> mbeventList){
        if (mbeventList != null && mbeventList.size() > 0) insert mbeventList;
    }
    public static void delMBEventList(List<Event__c> del_parents){
        List<MB_Event__c> mbeventList = [select Id, Event__c from MB_Event__c where Event__c in :del_parents];
        if (mbeventList != null && mbeventList.size() > 0) delete mbeventList;
    }
    
    public static void insMBReportList(List<MB_Report__c> mbreportList){
        if (mbreportList != null && mbreportList.size() > 0) insert mbreportList;
    }
    public static void delMBReportList(List<Report__c> del_parents){
        List<MB_Report__c> mbreportList = [select Id, Report__c from MB_Report__c where Report__c in :del_parents];
        if (mbreportList != null && mbreportList.size() > 0) delete mbreportList;
    }
    
    public static void insMBDRList(List<MB_Daily_Report__c> mbdrList){
        if (mbdrList != null && mbdrList.size() > 0) insert mbdrList;
    }
    public static void delMBDRList(List<Daily_Report__c> del_parents){
        List<MB_Daily_Report__c> mbdrList = [select Id, Daily_Report__c from MB_Daily_Report__c where Daily_Report__c in :del_parents];
        if (mbdrList != null && mbdrList.size() > 0) delete mbdrList;
    }
    
    public static void insMBMCList(List<MB_Maintenance_Contract__c> mbmcList){
        if (mbmcList != null && mbmcList.size() > 0) insert mbmcList;
    }
    public static void delMBMCList(List<Maintenance_Contract__c> del_parents){
        List<MB_Maintenance_Contract__c> mbmcList = [select Id, Maintenance_Contract__c from MB_Maintenance_Contract__c where Maintenance_Contract__c in :del_parents];
        if (mbmcList != null && mbmcList.size() > 0) delete mbmcList;
    }
    
    public static void insMBTgtList(List<MB_Target__c> mbtgtList){
        if (mbtgtList != null && mbtgtList.size() > 0) insert mbtgtList;
    }
    public static void delMBTgtList(List<Opportunity> del_parents){
        List<MB_Target__c> mbtgtList = [select Id, Opportunity__c from MB_Target__c where Opportunity__c in :del_parents];
        if (mbtgtList != null && mbtgtList.size() > 0) delete mbtgtList;
    }
    public static void insMBOppList(List<MB_Opportunity__c> mboppList){
        if (mboppList != null && mboppList.size() > 0) insert mboppList;
    }
    public static void delMBOppList(List<Opportunity> del_parents){
        List<MB_Opportunity__c> mboppList = [select Id, Opportunity__c from MB_Opportunity__c where Opportunity__c in :del_parents];
        if (mboppList != null && mboppList.size() > 0) delete mboppList;
    }
    
    public static void insMBTgtLineItemList(List<MB_TargetLineItem__c> mbTliList){
        if (mbTliList != null && mbTliList.size() > 0) insert mbTliList;
    }
    public static void delMBTgtLineItemList(List<String> del_parentIds){
        List<MB_TargetLineItem__c> mbTliList = [select Id, Opportunity__c from MB_TargetLineItem__c where OpportunityLineItemId__c in :del_parentIds];
        if (mbTliList != null && mbTliList.size() > 0) delete mbTliList;
    }
    public static void insMBOppLineItemList(List<MB_OpportunityLineItem__c> mbOliList){
        if (mbOliList != null && mbOliList.size() > 0) insert mbOliList;
    }
    public static void delMBOppLineItemList(List<String> del_parentIds){
        List<MB_OpportunityLineItem__c> mbOliList = [select Id, Opportunity__c from MB_OpportunityLineItem__c where OpportunityLineItemId__c in :del_parentIds];
        if (mbOliList != null && mbOliList.size() > 0) delete mbOliList;
    }

    public static void insMBAssetList(List<MB_Asset__c> mbassList){
        if (mbassList != null && mbassList.size() > 0) insert mbassList;
    }
    public static void delMBAssetList(List<Asset> del_parentIds) {
        List<MB_Asset__c> mbassList = [select Id, Asset__c from MB_Asset__c where Asset__c in :del_parentIds];
        if (mbassList != null && mbassList.size() > 0) delete mbassList;
    }

    public static void updDailyReport(Daily_Report__c report) {
        System.debug('Daily_Report__c11111' + report);
        update report;
    }

    public static void updMcList(List<Maintenance_Contract__c> mcs) {
        update mcs;
    }

    public static void updQuote(Quote quo) {
        update quo;
    }

    public static void delOppLine(List<OpportunityLineItem> ols) {
        delete ols;
    }

    public static void insOppLine(List<OpportunityLineItem> ols) {
        insert ols;
    }
    
    public static void updateMaintenance_Contract_Estimate(List<Maintenance_Contract_Estimate__c> mces) {
        update mces;
    }
    public static void deleteMaintenance_Contract_Asset_Estimate(List<Maintenance_Contract_Asset_Estimate__c> mcaes) {
        delete mcaes;
    }
    public static void insertMaintenance_Contract_Asset_Estimate(List<Maintenance_Contract_Asset_Estimate__c> mcaes) {
        insert mcaes;
    }
    
    public static void insMaterialFor(List<Material_For__c> mfList) {
        if (mfList != null && mfList.size() > 0) insert mfList;
    }
    
    public static void insProDocMidTbl(List<Product_and_document_middle_table__c> pdmtList) {
        if (pdmtList != null && pdmtList.size() > 0) insert pdmtList;
    }
    
    public static void insCicProMidTbl(List<CIC_case_and_product_middle_table__c> cpmtList) {
        if (cpmtList != null && cpmtList.size() > 0) insert cpmtList;
    }
    
    public static void delMaterialFor(String materialId, List<String> productIds) {
        List<Material_For__c> dels = [select Id from Material_For__c where Material__c = :materialId and Product__c in :productIds];
        if (dels.size() > 0) delete dels;
    }
    
    public static void delProDocMidTbl(String proDocId, List<String> productIds) {
        List<Product_and_document_middle_table__c> dels = [select Id from Product_and_document_middle_table__c where Product_document__c = :proDocId and Product_name__c in :productIds];
        if (dels.size() > 0) delete dels;
    }
    
    public static void delCicProMidTbl(String cicProId, List<String> productIds) {
        List<CIC_case_and_product_middle_table__c> dels = [select Id from CIC_case_and_product_middle_table__c where CIC__c = :cicProId and Product__c in :productIds];
        if (dels.size() > 0) delete dels;
    }
    
//bp2
//    // 备品用
//    public static void updEquipmentSetList(List<Equipment_Set__c> esList) {
//        if (esList != null && esList.size() > 0) update esList;
//    }
//    public static void updEquipmentSet(Equipment_Set__c es) {
//        if (es != null) update es;
////    }
//bp2
//    public static void setEquipmentSetProvisionFlg(Set<Id> esIds) {
//        // 備品Setと貸出備品Set一覧の主従関係を解除したため、こうして備品Setに貸出備品Set一覧の件数を計算するしかない
//        // 件数＞0：「引当済」フラグ＝True、でなければFalse
//        AggregateResult[] ars = [select Count(Id) cnt, Equipment_Set__c from Rental_Apply_Equipment_Set__c where Equipment_Set__c in :esIds and RAES_Status__c != '上架完了'and RAES_Status__c != '取消分配' group by Equipment_Set__c];
//        List<Equipment_Set__c> esList = new List<Equipment_Set__c>();
//        for (AggregateResult ar : ars) {
//            Equipment_Set__c es = new Equipment_Set__c();
//            // レコードある
//            if (esIds.contains(String.valueOf(ar.get('Equipment_Set__c')))) {
//                esList.add(new Equipment_Set__c(
//                    Id = String.valueOf(ar.get('Equipment_Set__c')),
//                    Provision_finish__c = true
//                ));
//                esIds.remove((Id)String.valueOf(ar.get('Equipment_Set__c')));
//            }
//        }
//        if (esIds.size() > 0) {
//            for (Id id : esIds) {
//                esList.add(new Equipment_Set__c(
//                    Id = id,
//                    Provision_finish__c = false
//                ));
//            }
//        }
//        update esList;
//    }
//bp2
//    public static Equipment_Set__c setEquipmentSetProvisionFlg(Equipment_Set__c es) {
//        // 自分が「上架完了」になるのは、その後トリガでやりますから、ここは自分のIdを抜けて、自分以外の一覧は「上架完了」であるかを判断
//        List<Rental_Apply_Equipment_Set__c> raeslist = [select Id from Rental_Apply_Equipment_Set__c where Equipment_Set__c = :es.Id and Id != :es.Last_Reserve_Rental_Apply_Equipment_Set__c and RAES_Status__c != '上架完了'and RAES_Status__c != '取消分配'];
//        if (raeslist.size() == 0) {
//            es.Provision_finish__c = false;
//        }
//        return es;
//    }
    
//bp2    // 备品Set回库後、ほかの借出备品Set一览を通知
//    public static void informOtherRAES(Id esId, Id lastRAESId) {
//        List<Rental_Apply_Equipment_Set__c> raesList = [select Id, Re_Inform_Mail__c from Rental_Apply_Equipment_Set__c where Equipment_Set__c = :esId and Id != :lastRAESId order by Rental_Start_Date__c];
//        if (raesList.size() > 0) {
//            raesList[0].Re_Inform_Mail__c = (raesList[0].Re_Inform_Mail__c == null || raesList[0].Re_Inform_Mail__c == '0') ? '1' : '0';
//            update raesList[0];
//        }
//    }
    
//bp2
//    public static void insEquipmentSetDetail(List<Equipment_Set_Detail__c> esdList) {
//        if (esdList != null && esdList.size() > 0) insert esdList;
//    }
//    public static void updEquipmentSetDetail(List<Equipment_Set_Detail__c> esdList) {
//        if (esdList != null && esdList.size() > 0) update esdList;
//    }
//    public static void delEquipmentSetDetail(List<Equipment_Set_Detail__c> esdList) {
//        if (esdList != null && esdList.size() > 0) delete esdList;
//    }

    public static void insRentalApply(Rental_Apply__c ra) {
        if (ra != null) insert ra;
    }
    public static void updRentalApply(Rental_Apply__c ra) {
        if (ra != null) update ra;
    }
    public static void updRentalApplyList(List<Rental_Apply__c> ra) {
        if (ra.size() > 0) update ra;
    }
    public static void insRentalApplyEquipmentSet(List<Rental_Apply_Equipment_Set__c> raesList) {
        if (raesList != null && raesList.size() > 0) insert raesList;
    }
    public static void delRentalApplyEquipmentSet(List<Rental_Apply_Equipment_Set__c> raesList) {
        if (raesList != null && raesList.size() > 0) delete raesList;
    }
    public static void delConsumableAccessoriesInvoiceSet(List<Consumable_accessories_invoice__c> raesList) {
        if (raesList != null && raesList.size() > 0) delete raesList;
    }

////bp2
//    public static void RAESDetailRollup(List<Id> raesIds) {
//        Map<Id, AggregateResult> allCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_Id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, AggregateResult> cliCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_Id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
//                   and Check_lost_Item__c = '欠品'
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, AggregateResult> cdsCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_Id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
////bp2                   and CDS_complete_time__c = null
//                   and Asset__r.Loaner_CDS_Info__c = '需要清洗'
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, AggregateResult> iraCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_Id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
//                   and Inspection_result_after__c = 'NG'
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, AggregateResult> aiwCntAr = new Map<Id, AggregateResult>([
//                select count(Id) Cnt_id, Rental_Apply_Equipment_Set__c Id
//                  from Rental_Apply_Equipment_Set_Detail__c
//                 where Rental_Apply_Equipment_Set__c in : raesIds
//                   and Arrival_in_wh__c = false
//                 group by Rental_Apply_Equipment_Set__c
//        ]);
//        Map<Id, Rental_Apply_Equipment_Set__c> raesUpdMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
//        for (Id raesId : raesIds) {
//            Rental_Apply_Equipment_Set__c raes = raesUpdMap.get(raesId);
//            if (raes == null) {
//                // raesIds に重複がある場合の対応、親Idなので配下のものを一緒に処理するとき発生します。
//                // 集計した値は同じのはず、一回だけ設定すればいいです。
//                raes = new Rental_Apply_Equipment_Set__c(
//                        Id = raesId,
//                        Count_Detail__c = 0,
//                        Count_Lost__c = 0,
//                        Count_NotComplete_CDS__c = 0,
//                        Count_NG_Inspection_Result_After__c = 0,
//                        Count_Not_Arrival_in_wh__c = 0
//                );
//                raesUpdMap.put(raesId, raes);
//                if (allCntAr.get(raesId) != null) {
//                    raes.Count_Detail__c                     = Integer.valueOf(allCntAr.get(raesId).get('Cnt_Id'));
//                }
//                if (cliCntAr.get(raesId) != null) {
//                    raes.Count_Lost__c                       = Integer.valueOf(cliCntAr.get(raesId).get('Cnt_Id'));
//                }
//                if (cdsCntAr.get(raesId) != null) {
//                    raes.Count_NotComplete_CDS__c            = Integer.valueOf(cdsCntAr.get(raesId).get('Cnt_Id'));
//                }
//                if (iraCntAr.get(raesId) != null) {
//                    raes.Count_NG_Inspection_Result_After__c = Integer.valueOf(iraCntAr.get(raesId).get('Cnt_Id'));
//                }
//                if (aiwCntAr.get(raesId) != null) {
//                    raes.Count_Not_Arrival_in_wh__c          = Integer.valueOf(aiwCntAr.get(raesId).get('Cnt_Id'));
//                }
//            }
//        }
//        update raesUpdMap.values();
//    }

    // Assetから病院に積み上げよう
    public static AggregateResult[] selectAssetSetHospitalCount(Set<Id> hpIds) {
        return [select Account.Parent.ParentId Parent_ParentId,
                       Sum(This_year_inspection_times__c) SUM_inspection_times,
                       Sum(This_year_inspection_count__c) SUM_inspection_count
                  from Asset where Account.Parent.ParentId in : hpIds
                group by Account.Parent.ParentId];
    }
    // Assetから戦略科室に積み上げよう
    public static AggregateResult[] selectAssetSetDCCount(Set<Id> dcIds) {
        return [select Account.ParentId Parent_Id,
                       Sum(This_year_inspection_times__c) SUM_inspection_times,
                       Sum(This_year_inspection_count__c) SUM_inspection_count
                  from Asset where Account.ParentId in : dcIds
                group by Account.ParentId];
    }
    //日报用的，显示不属于自身权限的医院
    public static List<Account> ShowAccount(list<String> AccountIdList){
        List<Account> accountList = [select id,Name from Account where Id in :AccountIdList];
        return accountList;
    }
    public static List<Campaign> ShowCampaign(list<String> CampaignIdList){
        List<Campaign> campaignList = [select Id, Name from Campaign where Id in :CampaignIdList];
        return campaignList;
    }
    // Smarm__cからUserに積み上げよう
    public static AggregateResult[] selectSmarmSetUserCount(Set<Id> userIds, List<Id> delIds) {
        if (delIds.size() == 0) {
            return [select Review_Target__c Review_Target,
                           COUNT(Id) Cnt_Id,
                           Max(Report_Date__c) Max_Report_Date
                      from SMARM__c where Review_Target__c in : userIds
                    group by Review_Target__c];
        } else {
            return [select Review_Target__c Review_Target,
                           COUNT(Id) Cnt_Id,
                           Max(Report_Date__c) Max_Report_Date
                      from SMARM__c where Review_Target__c in : userIds
                       and Id not in : delIds
                    group by Review_Target__c];
        }
    }
    public static void updateUserList(List<User> userList) {
        update userList;
    }

    public static void upsertAsset(List<Asset> astList) {
        if (astList.size() > 0) {
            upsert astList;
        }
    }
    public static void deleteAsset(List<Id> astIds) {
        if (astIds.size() > 0) {
            delete [Select Id from Asset where Id In: astIds];
        }
    }

    // SoNo_DeliveryDate_Text__c にて upsert
    public static void upsertStatuAchievementsJournalByKey(List<Statu_Achievements_Journal__c> pList) {
        if (pList.size() > 0) {
            upsert pList SoNo_DeliveryDate_Text__c;
        }
    }
    public static List<Statu_Achievements_Journal__c> selectStatuAchievementsJournalByKey(List<String> pList) {
        return [Select SoNo_DeliveryDate_Text__c, ShippedAmount__c from Statu_Achievements_Journal__c where SoNo_DeliveryDate_Text__c in :pList];
    }
    
    // CHAN-BCPCA3  插入并更新 虚拟 DN start
    public static void upsertStatuAchievementsDNByKey(List<Statu_Achievements_DN__c> pList) {
        if (pList.size() > 0) {
            upsert pList DNKey__c;
        }
    }
    // CHAN-BCPCA3 插入并更新 虚拟 DN end
    
    public static void deleteStatuAchievementsJournalByKey(List<String> pList) {
        for(List<Statu_Achievements_Journal__c> delList : [Select SoNo_DeliveryDate_Text__c, ShippedAmount__c from Statu_Achievements_Journal__c where SoNo_DeliveryDate_Text__c in :pList]) {
            delete delList;
        }
    }

    // 省単位 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 void updateAgencyName(Map<Id, Account> hpNameAfterAccMap) {
        List<Agency_Hospital_Link__c> ahls = [Select Id, Name,Hospital__c From Agency_Hospital_Link__c where Hospital__c in :hpNameAfterAccMap.keySet()];
        List<Agency_Hospital_Link__c> updAHList = new List<Agency_Hospital_Link__c>();
        if (ahls.size() > 0) {
            for (Agency_Hospital_Link__c ahl: ahls) {
                Account hp = hpNameAfterAccMap.get(ahl.Hospital__c);
                String hpName = hp.Name;
                if (ahl.Name != hpName) {
                    ahl.Name = hpName;
                    updAHList.add(ahl);
                }
            }
            update updAHList;
        }
    }

    public static void updateDeptName(Map<Id, Account> hpAfterAccMap) {
        if (hpAfterAccMap.size() > 0) {
            // 変更必要な 戦略課室、IDを集める
            List<String> dcNameIds = new List<String>();
            List<Account> updAccList = new List<Account>();
            List<Account> updChkList = new List<Account>();
            // 戦略課室ID:NAME
            Map<String, String> dcNameMap = new Map<String, String>();
            // 戦略課室名称を設定
            List<Account> accDcs = [Select Id, Name, ParentId, Parent.RecordTypeId, Department_Class_Label__c from Account where ParentId IN :hpAfterAccMap.keySet()];
            if (accDcs.size() > 0) {
                for (Account child: accDcs) {
                    dcNameIds.add(child.Id);
                    if (child.Name != hpAfterAccMap.get(child.ParentId).Name + ' ' + child.Department_Class_Label__c) {
                        child.Name = hpAfterAccMap.get(child.ParentId).Name + ' ' + child.Department_Class_Label__c;
                        // 入力規則回避
                        child.Sys_Dept_Name_Change_Chk__c = true;
                        updChkList.add(child);
                    }
                    child.OCM_Category__c = hpAfterAccMap.get(child.ParentId).OCM_Category__c;
                    child.State_Text__c = hpAfterAccMap.get(child.ParentId).State_Text__c;
                    dcNameMap.put(child.Id, child.Name);
                    updAccList.add(child);
                }
                // 診療科名称を設定
                List<Account> accDpts = [Select Id, Name, ParentId, Parent.ParentId, Department_Name__c from Account where ParentId IN :dcNameIds];
                if (accDpts.size() > 0) {
                    for (Account child: accDpts) {
                        child.Name = dcNameMap.get(child.ParentId) + ' ' + child.Department_Name__c;
                        child.OCM_Category__c = hpAfterAccMap.get(child.Parent.ParentId).OCM_Category__c;
                        child.State_Text__c = hpAfterAccMap.get(child.Parent.ParentId).State_Text__c;
                        updAccList.add(child);
                    }
                }
                update updAccList;
                // 入力規則回復
                if (updChkList.size() > 0) {
                    for (Account child: updChkList) {
                        child.Sys_Dept_Name_Change_Chk__c = false;
                    }
                    update updChkList;
                }
            }
        }
    }
    
    public static void collectDeptId(List<String> accIds, Map<String, String> purposeOfAdviceMap, List<String> hospitalIds) {
        if (hospitalIds.size() > 0) {
            List<Account> accList = [Select Id, Name, Is_Active__c, Hospital__c from Account where Hospital__c IN :hospitalIds];
            for (Account acc : accList) {
                accIds.add(acc.Id);
                purposeOfAdviceMap.put(acc.Id, purposeOfAdviceMap.get(acc.Hospital__c));
            }
        }
    }
    
    public static void collectChildIdForAgent(List<String> accIds, Map<String, String> purposeOfAdviceMap, List<String> agentIds) {
        if (agentIds.size() > 0) {
            //-----------20180913---------XinHongLu-------------------Start--------------------
            //Is_Active_Formula__c = '有效',该条件为"契约"为有效时,我们传给sap
            //-----------20180913---------XinHongLu-------------------End--------------------
            List<Account> accList = [Select Id, Name, Is_Active__c, Agent_Ref__c, AgencyContract_Management_Code__c from Account where Is_Active_Formula__c = '有效' and Agent_Ref__c IN :agentIds order by Agent_Ref__c, AgencyContract_Management_Code__c, CreatedDate desc];
            if (accList.size() > 0) update accList;
            String tmpAgentRef = null;
            String tmpAgencyContractManagementCode = null;
            for (Account acc : accList) {
                if ((tmpAgentRef == null || tmpAgentRef != acc.Agent_Ref__c)
                    || (tmpAgencyContractManagementCode == null || tmpAgencyContractManagementCode != acc.AgencyContract_Management_Code__c)) {
                    tmpAgentRef = acc.Agent_Ref__c;
                    tmpAgencyContractManagementCode = acc.AgencyContract_Management_Code__c;
                    accIds.add(acc.Id);
                    purposeOfAdviceMap.put(acc.Id, purposeOfAdviceMap.get(acc.Agent_Ref__c));
                    NFM001Controller.debug_msg += '_1';
System.debug(Logginglevel.DEBUG, 'collectChildIdForAgent acc.AgencyContract_Management_Code__c:::::' + acc.AgencyContract_Management_Code__c);
                }
            }
        }
    }
//    public static List<Account> getDoubleChildForAgent(Map<String, Account> agentStateIds) {
//        List<Account> childList = new List<Account>();
//        if (agentStateIds.size() > 0) {
//            childList = [Select Id, Agency_State_Master__c, AgencyContract_Management_Code__c from Account where RecordType.Name IN ('契約') and Agency_State_Master__c IN :agentStateIds.keySet() and Id NOT IN :agentStateIds.values()];
//        }
//        return childList;
//    }

    public static void updateDeptIsActive(List<String> accIds, Map<String, String> purposeOfAdviceMap,
            List<String> hospitalIdsNeedUpdateAccountIsActive, Map<Id, String> hpIsActiveMap, Map<Id, String> hpDateToMap) {
        if (hospitalIdsNeedUpdateAccountIsActive.size() > 0) {
            List<Account> accList = [
              Select Id, Name,Is_Active__c, DepartmentEffectiveDateTo__c, Hospital__c, Hospital__r.DepartmentEffectiveDateTo__c
                from Account
               where Hospital__c IN :hospitalIdsNeedUpdateAccountIsActive];
            List<Account> accUpdList = new List<Account>();
            for (Account acc : accList) {
                if (acc.Is_Active__c == hpIsActiveMap.get(acc.Hospital__c)) {
                    // 病院（変更後）と診療科のIs_Active__cが同じの場合
                    continue;
                }
                if (hpIsActiveMap.get(acc.Hospital__c) == '無効' && acc.DepartmentEffectiveDateTo__c == null) {
                    // 無効に変更する、診療科の有効終了日がnullのものが対象、処理対象
System.debug(Logginglevel.DEBUG, '無効に変更する、診療科の有効終了日がnullのものが対象、処理対象');
                }
                else if (hpIsActiveMap.get(acc.Hospital__c) == '有効' && acc.DepartmentEffectiveDateTo__c == acc.Hospital__r.DepartmentEffectiveDateTo__c) {
                    // 無効に変更する、診療科の有効終了日が病院(変更前)と同じのものが対象、処理対象
System.debug(Logginglevel.DEBUG, '無効に変更する、診療科の有効終了日が病院と同じのものが対象、処理対象');
                } else {
System.debug(Logginglevel.DEBUG, '処理対象外、病院Is_Active__c=' + hpIsActiveMap.get(acc.Hospital__c) + ', 診療科Dateto=' + acc.DepartmentEffectiveDateTo__c + ', 病院Dateto=' + hpDateToMap.get(acc.Hospital__c));
                    continue;
                }
                accIds.add(acc.Id);
                purposeOfAdviceMap.put(acc.Id, purposeOfAdviceMap.get(acc.Hospital__c));
System.debug(Logginglevel.DEBUG, 'purposeOfAdviceMap 病院=' + purposeOfAdviceMap.get(acc.Hospital__c));
                accUpdList.add(acc);
                acc.Is_Active__c = hpIsActiveMap.get(acc.Hospital__c);
                acc.DepartmentEffectiveDateTo__c = hpDateToMap.get(acc.Hospital__c);
            }
            if (accUpdList.size() > 0) {
                update accUpdList;
            }
        }
    }
    //CHAN-AZJ6JS 追溯系统来的询价，取消WIN时，经销商订单自动改到“驳回”
    public static void selectAndupdateOrderSatus(List<String> idList) {
        List<Consumable_order__c> orderList = [select id, Order_status__c from Consumable_order__c where Name = :idList and Order_status__c = '批准' and RecordType.DeveloperName = 'Order'];
        for (Consumable_order__c order : orderList) {
            order.Order_status__c = '驳回';
        }
        update orderList;
    }
    //更新订单
    public static void updateOrderSatus(List<Consumable_order__c> docList) {
        update docList;
    }
    //更新明细2
    public static void updateOrderDetailsSatus(List<Consumable_order_details2__c> docList) {
        update docList;
    }
    //更新明细1
    public static void updateOrderDetails1Satus(List<Consumable_orderdetails__c> docList) {
        update docList;
    }
    
    public static void updRentalApplyList(List<Consumable_order__c> ra) {
        if (ra.size() > 0) update ra;
    }
    
    public static List<Event__c> getEventCList(Date whereDate, Daily_Report__c oya) {
        return [
            select Id, Event_ID__c, Daily_Report__c, Subject__c, StartDateTime__c, EndDateTime__c, Main_Visit_Location__c,
                    Location__c, whatId__c, Activity_Type2__c, Activity_Type2_Before__c,
                    Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c,
                    Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c, 
                    Companion__c, Purpose__c, Purpose_Type__c, Purpose_Type2__c, Purpose_Type3__c, Purpose_Type4__c, Purpose_Type5__c,
                    Purpose_TypeFSE__c, Purpose_TypeFSE2__c, Purpose_TypeFSE3__c, Purpose_TypeFSE4__c, Purpose_TypeFSE5__c,
                    Purpose_TypeEscFSE__c, Purpose_TypeEscFSE2__c, Purpose_TypeEscFSE3__c, Purpose_TypeEscFSE4__c, Purpose_TypeEscFSE5__c,
                    Related_Opportunity1__c, Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,
                    Related_Opportunity1_ID__c, Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                    Related_Service1__c, Related_Service2__c,
                    Related_Service1_ID__c, Related_Service2_ID__c,
                    Description__c, Hospital_Info__c, Doctor_Info__c, Technology_Treatment__c,
                    New_Query__c, Update_Query__c, Lost_Info__c, VOC__c, Meeting_Info__c, Product_Description_Id__c,
                    Maintenance_Contract_ID__c, Asset_Manual_ID__c, Rental_Apply_ID__c,
                    OPD_ID__c, NTC_ID__c, ReportAccompanied_ID__c, CityStatus_ID__c, Conflict_ID__c, Claim_ID__c, Improvement_ID__c, OnCall_ID__c,
                    nextPlanDate__c, nextPlanTimePurpose__c, Activity_ID__c,
                    Minister__c, Minister_Comment__c, Manager__c, Manager_Comment__c,
                    Free_Input__c, Visitor_Place_Free__c, Mail_Send_Btn__c,
                    Lead_ID__c, Lead_Count__c, InsReport_ID__c,
                    Activity_Purpose__c,Activity_PurposeFSE__c,Activity_PurposeEscFSE__c,ETAPPAct__c
                      ,IsAlertInputDep__c // 2018/11/21 SWAG-B6Q8BS 判断是否需要弹窗更新客户信息
                      ,SLARecorded__c,UseReport__c,SLAReportInfo__c//20210701 zh SLA 
                    // 20200420 任务日报管理 add gzw start 
                    // ,eventStatus__c, delayToDate__c, delayReason__c,DurationInMinutes__c,BeforeActivityDate__c,OPDPlan_Flag__c,IsScheduled__c,AppCdId__c,SyncCreatedDate__c
                      
                    ,eventStatus__c, CancelReason__c, delayToDate__c, delayReason__c,DurationInMinutes__c,cancelReasonSelect__c,cancelReasonSelectFSE__c,cancelReasonOther__c,delayReasonOther__c,delayReasonSelect__c,delayReasonSelectFSE__c,BeforeActivityDate__c,OPDPlan_Flag__c,IsScheduled__c,AppCdId__c,SyncCreatedDate__c
                    // 20200420 任务日报管理 add gzw end
                    //,OPD_plan__c // 2022-4-14 yjk 增加OPD计划
            from Event__c where ActivityDate__c =:whereDate and Daily_Report__c = :oya.Id order by StartDateTime__c
        ];
    }
    
    public static List<Event__c> getNextEventCList(List<String> nextEcIds) {
        return [
            select Id, Event_ID__c, Daily_Report__c, Subject__c, StartDateTime__c, EndDateTime__c, Main_Visit_Location__c,
                    Location__c, whatId__c, Activity_Type2__c, Activity_Type2_Before__c,
                    Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c,
                    Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c, 
                    Companion__c, Purpose__c, Purpose_Type__c, Purpose_Type2__c, Purpose_Type3__c, Purpose_Type4__c, Purpose_Type5__c,
                    Purpose_TypeFSE__c, Purpose_TypeFSE2__c, Purpose_TypeFSE3__c, Purpose_TypeFSE4__c, Purpose_TypeFSE5__c,
                    Purpose_TypeEscFSE__c, Purpose_TypeEscFSE2__c, Purpose_TypeEscFSE3__c, Purpose_TypeEscFSE4__c, Purpose_TypeEscFSE5__c,
                    Related_Opportunity1__c, Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,
                    Related_Opportunity1_ID__c, Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                    Related_Service1__c, Related_Service2__c,
                    Related_Service1_ID__c, Related_Service2_ID__c,
                    Description__c, Hospital_Info__c, Doctor_Info__c, Technology_Treatment__c,
                    New_Query__c, Update_Query__c, Lost_Info__c, VOC__c, Meeting_Info__c, Product_Description_Id__c,
                    Maintenance_Contract_ID__c, Asset_Manual_ID__c, Rental_Apply_ID__c,
                    OPD_ID__c, NTC_ID__c, ReportAccompanied_ID__c, CityStatus_ID__c, Conflict_ID__c, Claim_ID__c, Improvement_ID__c, OnCall_ID__c,
                    nextPlanDate__c, nextPlanTimePurpose__c, Activity_ID__c,
                    Minister__c, Minister_Comment__c, Manager__c, Manager_Comment__c,
                    Free_Input__c, Visitor_Place_Free__c, Mail_Send_Btn__c,
                    Lead_ID__c, Lead_Count__c, InsReport_ID__c,
                    Activity_Purpose__c,Activity_PurposeFSE__c,Activity_PurposeEscFSE__c
                    ,IsAlertInputDep__c // 2018/11/21 SWAG-B6Q8BS 判断是否需要弹窗更新客户信息
            from Event__c where Id in :nextEcIds order by StartDateTime__c
        ];
    }
    
    public static Map<String, Map<String, String>> getAccsByName(List<String> accList) {
        Map<String, Map<String, String>> accMap = new Map<String, Map<String, String>>();
        Map<String, String> accIds = new Map<String, String>();
        
        List<Account> accs = [select Id, Name from Account where Name in : accList];
        for (Account acc : accs) {
            if (accMap.containsKey(acc.Name)) {
                accIds = accMap.get(acc.Name);
            } else {
                accIds = new Map<String, String>();
            }
            accIds.put(acc.Id, acc.Id);
            accMap.put(acc.Name, accIds);
        }
        return accMap;
    }
    
    public static Map<String, Map<String, String>> getCampsByName(List<String> campList) {
        Map<String, Map<String, String>> campMap = new Map<String, Map<String, String>>();
        Map<String, String> campIds = new Map<String, String>();
        
        List<Campaign> camps = [select Id, Name from Campaign where Name in : campList];
        for (Campaign camp : camps) {
            if (campMap.containsKey(camp.Name)) {
                campIds = campMap.get(camp.Name);
            } else {
                campIds = new Map<String, String>();
            }
            campIds.put(camp.Id, camp.Id);
            campMap.put(camp.Name, campIds);
        }
        return campMap;
    }

    // CHAN-BE6CZZ 最后跟进结果 LHJ 20190724 Start
    //public static AggregateResult[] selectForOpp_Last_Follow_Up_Date(List<String> oppIds) {    
        //return [select Opportunity__c, Max(End_Time__c) maxET from Event_Oppotunity__c where Opportunity__c in : oppIds
        //        and Daily_Report__r.Status_With_Check__c <> '草案中' and Daily_Report__r.Status_With_Check__c <> ''
        //        group by Opportunity__c];
    //}
    public static List<Event_Oppotunity__c> selectForOpp_Last_Follow_Up_Date(List<String> oppIds) {
        return [select Opportunity__c, End_Time__c, EventC_ID__r.Description__c
                  from Event_Oppotunity__c 
                 where Opportunity__c in : oppIds
                   and Daily_Report__r.Status_With_Check__c <> '草案中' 
                   and Daily_Report__r.Status_With_Check__c <> ''
              order by Opportunity__c, End_Time__c desc
              ];
    }
    // CHAN-BE6CZZ 最后跟进结果 LHJ 20190724 Start

    
    public static List<Event> selectForOpp_Last_Visit_Scheduled_Date(List<String> oppIds) {
        // Max(ActivityDateTime)がつかえないため、group by をやめました。
        return [select Id, Related_Opportunity1_ID__c, ActivityDateTime from Event where Related_Opportunity1_ID__c != null and Related_Opportunity1_ID__c in :oppIds
                order by Related_Opportunity1_ID__c, ActivityDateTime desc];
    }

    public static AggregateResult[] selectEventOppForAggregateFollowToOpp(List<String> oppIds) {
        return [select Opportunity__c
                       , count(Name) cnt
                       , sum(Visit_President_Flag__c) vprCnt
                       , sum(Visit_Head_Doctor_Flag__c) vhdCnt
                       , sum(NTC_Flag__c) ntcCnt
                  from Event_Oppotunity__c where Opportunity__c in :oppIds
                  and Daily_Report__r.Status_With_Check__c <> '草案中' and Daily_Report__r.Status_With_Check__c <> ''
                  group by Opportunity__c];
    }
    
    public static List<Report__c> selectReportForAggregateOpdToOpp(List<String> oppIds) {
        return [select Opportunity1__c, Opportunity2__c, Opportunity3__c, Opportunity4__c, Opportunity5__c
                  from Report__c where Status__c <> '作成中' and Status__c <> '取消し' and Status__c <> ''
                  and (Opportunity1__c in :oppIds or Opportunity2__c in :oppIds or Opportunity3__c in :oppIds or Opportunity4__c in :oppIds or Opportunity5__c in :oppIds)
                  and RecordType.DeveloperName = 'OPD'];
    }

    // ５つの商談を見るため、group by ができないので、検索後loopして集計する
    public static AggregateResult[] selectForService_Last_Follow_Up_Date(List<String> serviceIds) {
        return [select Service__c, Max(Date__c) maxD from Event_Service__c where Service__c in : serviceIds
                and Daily_Report__r.Status_With_Check__c <> '草案中' and Daily_Report__r.Status_With_Check__c <> ''
                group by Service__c];
    }
    
    public static void updateContactMonth(List<String> conIds, List<Date> conDates) {
        Map<String, Integer> conCntMap = new Map<String, Integer>();
        AggregateResult[] ar = [select count(Id) cnt, Contact__c, Date__c from Activity_History_Daily_Report__c
                                where Daily_Report__r.Status_With_Check__c <> '草案中' and Daily_Report__r.Status_With_Check__c <> ''
                                and Contact__c in :conIds group by Contact__c, Date__c];
        if (ar.size() > 0) {
            for (Integer i = 0; i < ar.size(); i++) {
                Date actDate = (Date) ar[i].get('Date__c');
                String key = String.valueOf(ar[i].get('Contact__c')) + String.valueOf(actDate.year()) + (actDate.month() < 10 ? '0' + actDate.month() : '' + actDate.month());
                if (conCntMap.containsKey(key)) {
                    conCntMap.put(key, conCntMap.get(key) + Integer.valueOf(ar[i].get('cnt')));
                } else {
                    conCntMap.put(key, Integer.valueOf(ar[i].get('cnt')));
                }
            }
        }
        
        // ここから12ヶ月のカウントを更新
        Map<Id, Contact> conThisMap = new Map<Id, Contact>([select Id, Visit_Count1__c, Visit_Count2__c, Visit_Count3__c, Visit_Count4__c, Visit_Count5__c, Visit_Count6__c, 
                                                            Visit_Count7__c, Visit_Count8__c, Visit_Count9__c, Visit_Count10__c, Visit_Count11__c, Visit_Count12__c 
                                                            from Contact where Id in :conIds for update]);
        if (conThisMap.size() > 0) {
            Map<String, Contact> updMap = new Map<String, Contact>();
            for (Integer i = 0; i < conIds.size(); i++) {
                Contact con = conThisMap.get(conIds[i]);
                if (updMap.containsKey(con.Id)) {
                    con = updMap.get(con.Id);
                }
                
                if (con != null) {
                    Date repDate = conDates[i];
                    Integer year = repDate.year();
                    Integer month = repDate.month();
                    
                    Integer cnt = null;
                    if (conCntMap != null) {
                        cnt = conCntMap.get(con.Id + '' + year + ((month < 10) ? '0' : '') + month);
                    }
                    if(month == 1) {
                        if (!equalTwoNum(con.Visit_Count1__c, cnt)) {
                            con.Visit_Count1__c = cnt;
                        }
                    } else if(month == 2) {
                        if (!equalTwoNum(con.Visit_Count2__c, cnt)) {
                            con.Visit_Count2__c = cnt;
                        }
                    } else if(month == 3) {
                        if (!equalTwoNum(con.Visit_Count3__c, cnt)) {
                            con.Visit_Count3__c = cnt;
                        }
                    } else if(month == 4) {
                        if (!equalTwoNum(con.Visit_Count4__c, cnt)) {
                            con.Visit_Count4__c = cnt;
                        }
                    } else if(month == 5) {
                        if (!equalTwoNum(con.Visit_Count5__c, cnt)) {
                            con.Visit_Count5__c = cnt;
                        }
                    } else if(month == 6) {
                        if (!equalTwoNum(con.Visit_Count6__c, cnt)) {
                            con.Visit_Count6__c =cnt;
                        }
                    } else if(month == 7) {
                        if (!equalTwoNum(con.Visit_Count7__c, cnt)) {
                            con.Visit_Count7__c = cnt;
                        }
                    } else if(month == 8) {
                        if (!equalTwoNum(con.Visit_Count8__c, cnt)) {
                            con.Visit_Count8__c = cnt;
                        }
                    } else if(month == 9) {
                        if (!equalTwoNum(con.Visit_Count9__c, cnt)) {
                            con.Visit_Count9__c = cnt;
                        }
                    } else if(month == 10) {
                        if (!equalTwoNum(con.Visit_Count10__c, cnt)) {
                            con.Visit_Count10__c = cnt;
                        }
                    } else if(month == 11) {
                        if (!equalTwoNum(con.Visit_Count11__c, cnt)) {
                            con.Visit_Count11__c = cnt;
                        }
                    } else if(month == 12){
                        if (!equalTwoNum(con.Visit_Count12__c, cnt)) {
                            con.Visit_Count12__c = cnt;
                        }
                    } else {
                        // TODO Exception
                    }
                    updMap.put(con.Id, con);
                }
            }
            List<Contact> updCon = updMap.values();
            if (updCon.size() > 0) update updCon;
        }
    }
    
    public static List<SObject> getPe99Info(String soql, String userId) {
        return Database.query(soql);
    }
    
    public static Boolean checkInsHpChange(Id irHpId, Map<Id, Id> iiHpMap) {
        Boolean isChange = false;
        for (String key : iiHpMap.keySet()) {
            Id iiHpId = iiHpMap.get(key);
            if (irHpId != iiHpId) {
                isChange = true;
                break;
            }
        }
        return isChange;
    }
    
    
    // equal:true
    private static Boolean equalTwoNum(Decimal val1, Integer val2) {
        if (val1 == null && val2 == null) {
            return true;
        } else if (val1 != null && val2 != null && val1 == Decimal.valueOf(val2)) {
            return true;
        } else {
            return false;
        }
    }
    
    // JS用检索
    @ReadOnly
    @RemoteAction
    global static String getQueryJson(String sql) {
        system.debug('=====sql:' + sql);
        List<SObject> rs = Database.query(sql);
        String rsStr = JSON.serialize(rs);
        system.debug('=====rsStr:' + rsStr);
        return rsStr;
    }
    
    // JS用更新
    @ReadOnly
    @RemoteAction
    global static String getUpdateResult(String j) {
        system.debug('=====json:' + j);
        SObject obj = (SObject)JSON.deserializeStrict(j, SObject.class);
        Database.SaveResult rs = Database.update(obj);
        String rsStr = rs.isSuccess() ? '1' : '0';
        system.debug('=====rsStr:' + rsStr);
        return rsStr;
    }
    
    WebService static String getAccessToken() {
        return UserInfo.getSessionId();
    }
    
    WebService static void addBatchIfLog(String typeStr, Integer isError, String logStr) {
        BatchIF_Log__c log = new BatchIF_Log__c(
            Type__c = typeStr,
            Is_Error__c = isError
        );
        if (isError == 0) {
            log.log__c = logStr;
        } else {
            log.ErrorLog__c = logStr;
        }
        insert log;
    }
    
    WebService static String deleteRepair(String rid) {
        try {
            Repair__c r = new Repair__c(Id = rid);
            delete r;
            return 'OK';
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    /*
    =======================================================================================================================
    ===================================================SI 询价部分util集合=================================================
    =======================================================================================================================
    */
    /**
    OCM-SI需求表用，复制功能，仅限当前所有SI需求表失效的时候，才能使用
    */
    @AuraEnabled
    WebService static String ISO_Copy_Func(id isoID){
        IS_Opportunity_Demand__c checkISO = [select Opportunity_ID__c from IS_Opportunity_Demand__c where id =:isoID];
        String opporID = checkISO.Opportunity_ID__c;
        List<IS_Opportunity_Demand__c> isoListForCheck = [select id, Func_SOD_Status__c,Abort_Date__c from IS_Opportunity_Demand__c where Opportunity_ID__c=:opporID];
        for(IS_Opportunity_Demand__c iso: isoListForCheck){
            if(iso.Abort_Date__c==null){
                return '存在未终止的SI需求表，不能复制';
            }
        }
        
        return ISO_DemandOperAndDemonsController.CopyFunc(isoID);
    }
    /**
    OCM-SI需求表用，自定义提交待审批
    */
    WebService static String ISO_Submit_Func(id isoID){
        List<IS_Opportunity_Demand__c> submintISOList = new List<IS_Opportunity_Demand__c>();
        submintISOList = [SELECT id,Data_Check_TF__c from IS_Opportunity_Demand__c WHERE id =:isoID];
        List<IS_Opportunity_Demand__c> isOppList = new List<IS_Opportunity_Demand__c>();
        for(IS_Opportunity_Demand__c iso: submintISOList){
            if(iso.Data_Check_TF__c){
                Savepoint sp = Database.setSavepoint();
                try {
                    Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                    psr.setObjectId(isoID);
                    Approval.ProcessResult submitResult = Approval.process(psr);
                    return  'Fin'; 
                }catch(exception e){
                    String ioError = e.getMessage();
                    Database.rollback(sp);
                    return  ''+ioError; 
                }
                }else{
                    return '请现在编辑页面，检查数据完整性，然后再执行提交';
                }
        }
        if(isOppList.size() > 0){
            update isOppList;
        }
        return 'Fin';
    }
    /**
    OCM-SI询价文件上传用，自定义提交待审批
    */
    WebService static String SI_FileUpdateSubmit(id subID){
            //List<Attachment> CheckFile = [select id from Attachment where ParentId=:subID];
            //if(CheckFile.size()==0){
            //    return '请上传附件后再提交';
            //}else{
            Savepoint sp = Database.setSavepoint();
            try {
                    Approval.ProcessSubmitRequest psr = new Approval.ProcessSubmitRequest();
                    psr.setObjectId(subID);
                    Approval.ProcessResult submitResult = Approval.process(psr);
                    return  'Fin'; 
                }catch(exception e){
                    String ioError = e.getMessage();
                    Database.rollback(sp);
                    return  ''+ioError; 
            }
        //}
    }
    /**
    OCM注残用，当注残更新时，判断数个日期是否变革，如若变革，则更新对应询价的映射时间（取最大值）;
    */
    public static String updateOppoMuiltDate(id opporID){
        List<AggregateResult> ArResult = [select 
                                    Max(ContractReceivedDate__c ) al,
                                    Max(FirstApproveDate__c ) bl,
                                    Max(LastApproveDate__c  ) cl,
                                    Max(X30_Deposit_Day__c) dl,
                                    Max(Deposit_In_Full_Day__c) el,
                                    Max(SoLatestDeliveryDate__c) fl,
                                    Max(DeliveryDate__c ) gl,
                                    Max(DeliveryDate_backup__c) hl,
                                    Max(InstallDate__c) il,
                                    Max(Collection_Day_Invoice__c) jl,
                                    Max(Inspection_explanation_day__c) kl 
                                    from
                                    Statu_Achievements__c
                                    WHERE Opportunity__c =: opporID];
        Opportunity ops = [SELECT   Contract_Recieve_Date__c ,
                                    First_Review_Date__c ,
                                    LastApproveDate__c ,
                                    X30_Deposit_Day__c,
                                    Pay_All_Money__c,
                                    Last_Delivery_Date__c,
                                    DeliveryDate__c ,
                                    InstallDate__c,
                                    Inspection_explanation_day__c
                            From    Opportunity
                            WHERE   id =:opporID];
        for(AggregateResult ar : ArResult ){
            if(Date.valueOf(ar.get('al')) != ops.Contract_Recieve_Date__c){
                ops.Contract_Recieve_Date__c = Date.valueOf(ar.get('al'));
            }
            if(Date.valueOf(ar.get('bl')) != ops.First_Review_Date__c){
                ops.First_Review_Date__c = Date.valueOf(ar.get('bl'));
            }
            if(Date.valueOf(ar.get('cl')) != ops.LastApproveDate__c){
                ops.LastApproveDate__c = Date.valueOf(ar.get('cl'));
            }
            if(Date.valueOf(ar.get('dl')) != ops.X30_Deposit_Day__c){
                ops.X30_Deposit_Day__c = Date.valueOf(ar.get('dl'));
            }
            if(Date.valueOf(ar.get('el')) != ops.Pay_All_Money__c){
                 ops.Pay_All_Money__c = Date.valueOf(ar.get('el'));
            }
            if(Date.valueOf(ar.get('fl')) != ops.Last_Delivery_Date__c){
                ops.Last_Delivery_Date__c = Date.valueOf(ar.get('fl'));
            }
            if(Date.valueOf(ar.get('gl')) != ops.DeliveryDate__c){
                ops.DeliveryDate__c = Date.valueOf(ar.get('gl'));
            }
            if(Date.valueOf(ar.get('il')) != ops.InstallDate__c){
                ops.InstallDate__c = Date.valueOf(ar.get('il'));
                system.debug(ar.get('il')+'2333333333');
            }
            if(Date.valueOf(ar.get('kl')) != ops.Inspection_explanation_day__c){
                ops.Inspection_explanation_day__c = Date.valueOf(ar.get('kl'));
            }
        }
        update ops;

        ControllerUtil.refreshSIOpporStatus(opporID);
        return 'Fin';
    }
    /**
    OCM询价用，刷新OCM——SI的状态
    */
    public static string refreshSIOpporStatus(id opporID){
        Opportunity ops =  [SELECT  Last_Install_Confirm_Date__c,
                                    InstallDate__c,                     
                                    DeliveryDate__c,
                                    Last_Delivery_Date__c,
                                    Pay_All_Money__c ,
                                    X30_Deposit_Day__c ,
                                    LastApproveDate__c,
                                    First_Review_Date__c,
                                    Contract_Recieve_Date__c,
                                    SFDCLast_Process_Date__c,
                                    Input_Dealer_HP_date__c,
                                    Agency_Contract_Date_last_update__c,
                                    Assistant_Applied_Date__c,
                                    Closing_Bid_Date__c,
                                    Bid_Date__c,
                                    Autholization_Activated_Date__c,
                                    Authorized_Date__c,
                                    Last_Follow_Up_Date__c,
                                    Key_tipics_last_update_day__c,
                                    Status_List_SI__c
                            FROM    Opportunity
                            WHERE   id=:opporID];
        if(ops.Last_Install_Confirm_Date__c!=null){ops.Status_List_SI__c ='16 已结束';}
            else if(ops.InstallDate__c!=null){ops.Status_List_SI__c ='15 已安装';}
                else if(ops.DeliveryDate__c!=null){ops.Status_List_SI__c ='14 已发货';}
                    else if(ops.Last_Delivery_Date__c!=null){ops.Status_List_SI__c ='13 已分配，待发货';}
                        else if(ops.Pay_All_Money__c!=null){ops.Status_List_SI__c ='12 已订货，付全款';}
                            else if(ops.X30_Deposit_Day__c!=null){ops.Status_List_SI__c ='11 已订货，付订金';}
                                else if(ops.LastApproveDate__c!=null){ops.Status_List_SI__c ='10 库存已预留，未付款';}
                                    else if(ops.First_Review_Date__c!=null){ops.Status_List_SI__c ='9 已录入订单，未付款';}
                                        else if(ops.Contract_Recieve_Date__c!=null){ops.Status_List_SI__c ='9 已录入订单，未付款';}
                                            else if(ops.SFDCLast_Process_Date__c!=null){ops.Status_List_SI__c ='8 已签约';}
                                                else if(ops.Input_Dealer_HP_date__c!=null){ops.Status_List_SI__c ='7 用户已签约';}
                                                    else if(ops.Agency_Contract_Date_last_update__c!=null){ops.Status_List_SI__c ='6 用户未签约';}
                                                        else if(ops.Assistant_Applied_Date__c!=null){ops.Status_List_SI__c ='5 价格申请中';}
                                                            else if(ops.Closing_Bid_Date__c!=null){ops.Status_List_SI__c ='4 已中标';}
                                                                else if(ops.Bid_Date__c!=null ||ops.Autholization_Activated_Date__c!=null||ops.Authorized_Date__c!=null){ops.Status_List_SI__c ='3 已授权';}
                                                                    else if(ops.Last_Follow_Up_Date__c!=null){ops.Status_List_SI__c ='2 跟进中';}
                                                                        else if(ops.Key_tipics_last_update_day__c!=null){ops.Status_List_SI__c ='1 还没拜访';}
                                                                            else{ops.Status_List_SI__c = '0 还没跟进';}
        update ops;
        return 'Fin';
    }/**
    OCM询价文件上传用，实际上传文件后，刷新上传时间
    */
    public static String UpdateFileDateSet(List<String> SIopportunityIds){
        List<SI_Attachment__c> attFileList = [select id,Opportunity_ID__c,File_Upload_Date__c,Type__c from SI_Attachment__c where id in:SIopportunityIds];
        List<id> oppsId = new List<id>();
        Map<id,id> SODOwnerMap = new Map<id,id>();
        for(SI_Attachment__c siAc : attFileList){
            oppsId.add(siAc.Opportunity_ID__c);
        }
        List<IS_Opportunity_Demand__c> sodList = [select OwnerId,id,Opportunity_ID__c from IS_Opportunity_Demand__c where Opportunity_ID__c in:oppsId];
        for(IS_Opportunity_Demand__c sod: sodList){
            SODOwnerMap.put(sod.Opportunity_ID__c, sod.OwnerId);
        }
        for(SI_Attachment__c siAc : attFileList){
            siAc.File_Upload_Date__c = Date.today();
            siAc.SI_SOD_Owner__c = SODOwnerMap.get(siAc.Opportunity_ID__c);
        }
        savepoint sp = Database.setsavepoint();
        try{
            update attFileList;
            return 'Fin';
        }catch(exception o){
            Database.rollback(sp);
            return 'Database Error';
        }
       
    }

    /**
    OCM询价文件上传用，询价上传文件，根据文件种类，更新对应SI需求表状态
    */
    public static String UpdateSIFunctionStatus(List<String> SIopportunityIds){
    system.debug('Inside+++++++++++++++');
        List<SI_Attachment__c> attFileList = [select id,Opportunity_ID__c,Type__c from SI_Attachment__c where id in:SIopportunityIds];
        List<id> oppid = new List<id>();
        for(SI_Attachment__c si : attFileList){
            oppid.add(si.Opportunity_ID__c);
        }
        List<IS_Opportunity_Demand__c> isoFileList = new List<IS_Opportunity_Demand__c>();
        List<Opportunity> opslist = [select id,Project_decide_date__c,bid_Confrim_Date__c from Opportunity where id in:oppid];
        List<Opportunity> opslistUpdate = new List<Opportunity>();
        Map<Id,String> AttTypeToISODate = new Map<Id,String>();
        isoFileList = [ select  Id,CAD_Upload_Date__c,Program_Plan_Upload_Date__c,
                                Param_Upload_Date__c,Bid_Document_Upload_Date__c,
                                ConfirmBook_Upload_Date__c,Opportunity_ID__c 
                        from IS_Opportunity_Demand__c
                        where Opportunity_ID__c in:oppid
                        and  Func_SOD_Status__c !='已终止'];
        for(SI_Attachment__c att: attFileList){
            AttTypeToISODate.put(att.Opportunity_ID__c,att.Type__c);
        }
        for(IS_Opportunity_Demand__c iso : isoFileList){
            if(AttTypeToISODate.get(iso.Opportunity_ID__c) == 'CAD图纸'||
                AttTypeToISODate.get(iso.Opportunity_ID__c) == '手术室净化平面图（含设备定位）'||
                    AttTypeToISODate.get(iso.Opportunity_ID__c) == '目标术间吊塔定位图'||
                        AttTypeToISODate.get(iso.Opportunity_ID__c) == '目标术间净化立体图'||
                            AttTypeToISODate.get(iso.Opportunity_ID__c) == '示教点楼层平面图'||
                                AttTypeToISODate.get(iso.Opportunity_ID__c) == '楼层建筑平面图'||
                                    AttTypeToISODate.get(iso.Opportunity_ID__c) == '其他工程文件清单'){
                    if( iso.CAD_Upload_Date__c == null || AttTypeToISODate.get(iso.Opportunity_ID__c) == '手术室净化平面图（含设备定位）'){
                        iso.CAD_Upload_Date__c = Date.today();

                    }
                }else if(AttTypeToISODate.get(iso.Opportunity_ID__c) == '项目方案书'){
                    iso.Program_Plan_Upload_Date__c = Date.today();
                    for(Opportunity op : opslist){
                        op.Project_decide_date__c = Date.today();
                        opslistUpdate.add(op);
                        System.debug('项目方案书op'+opslistUpdate);
                    }
                    }else if(AttTypeToISODate.get(iso.Opportunity_ID__c) == '招标参数'){
                        iso.Param_Upload_Date__c = Date.today();
                        }else if(AttTypeToISODate.get(iso.Opportunity_ID__c) == '标书'  ){
                            iso.Bid_Document_Upload_Date__c = Date.today();
                            for(Opportunity op : opslist){
                                op.bid_Confrim_Date__c = Date.today();
                                opslistUpdate.add(op);
                            }
                            }else if(AttTypeToISODate.get(iso.Opportunity_ID__c) == 'OCAP/TUV认证'){
                                iso.ConfirmBook_Upload_Date__c = Date.today();
                            }
        }
        savepoint sp = Database.setsavepoint();
        try{
            update isoFileList;
            if(opslistUpdate.size()>0){
                 update opslistUpdate;
            }
           
            }catch(exception o){
                Database.rollback(sp);
                return 'Failed: '+o;
                system.debug('服务器侦错：'+o);
            }
        return 'Fin';
    }
    /**
    OCM报价用，当询价编码更新时，报价编码相应改变
    */
    public static String ResetQuoteNo(List<id> oppidList){
        List<Quote> UpdateQuoteList = new  List<Quote>();
        List<Opportunity> oppNoList = new  List<Opportunity>();
        Map<id,String> oppIdnoMap = new Map<id,String>();
        oppNoList = [SELECT id,Opportunity_No__c from Opportunity where id in:oppNoList];
        for(Opportunity ops : oppNoList){
            oppIdnoMap.put(ops.id, ops.Opportunity_No__c);
        }
        UpdateQuoteList = [SELECT id,Quote_No__c,Opportunityid from Quote WHERE Opportunityid in:oppidList order by Opportunityid];
        Integer index = 0;
        id flgId = null;
        for(Quote Qu : UpdateQuoteList){
            if(flgId == null){
                id ids = Qu.Opportunityid;
            }
            if(flgId == Qu.Opportunityid){
                index ++;
            }else{
                flgId = Qu.Opportunityid;
                index = 1;
            }
            Qu.Quote_No__c = oppIdnoMap.get(Qu.Opportunityid) + (index>9?(String.valueof(index)):('0'+String.valueof(index)));
        }
        return 'Fin';
    }
    /**
    OCM_SI更新对应报价状态，
    */
    WebService static String setQuote(string oppid){
        system.debug('2323^^^^^^^^^^^^');
        List<IS_Opportunity_Demand__c> updateList = [SELECT Quote_Locked_Date__c from IS_Opportunity_Demand__c WHERE Opportunity_ID__c =:oppid ];
        for(IS_Opportunity_Demand__c iso : updateList){
            iso.Quote_Locked_Date__c = Date.today();
        }
        update updateList;
        return 'Fin';
    }
    /**
    OCM询价拆单用，用来复制原有询价的报价
    */
    public static String CopyQuoteFromOppor(id oldOppor,String opporName , id newOppor,Opportunity ModelOppor){
        List<Quote> newQuoteList  = new List<Quote>();
        Map<id,id> newToold = new Map<id,id>();
        Map<id,QuoteLineItem> QuidWithQLitem = new Map<id,QuoteLineItem>();
        List<id> QuoteidOldList = new List<id>();
        List<Opportunity> opGetname = [SELECT Opportunity_No__c from Opportunity where id = :newOppor];
        if(opGetname.size()>0){
            String nameCode = opGetname[0].Opportunity_No__c;
            system.debug(nameCode+'nameCode');
        }
        String ele = '%'+ModelOppor.old_Oppo_No__c +'%';
        List<Quote> countQu = [SELECT id from Quote WHERE Quote_No__c like :ele];
        List<Quote> oldQuoteList = [SELECT  Id,
                                        Name,
                                        CurrencyIsoCode,
                                        CreatedDate,
                                        OpportunityId,
                                        Pricebook2Id,
                                        ContactId,
                                        QuoteNumber,
                                        IsSyncing,
                                        ShippingHandling,
                                        Tax,
                                        Status,
                                        ExpirationDate,
                                        Description,
                                        Subtotal,
                                        TotalPrice,
                                        LineItemCount,
                                        BillingName,
                                        ShippingName,
                                        QuoteToName,
                                        AdditionalName,
                                        Email,
                                        Phone,
                                        Fax,
                                        AccountId,
                                        Discount,
                                        GrandTotal,
                                        Agency1__c,
                                        Agency1_Profit__c,
                                        Agency1_Profit_Rate__c,
                                        Agency2__c,
                                        Agency2_Profit__c,
                                        Agency2_Profit_Rate__c,
                                        Agent1_Agent2_Price__c,
                                        OCM_Agent1_Price__c,
                                        OCM_Sales_Forecast__c,
                                        Estimation_List_Price__c,
                                        Stocking_Price__c,
                                        Dealer_Final_Price__c,
                                        Quote_No__c,
                                        Stock_Pre_Arrangement__c,
                                        Quote_Date__c,
                                        Unit_Price__c,
                                        Offer_Amount__c,
                                        TOTAL__c,
                                        Discount__c,
                                        Pricing__c,
                                        Preferential_Trading_Price__c,
                                        Contract__c,
                                        Quote_Expiration_Date__c,
                                        Quote_Comment__c,
                                        Discount_Amount_Calculate__c,
                                        Discount_Amount__c,
                                        Print_HP_Name__c,
                                        Quote_Adjust_Amount__c,
                                        Quote_Adjust_Calculate__c,
                                        Quote_No_Auto__c,
                                        Installation_location__c,
                                        QuoteName__c,
                                        PriceRefreshDate__c,
                                        Quote_Print_Date__c,
                                        OCM_Sales_Forecast_Without_Tax__c,
                                        Quote_Decision__c,
                                        Cancel_Decide__c,
                                        TotalPrice__c,
                                        Quote_Decision_Date__c,
                                        Quote_CreatedDate__c,
                                        IsSelected__c,
                                        HasType3Machine__c,
                                        OCM_Sales_Forecast_F__c,
                                        Dealer_Final_Price_F__c,
                                        Agent1_Agent2_Price_Page__c,
                                        Dealer_Final_Price_Page__c,
                                        OCM_Agent1_Price_Page__c,
                                        QuoteTotal_Page__c,
                                        Quote_Adjust_Amount_Page__c,
                                       
                                        OCM_Agent1_Price_F__c,
                                       
                                        Agent1_Agent2_Price_F__c,
                                        Agency2_Profit_F__c,
                                        Agency2_Profit_Rate_F__c,
                                        Quote_Adjust_Amount_F__c,
                                        Quote_Adjust_Calculate_F__c,
                                        TotalPrice_F__c,
                                        Discount_Amount_F__c,
                                        Discount_Amount_Calculate_F__c,
                                        BidAnnounce__c,
                                        Quote_No_last2__c
                                    FROM
                                        Quote
                                    WHERE 
                                        OpportunityId = :oldOppor
                                    order by 
                                        CreatedDate];
       
        Integer i = countQu.size();
        i=1;
        for(Quote Qu : oldQuoteList){
            //要按照原有顺序采番
            system.debug(Qu.Id+'===============4'); 
            String title = ModelOppor.old_Oppo_No__c;
            QuoteidOldList.add(Qu.Id);
            Qu.Id = null;
            Qu.OpportunityId = newOppor;
            Qu.Quote_No__c = title.substring(0,title.length() - 7)+ModelOppor.Opp_Number__c+ '-'+(i>9?(String.valueof(i)):('0'+i));
            newQuoteList.add(Qu);
            i++;
        }
        Savepoint sp = Database.setSavepoint();
        try{
            insert newQuoteList;
        } catch(Exception o){
            Database.rollback(sp);
            return 'Insert  Failed'+o;
        }
        for(Integer k = 0; k < newQuoteList.size(); k++){
                newToold.put(QuoteidOldList[k],newQuoteList[k].id);
        }
        List<QuoteLineItem> oldQuoteitemList = [Select Id,Asset_Model_No__c,SFDA_Status__c,Product_Sales_Possibility__c,
                                                Name__c,BSS_Category__c,Quote.Quote_Print_Date__c,Quoteid,
                                                Qty_Unit__c,Cost__c,UnitPrice__c,ListPrice__c,Quantity,TotalPrice__c,
                                                PricebookEntry.Product2.SFDA_Status__c, ProductCode__c, Product_Cost__c,PricebookEntry.Product2.VenderName__c, Product2.VenderName__c,Product_ListPrice__c, PricebookEntry.Product2.Sales_Possibility__c, PricebookEntry.Product2.Name,
                                                PricebookEntryId, PricebookEntry.Product2Id,UnitPrice_Page__c,PricebookEntry.Product2.Packing_list_manual__c,PricebookEntry.Product2.StorageStatus__c
                                                // 2022-03-21 SWAG-CBX5NN start
                                                ,If_Cancel_Guarantee__c
                                                ,multiYearWarranty__c
                                                ,CanNotCancelFlag__c 
                                                ,ProductEntend_gurantee_period_all__c
                                                ,warrantyType__c
                                                ,GuaranteePeriod__c
                                                ,GuranteeType__c 
                                                // 2022-03-21 SWAG-CBX5NN end
                                                From QuoteLineItem where Quoteid = :QuoteidOldList];
        for(QuoteLineItem qli : oldQuoteitemList){
            QuidWithQLitem.put(qli.Quoteid,qli);
        }
        system.debug(newToold+'newTooldnewTooldnewToold');
        system.debug(QuoteidOldList+'QuoteListQuoteListQuoteList');
        List<QuoteLineItem> copyQuoteItemList = new List<QuoteLineItem>();
         for(String Qu : QuoteidOldList){
            system.debug(Qu+'===============1');
            for(QuoteLineItem qlir : oldQuoteitemList){
                if(qlir.Quoteid == Qu){
                    system.debug(qlir+'===============2');
                    system.debug(QuidWithQLitem.get(Qu)+'===============3');
                    QuoteLineItem qli = qlir.clone();
                    qli.Quoteid = newToold.get(Qu);
                    qli.Id = null;
                    qli.UnitPrice = 0;
                    copyQuoteItemList.add(qli);
                }
               
            }
        }
        Savepoint spl = Database.setSavepoint();
        try{
            insert copyQuoteItemList;
        } catch(Exception o){
            Database.rollback(spl);
            return 'Insert  Failed copyQuoteItemList '+o;
        }
        return 'Fin';
    }
    /**
    OCM报价用，判断SI需求表的状态
    */
    WebService static String getStatusForISO(id opporID){
        //翻译已批准的数量
        Integer Abort = 0;
        Integer Applying = 0;
        Integer CommitCode = 0;
        List<IS_Opportunity_Demand__c> isoList = [  SELECT 
                                                        id,
                                                        name,
                                                        Abort_Date__c,
                                                        Approval_Date__c,
                                                        Func_SOD_Status__c
                                                    FROM
                                                        IS_Opportunity_Demand__c
                                                    where
                                                        Opportunity_ID__c = :opporID
                                                    AND
                                                        (
                                                        Approval_Date__c !=null
                                                        )]; 
        
        if(isoList.size()==0){
            return 'Abort';

        }else if(isoList.size()>0){
            return 'CommitCode';
        }
        return 'NoneIn';
        
    }
    /**
    OCM用，取消SI需求表
    */
    WebService static String setAbortSI(id isoID,String AbortReason){
        List<IS_Opportunity_Demand__c> updateList = new List<IS_Opportunity_Demand__c>();
        List<id> oppidList = new List<id>();
        List<Opportunity> Opplist = new List<Opportunity>();
        if(AbortReason==null||String.isBlank(AbortReason)){
            return '请输入终止SI需求原因';
        }else{
            updateList = [SELECT id,Abort_SI_Reason__c,Abort_Date__c,Opportunity_ID__c from IS_Opportunity_Demand__c where id = :isoID];
            for(IS_Opportunity_Demand__c iso : updateList){
                iso.Abort_SI_Reason__c = AbortReason;
                iso.Abort_Date__c = Date.today();
                oppidList.add(iso.Opportunity_ID__c);
            }
            Opplist = [SELECT Project_decide_date__c , Stock_Submit_Date__c , Stock_Confrim_Date__c from Opportunity WHERE id in:oppidList];
            for(Opportunity ops : Opplist){
                ops.Project_decide_date__c = null;
                ops.Stock_Submit_Date__c = null;
                ops.Stock_Confrim_Date__c = null;
            }
            Savepoint sp = Database.setSavepoint();
            try{
                update Opplist;
                update updateList;
                return 'Fin';
            }catch (Exception o){
                Database.rollback(sp);
                return 'DataBase is Crashed,Connect with the Developer PLEASE';
            }
        }
    }
    /**
    OCM询价用，取消SI询价，将相关联的SI需求表无效化
    */
    public static void updateSIodcList(List<String> OpporList){
        //询价失单，将询价对应的SI需求表无效化
        List<IS_Opportunity_Demand__c> ODCLIST = new List<IS_Opportunity_Demand__c>();
            ODCLIST = [SELECT id,Abort_Date__c from IS_Opportunity_Demand__c where Opportunity_ID__c in:OpporList and Abort_Date__c=null];
            for(IS_Opportunity_Demand__c Od : ODCLIST){
                Od.Abort_Date__c = Date.today();
            }
            update ODCLIST;
    }
    /*
    =======================================================================================================================
    ===================================================SI 询价部分util集合=================================================
    =======================================================================================================================
    */
    WebService static void addBatchIfLogForCnt(String typeStr, String operationType, String fileType, String hpId) {
        BatchIF_Log__c log = new BatchIF_Log__c(
            Type__c = typeStr,
            Is_Error__c = 0
        );
        log.Account__c = hpId;
        log.Log__c = operationType;
        log.Log2__c = fileType;
        
        insert log;
    }
    
    WebService static String setSObjectShare(String sobjectName, String rowCause, String parentId, List<String> userAccess, String ownerId) {
        try {
            List<SObject> sObjList = new List<SObject>();
            for (String ua : userAccess) {
                String userid = ua.split('_')[0];
                String access = ua.split('_')[1];
                SObject sObj = Schema.getGlobalDescribe().get(sobjectName).newSObject();
                if (String.isBlank(userid) == false && userid.substring(0, 15) != ownerId.substring(0, 15)) {
                    sObj.put('RowCause', rowCause);
                    sObj.put('ParentId', parentId);
                    sObj.put('UserOrGroupId', userid);
                    sObj.put('AccessLevel', access);
                    sObjList.add(sObj);
                }
            }
            if (sObjList.size() > 0) insert sObjList;
            return 'OK';
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    // SWAG-BJ29Z4 营业助理共享询价字段审批加入共享 start
    WebService static String setOpportunityShare(String sobjectName, String parentId, List<String> userAccess, String ownerId) {
        System.debug(sobjectName+'======'+parentId+'======'+ownerId);
        try {
            List<SObject> sObjList = new List<SObject>();
            for (String ua : userAccess) {
                String userid = ua.split('_')[0];
                String access = ua.split('_')[1];
                SObject sObj = Schema.getGlobalDescribe().get(sobjectName).newSObject();
                if (String.isBlank(userid) == false && userid.substring(0, 15) != ownerId.substring(0, 15)) {
                    // sObj.put('RowCause', rowCause);
                    sObj.put('ParentId', parentId);
                    sObj.put('UserOrGroupId', userid);
                    sObj.put('AccessLevel', access);
                    sObjList.add(sObj);
                }
            }
            System.debug(sObjList+'======');
            if (sObjList.size() > 0) insert sObjList;
            return 'OK';
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    // SWAG-BJ29Z4 营业助理共享询价字段审批加入共享 end
    
    public static void insertBatchIfLog(BatchIF_Log__c bl) {
        insert bl;
    }
    
    public static List<BatchIF_Log__c> getBatchIfLogForRequest(String typeStr, String hpId, Datetime dt) {
        return [select Id from BatchIF_Log__c where Type__c = :typeStr and Account__c = :hpId
                 and RequestStatus__c != 'Finish' and RequestStatus__c != 'Error' and CreatedDate > :dt];
    }
    public static Integer getOlympusWorkDayCount(Date fromDate, Date toDate) {
        AggregateResult[] calAggResult = [Select Count(Id) cnt From OlympusCalendar__c Where Date__c >= :fromDate And Date__c <= :toDate And IsWorkDay__c = 1];
        Integer workDayCount = (Integer) calAggResult[0].get('cnt');
        return workDayCount;
    }
    
    public static Pricebook2 getStandardPricebook() {
        if (system.Test.isRunningTest()) { 
            return new Pricebook2(Id = System.Test.getStandardPricebookId(), Name = 'Standard Pricebook');
        } else {
            List<Pricebook2> pbs = [Select Id, Name From Pricebook2 where IsStandard = true AND isActive = true];
            if (pbs.size() > 0) {
                return pbs[0];
            } else {
                return null;
            }
        }
    }
    public static Set<Id> getAllSubRoleIds(Id userRoleId, String additionalRoleName) {
        // currentRoleId と additionalRoleName まず queryする
        Map<Id, UserRole> parentRoleMap = new Map<Id, UserRole>();
        Boolean isAdditional = false;
        if (String.isBlank(additionalRoleName) == true) {
            parentRoleMap = new MAP<Id, UserRole>([select Id from UserRole where Id = :userRoleId]);
        } else {
            isAdditional = true;
            List<String> addtionalRoleNameList = additionalRoleName.split(',');
            parentRoleMap = new MAP<Id, UserRole>([select Id from UserRole where Id = :userRoleId or DeveloperName in :addtionalRoleNameList]);
        }
        //MAP<Id, UserRole> parentRoleMap = new MAP<Id, UserRole>([select Id from UserRole where Id = :userRoleId or DeveloperName = :additionalRoleName]);
        Map<Id, Set<Id>> allRoleMap = new Map<Id, Set<Id>>();
        for (UserRole role : [select Id, ParentRoleId from UserRole]) {
            Set<Id> roleIds = allRoleMap.get(role.ParentRoleId);
            if (roleIds == null) {
                roleIds = new Set<Id>();
            }
            roleIds.add(role.Id);
            allRoleMap.put(role.ParentRoleId, roleIds);
        }
        return getSubRoleRecursive(parentRoleMap.keySet(), allRoleMap, isAdditional, userRoleId);
    }

    private static Set<Id> getSubRoleRecursive(Set<Id> roleIds, Map<Id, Set<Id>> allRoleMap, Boolean isAdditional, Id userRoleId) {
        Set<Id> currentRoleIds = new Set<Id>();

        // get all of the roles underneath the passed roles
        for (Id parentRoleId : roleIds) {
            if (allRoleMap.get(parentRoleId) != null) {
                currentRoleIds.addAll(allRoleMap.get(parentRoleId));
            }
        }

        // go fetch some more rolls!
        if(currentRoleIds.size() > 0) {
            currentRoleIds.addAll(getSubRoleRecursive(currentRoleIds, allRoleMap, isAdditional, userRoleId));
        }
        
        // 兼職の場合、兼職Role自身のIdも入れる
        if (isAdditional) {
            roleIds.remove(userRoleId);
            currentRoleIds.addAll(roleIds);
        }
        return currentRoleIds;
    }

    public static String getOppSearchSQOL(String visitorPlaceId, String nameCondition) {
        Account a = null;
        a = [select Id, Hospital__c, Agent_Ref__c, Parent.Parent.RecordType.DeveloperName, Parent.RecordType.DeveloperName, RecordType.DeveloperName from Account where Id=:visitorPlaceId];
        
//        String nameCondition = '%' + String.escapeSingleQuotes(query.replaceAll('%', '')) + '%';
        system.debug('cond=' + nameCondition);
        
        // 検索
        String queryString = '';
        String temptoday = Date.today().format().replace('/', '-');
        //String tempLastDate = Date.today().addDays(365).format().replace('/', '-');
        String tempLastDate = Date.today().addDays(-365).format().replace('/', '-');
        // 病院
        if (a.Parent.Parent.RecordType.DeveloperName == 'HP') {
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and StageName IN (\'引合\',\'注残\',\'出荷\') and RecordTypeId = \'01210000000QekK\' order by Name, Opportunity_No__c, Department_Name__c limit 31';
            // 20200616 CHAN-BQM8LU vivek start
            // 20191126 SWAG-BJA6JK LHJ Start
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and StageName IN (\'引合\',\'注残\',\'出荷\') and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and StageName IN (\'引合\',\'注残\') and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210824 zh SWAG-C5S46P start
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__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 CountNoInstall__c > 0 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';

            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__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 DeliveryDate__c > '+temptoday+' and DeliveryDate__c <= '+tempLastDate+')) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210824 zh SWAG-C5S46P end
            // 20191126 SWAG-BJA6JK LHJ End
            //20210826 mzy SWAG-C5S46P start
            //改为用 发货完毕日 判断 且 将 2012年创建的且询价状态是发货/完毕的数据排除
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__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 > '+temptoday+' and Shipping_Finished_Day__c <= '+tempLastDate+' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__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';
            //20210826 mzy SWAG-C5S46P end
            // 20200616 CHAN-BQM8LU vivek end
        }
        // 販売店
        else if (a.RecordType.DeveloperName == 'Agency') {
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' (Agency1__c=\'' + a.Id + '\' or Agency2__c=\'' + a.Id + '\') and StageName IN (\'引合\',\'注残\',\'出荷\') and RecordTypeId = \'01210000000QekK\' order by Name, Opportunity_No__c, Department_Name__c limit 31';
            // 20200616 CHAN-BQM8LU vivek start
            // 20191126 SWAG-BJA6JK LHJ Start
            // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' (Agency1__c=\'' + a.Id + '\' or Agency2__c=\'' + a.Id + '\') and StageName IN (\'引合\',\'注残\',\'出荷\') and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c, Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition + ' (Agency1__c=\'' + a.Id + '\' or Agency2__c=\'' + a.Id + '\') and StageName IN (\'引合\',\'注残\') and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210824 zh SWAG-C5S46P start
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__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 CountNoInstall__c > 0 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';

            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__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 DeliveryDate__c > '+temptoday+' and DeliveryDate__c <= '+tempLastDate+')) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            //20210824 zh SWAG-C5S46P end
            //20210826 mzy SWAG-C5S46P start
            //改为用 发货完毕日 判断 且 将 2012年创建的且询价状态是发货/完毕的数据排除
            //queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__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 > '+temptoday+' and Shipping_Finished_Day__c <= '+tempLastDate+' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';
            queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,CountNoInstall__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';
            //20210826 mzy SWAG-C5S46P end
            // 20191126 SWAG-BJA6JK LHJ End
            // 20200616 CHAN-BQM8LU vivek end
        }

        return queryString;
    }
    // 用来解决经销商活动的担当
    public static List<Agency_Opportunity__c> DatabaseQuery(String soql){
        return DataBase.query(soql);
    }

    public class myException extends Exception {}

    WebService static String qureySoql(String soql) {
        List<SObject> rtnList = Database.query(soql);
        String rtnJSON = JSON.serialize(Database.query(soql), true);
        System.debug('rtnJSON:' + rtnJSON);
        return rtnJSON;
    }

    // GIR 项目需求用，找不到Add_report的测试程序 20191219 by vivek start
    WebService static Account getAccountForJs(String id){
        return [select Id, Name, Province_formula__c, Hospital__r.Salesdepartment_HP__c,Department_Class__r.Name,Department_Class__r.OwnerId, Department_Class__r.Owner.Name, Department_Class__r.Id, OwnerId, Owner.Name,  
                Hospital__r.Name, Hospital__r.Id, Hospital__r.OCM_Category__c,Hospital__r.OCM_Management_Province__r.GI_assistant__c,Hospital__r.OCM_Management_Province__r.GI_assistant__r.Name
                from Account where Id = :id];
    }
    // GIR 项目需求用，找不到Add_report的测试程序 20191219 by vivek end

    // 任务和日报 2020-05-23 update by vivek start
    public static Event__c getNoIdEventC(Event__c dlyevt){
        dlyevt.Id = null;
        return dlyevt;
    }
    public static Event getNoIdEvent(Event dlyec){
        dlyec.Id = null;
        return dlyec;

    } 
    public static Event getEventList(Id eventcid){
        Event dlyec = [select id, ActivityDate, OwnerId, Subject, task_id__c,whatid__c, EventC_ID__c, NextEventC_ID__c, AppCdId__c, SyncCreatedDate__c, 
                                  StartDateTime, DurationInMinutes, Main_Visit_Location__c, Activity_Type2__c, IsScheduled__c, BeforeActivityDate__c,
                                  Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c, Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c,
                                  Purpose_Type__c, Location, Related_Opportunity1__c, Related_Service1__c, Related_Opportunity1_ID__c, Related_Service1_ID__c, WS_flg__c,
                                  Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,OPDPlan_Flag__c,
                                  Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                                  Activity_Purpose__c, Activity_PurposeFSE__c, Activity_PurposeEscFSE__c, Purpose_TypeFSE__c, Purpose_TypeEscFSE__c,Opd_Plan__c  
                                  from Event where EventC_ID__c = :eventcid];
                                  return dlyec;
    }

    public static List<Event> getEventsList(Set<String> eventcid){
        List<Event> dlyec = [select id, ActivityDate, OwnerId, Subject, whatid__c,task_id__c, EventC_ID__c, NextEventC_ID__c, AppCdId__c, SyncCreatedDate__c, 
                                  StartDateTime, DurationInMinutes, Main_Visit_Location__c, Activity_Type2__c, IsScheduled__c, BeforeActivityDate__c,
                                  Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c, Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c,
                                  Purpose_Type__c, Location, Related_Opportunity1__c, Related_Service1__c, Related_Opportunity1_ID__c, Related_Service1_ID__c, WS_flg__c,
                                  Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,OPDPlan_Flag__c,
                                  Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                                  Activity_Purpose__c, Activity_PurposeFSE__c, Activity_PurposeEscFSE__c, Purpose_TypeFSE__c, Purpose_TypeEscFSE__c
                                  from Event where Id = :eventcid];
                                  return dlyec;
    }
    // 任务和日报 2020-05-23 update by vivek end

    //失但报告申请保存    2021-09-13 upsert  zxk  start
    public static void lostOrder(Lost_Report__c lostData) {
        upsert lostData;
    }

    // FY23修改 WLIG-CFV4AV 重点产品维护（新）start
    public static String getKeyByProduct(String keyword) {
        if (String.isBlank(keyword)) {
            return null;
        }
        String KeyProductMapping = System.Label.Key_Product_Mapping;
        Map<String, Object> mapping = (Map<String, Object>) JSON.deserializeUntyped(KeyProductMapping);
        System.debug('==Mapping is: ' + mapping);
        
        return mapping.get(keyword) != null ? String.valueOf(mapping.get(keyword)) : null;
    }
    // FY23修改 WLIG-CFV4AV 重点产品维护（新）end

    //20221021  lt SWAG-CHL5XA【FY23询价改善】-统计主机台数 start
    public static void UpdateBiddingFlag(List<String> oppId){
        List<Tender_Opportunity_Link__c> links = [SELECT Id, Tender_information__c, Tender_information__r.IsReactionOpp__c, Opportunity__c 
                                                  FROM Tender_Opportunity_Link__c 
                                                  WHERE Opportunity__c in :oppId ];

        Map<String,Tender_information__c> tenderMap = new Map<String,Tender_information__c>();

        for (Tender_Opportunity_Link__c link : links){
        
            Tender_information__c temptender = new Tender_information__c();
            temptender.Id = link.Tender_information__c;
            temptender.IsReactionOpp__c = true;
            tenderMap.put(temptender.id ,temptender); 
        
        }

        if(tenderMap.size()>0){
            update tenderMap.values();
        }
                    
    }
    //20221021  lt SWAG-CHL5XA【FY23询价改善】-统计主机台数 end
   
}