/*
 TestClass
 ConsumApplyTriggerHandlerTest
 ConsumApplyTriggerTest
 ConsumApplyTriggerTest2
 ConsumFixtureManage14Test
 ConsumFixtureManage11Test
*/
public without sharing class ConsumApplyTriggerHandler extends Oly_TriggerHandler {
    private Map<Id, Consum_Apply__c> newMap;
    private Map<Id, Consum_Apply__c> oldMap;
    private List<Consum_Apply__c> newList;
    private List<Consum_Apply__c> oldList;
    private static boolean hasInsert;
    private static Map<Date, OlympusCalendar__c> calendarMap = new Map<Date, OlympusCalendar__c>();        // 已经处理过排队顺 Consum_Apply_Equipment_Set_Detail__c.Id
    // static initialization
    static {
        hasInsert = false;
    }

    private static Map<String, String> Consum_Apply_App_CCEmailMap = FixtureUtil.initRental_Apply_App_CCEmailMap();
    private static Map<Id, User> personInChargeMap = new Map<Id, User>();

    private static Map<String, OCM_Management_Province__c> mpMap {
        set;
        get{
            if (mpMap == null) {
                mpMap = new Map<String, OCM_Management_Province__c>();
                for (OCM_Management_Province__c mp : [SELECT id
                                                           , Name
                                                           , Consum_assistant__c
                                                           , Consum_assistant2__c
                                                           , Consum_assistant3__c
                                                           , Energy_assistant__c
                                                        FROM OCM_Management_Province__c]) {
                    mpMap.put(mp.Name, mp);
                }
            }
            return mpMap;
        }
    }

    public ConsumApplyTriggerHandler() {
        this.newMap = (Map<Id, Consum_Apply__c>) Trigger.newMap;
        this.oldMap = (Map<Id, Consum_Apply__c>) Trigger.oldMap;
        this.newList = (List<Consum_Apply__c>) Trigger.new;
        this.oldList = (List<Consum_Apply__c>) Trigger.old;
    }

    protected override void beforeInsert() {
        checkOneConsumApplyForQIS();
        setManager();
        setAssistant();
        setcalendarMap();
        beforeSetValue();
        setDateRemind(); // 需要日历信息 所以在日历后面执行
    }
    protected override void afterInsert() {
        // Check本部是否可以选择
        // checkbenbu();
        setRental_Apply_Consum_ApplyId();
    }
    protected override void beforeUpdate() {
        checkOneConsumApplyForQIS();
        setManager();
        setAssistant();
        setcalendarMap();
        beforeSetValue();
        setDateRemind(); // 需要日历信息 所以在日历后面执行
        setDetailForEmail();
        approvalCheck();
    }

    protected override void afterUpdate() {
        // Check本部是否可以选择
        // checkbenbu();
        cancelRa();
        // before では数式項目がnullの場合があります
        formulaToTextCheck();
        //医院确认相关的字段更新的时候要更新一览
        reReceivedConfirmStatus();
        //医院确认相关的字段更新的时候要更新一览
        // reApprovalStatus();
        // 取消申请单的审批
        removedProcessRequest();
        // 删除明细
        // checkStatucDeleteDetail();
    }

    // 同一个QIS下不能有多个耗材申请，RentalApplyBeforeUpdate.trigger
    private void checkOneConsumApplyForQIS(){
        for(Consum_Apply__c ca : this.newList) {
            if (String.isBlank(ca.QIS_number__c) == false) {
                if (Trigger.isInsert) {
                    List<Consum_Apply__c> rs = [select Id from Consum_Apply__c where QIS_number__c = :ca.QIS_number__c and Status__c <> '取消' and Status__c <> '删除'];
                    if (rs.size() > 0 && ca.Old_Consum_Apply__c == null ) {
                        ca.addError('同一个QIS记录不能重复申请耗材');
                    }
                }
                if (Trigger.isUpdate && ca.QIS_number__c != this.oldMap.get(ca.Id).QIS_number__c) {
                    List<Consum_Apply__c> rs = [select Id from Consum_Apply__c where QIS_number__c = :ca.QIS_number__c and Id <> :ca.Id and Status__c <> '取消' and Status__c <> '删除'];
                    if (rs.size() > 0 && ca.Old_Consum_Apply__c == null ) {
                        ca.addError('同一个QIS记录不能重复申请耗材');
                    }
                }
            }
        }
    }

    public void setRental_Apply_Consum_ApplyId() {
        Map<Id, Rental_Apply__c> raMap = new Map<Id, Rental_Apply__c>();
        for (Consum_Apply__c nObj : newList) {
            if (String.isNotBlank(nObj.Rental_Apply__c)) {
                if (raMap.containsKey(nObj.Rental_Apply__c) == false) {
                    Rental_Apply__c ra = new Rental_Apply__c(Id = nObj.Rental_Apply__c
                                , Consum_ApplyId__c = nObj.Id);
                    raMap.put(nObj.Rental_Apply__c, ra);
                }
            }
        }
        if (raMap.isEmpty() == false) {
            update raMap.values();
        }
    }

    // private void checkbenbu() {
    //     for (Consum_Apply__c nObj : newList) {
    //         if (nObj.DataMigration_Flag__c == false) {
    //             Consum_Apply__c oObj;
    //             if (Trigger.isUpdate) {
    //                 oObj = oldMap.get(nObj.Id);
    //             }
    //             if ((Trigger.isInsert
    //                     || oObj.Demo_purpose2__c != nObj.Demo_purpose2__c
    //                     || oObj.Salesdept__c != nObj.Salesdept__c)
    //                     // 日报画面新建的情况，可以不填使用目的
    //                     && !(nObj.Demo_purpose2__c == null && nObj.Event_Id__c != null)) {
    //                 if (!FixtureUtil.departmentMap.containsKey(nObj.Demo_purpose2__c)) {
    //                     nObj.Demo_purpose2__c.addError('没有定义目的2 ' + nObj.Demo_purpose2__c + '可以选择的本部');
    //                 }
    //                 else {
    //                     Set<String> benbuSet = new Set<String>();
    //                     benbuSet.addAll(FixtureUtil.departmentMap.get(nObj.Demo_purpose2__c));
    //                     if (!benbuSet.contains(nObj.Salesdept__c)) {
    //                         nObj.Person_In_Charge__c.addError('此用户无该使用目的的申请权限');
    //                     }
    //                 }
    //             }
    //         }
    //     }
    // }
    /**
    @description modelCntMap 型号=>数量
    @return 拼接好的型号及数量字符串
    */
    private String getJoinedMessage(Map<String, Integer> modelCntMap) {
        String message = '';
        for(String model:modelCntMap.keySet()) {
            message += model + ' *' + modelCntMap.get(model) + '\n';
        }
        return message;
    }

    private void setDetailForEmail () {
        Set<Id> caIdSet = new Set<Id>();
        for (Consum_Apply__c nObj : newList) {
            caIdSet.add(nObj.Id);
        }
        List<Consum_Apply_Equipment_Set_Detail__c> caesdList = [
                SELECT Fixture_Model_No__c
                     , Consum_Apply__c
                FROM Consum_Apply_Equipment_Set_Detail__c
                WHERE Consum_Apply__c IN:caIdSet
                AND Cancel_Select__c = false
                ORDER BY Name
            ];
        Map<Id,String> caDetailMap = new Map<Id,String> ();
        String oCaId = '';
        Map<String, Integer> modelCntMap = new Map<String, Integer>();
        for (Consum_Apply_Equipment_Set_Detail__c caesd : caesdList) {
            if (String.isBlank(oCaId)) {
                oCaId = caesd.Consum_Apply__c;
            }
            if (oCaId != caesd.Consum_Apply__c) {
                String message = getJoinedMessage(modelCntMap);
                caDetailMap.put(oCaId, message);
                modelCntMap = new Map<String, Integer>();
            }
            oCaId = caesd.Consum_Apply__c;
            String model = caesd.Fixture_Model_No__c;
            Integer cnt = 1;
            if(modelCntMap.containsKey(model)){
                cnt = modelCntMap.get(model) + 1; 
            }
            modelCntMap.put(model, cnt);
        }
        if (String.isNotBlank(oCaId)) {
            String message = getJoinedMessage(modelCntMap);
            caDetailMap.put(oCaId, message);
        }
        for (Consum_Apply__c nObj : newList) {
            if (String.isNotBlank(caDetailMap.get(nObj.Id))) {
                nObj.Consum_Apply_Detail_ForEmail__c = caDetailMap.get(nObj.Id);
            }
        }
    }
    // 耗材助理设置
    // Copy From RentalApplyTrigger
    private void setAssistant() {
        Set<Id> personInChargeIds = new Set<Id>();
        for (Consum_Apply__c nObj : newList) {
            if (String.isNotBlank(nObj.Person_In_Charge__c)
                && personInChargeMap.containsKey(nObj.Person_In_Charge__c) == false) {
                personInChargeIds.add(nObj.Person_In_Charge__c);
            }
        }
        if (personInChargeIds.size() > 0) {
            if (System.Test.isRunningTest() && trigger.isUpdate) {
            } else {
                for (User use : [SELECT Id
                                     , Name
                                     , OCM_man_province_Rental__c
                                     , Dept__c
                                  FROM User
                                 WHERE Id IN :personInChargeIds]
                ) {
                    personInChargeMap.put(use.Id, use);
                }

                for (Consum_Apply__c nObj : newList) {
                    if (personInChargeMap.containsKey(nObj.Person_In_Charge__c)) {
                        User tempUser = personInChargeMap.get(nObj.Person_In_Charge__c);
                        OCM_Management_Province__c omp = mpMap.get(tempUser.OCM_man_province_Rental__c);
                        if (omp != null) {
                            /*
                            SWAG-B6X8CK  把能量事业本部的判断去掉，都取备品助理 2018/11/29 start
                             */
                            /*if (tempUser.Dept__c == '能量事业本部') {
                                rac.Rental_Assistant__c = omp.Energy_assistant__c;
                                rac.Rental_Assistant2__c = null;
                                rac.Rental_Assistant3__c = null;
                            } else {*/
                                nObj.Consum_Assistant__c = omp.Consum_assistant__c;
                                nObj.Consum_Assistant2__c = omp.Consum_assistant2__c;
                                nObj.Consum_Assistant3__c = omp.Consum_assistant3__c;

                            //}
                            /*
                            SWAG-B6X8CK  把能量事业本部的判断去掉，都取备品助理 2018/11/29 end
                             */
                        }
                    }
                }
            }
        }
    }

    // 申请书部长经理等设置
    private void setManager() {
        // 申請中かどうかのチェック
        List<Id> copyUserIds = new List<Id>();                       // 件数は Trigger.New と同じ
        List<Consum_Apply__c> newList1 = new List<Consum_Apply__c>(); // 件数は Trigger.New と同じ
        for (Consum_Apply__c nObj : newList) {
            Consum_Apply__c oObj;
            if (Trigger.isUpdate) {
                oObj = oldMap.get(nObj.Id);
            }
            if (nObj.Person_In_Charge__c != null) nObj.OwnerId = nObj.Person_In_Charge__c;
            System.debug(nObj.Person_In_Charge__c);
            System.debug(nObj.OwnerId);
            if (Trigger.isInsert
                        || (Trigger.isUpdate && oObj.Status__c != nObj.Status__c && nObj.Status__c == '填写完毕')
                        || (Trigger.isUpdate && oObj.OwnerId != nObj.OwnerId)
                ) {
                    newList1.add(nObj);
                    copyUserIds.add(nObj.OwnerId);
                }
        }
        System.debug(copyUserIds);
        if (copyUserIds.size() > 0) {
            Map<Id, User> copyUserMap = new Map<Id, User>([
                SELECT Id, Name, Buzhang_Equipment_Manager__c, JingliEquipmentManager__c, SalesManager__c, BuchangApprovalManagerSales__c, JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c, TongkuoZongjian__c FROM User WHERE Id IN :copyUserIds
            ]);

            for (Integer i = 0; i < copyUserIds.size(); i++) {
                Consum_Apply__c nObj = newList1[i];
                User loginUser = copyUserMap.get(copyUserIds[i]);
                nObj.SalesManager__c = loginUser.JingliEquipmentManager__c;
                nObj.BuchangApprovalManagerSales__c = loginUser.Buzhang_Equipment_Manager__c;
                nObj.JingliApprovalManager__c = loginUser.JingliApprovalManager__c;
                nObj.BuchangApprovalManager__c = loginUser.BuchangApprovalManager__c;
                nObj.ZongjianApprovalManager__c = loginUser.ZongjianApprovalManager__c;
                nObj.TongkuoZongjian__c = loginUser.TongkuoZongjian__c;
                System.debug(loginUser);
            }
        }
    }

    private void beforeSetValue() {

        List<Consum_Apply__c> ApprovalApply = new List<Consum_Apply__c>();
        // List<Consum_Apply__c> addApprovalApply = new List<Consum_Apply__c>();
        Set<Id> hpIdSet = new Set<Id>();
        for (Consum_Apply__c nObj : newList) {
            // 由于requestNoJoinStr3__c和requestNoJoinStr2__c在新建申请时取不到值，所以Name更新在workflow里做
            // nObj.Name = nObj.requestNoJoinStr1__c + '-' + nObj.requestNoJoinStr3__c + '-' + nObj.requestNoJoinStr2__c; // 申请No.
            nObj.HP_received_sign_text__c = nObj.HP_received_sign_rich__c;
            nObj.HP_received_Confirmed__c = nObj.HP_received_Confirmed_F__c;
            nObj.Rental_Apply_Mail__c = nObj.Rental_Apply_Mail_F__c;
            if (nObj.Hospital__c != null ) hpIdSet.add(nObj.Hospital__c);
            Consum_Apply__c oObj;

            if (Trigger.isUpdate || Trigger.isInsert) {
                if (Trigger.isUpdate){
                    oObj = oldMap.get(nObj.Id);
                }
                else{
                    oObj = new Consum_Apply__c();
                }
                if (oObj.Request_shipping_day__c != nObj.Request_shipping_day__c) {
                    if (nObj.Request_shipping_day__c == null) {
                        nObj.Request_Shipping_7days_Before__c = null;
                    }
                    else {
                        Date d7before;
                        System.debug(calendarMap);
                        System.debug(nObj.Request_shipping_day__c);
                        if (calendarMap.containsKey(nObj.Request_shipping_day__c) && calendarMap.get(nObj.Request_shipping_day__c).Before_7_WorkDay__c != null) {
                            d7before = calendarMap.get(nObj.Request_shipping_day__c).Before_7_WorkDay__c;
                        }
                        else {
                            d7before = Consum_ApplyUtil.getWD_addday(nObj.Request_shipping_day__c, -7);
                        }
                        nObj.Request_Shipping_7days_Before__c = d7before;
                    }
                }
            }
            if (Trigger.isUpdate) {
                oObj = oldMap.get(nObj.Id);
                if (oObj.Status__c != Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Qu_Xiao.ordinal())
                    && nObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Qu_Xiao.ordinal())) {
                    nObj.Cancel_time__c = Datetime.now();
                    // nObj.Cancel_Mem__c = UserInfo.getUserId();
                }
                if (oObj.Status__c != '填写完毕' && nObj.Status__c == '填写完毕') {
                    ApprovalApply.add(nObj);
                    if (Consum_Apply_App_CCEmailMap.containsKey(nObj.Salesdept__c)) {
                        String ccUser = nObj.get(Consum_Apply_App_CCEmailMap.get(nObj.Salesdept__c)) == null ? null : String.valueOf(nObj.get(Consum_Apply_App_CCEmailMap.get(nObj.Salesdept__c)));
                        nObj.CC_EmailUser__c =  ccUser;
                    }
                }

                // if (oObj.Add_Approval_Status__c != '填写完毕' && nObj.Add_Approval_Status__c == '填写完毕') {
                //     addApprovalApply.add(nObj);
                // }

                //批准之前就有批准时间的话需要清空
                if ((nObj.Status__c == '草案中'
                      || nObj.Status__c == '填写完毕'
                      || nObj.Status__c == '申请中')
                    && nObj.Request_approval_time__c != null) {
                    nObj.Request_approval_time__c = null;
                }

                // 提交申请的时候设置跟进询价状态（申请时）
                if (oObj.Status__c != Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Tian_Xie_Wan_Bi.ordinal())
                    && nObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Tian_Xie_Wan_Bi.ordinal())) {
                        //nObj.Follow_pcl_status2_Text__c = nObj.Follow_pcl_status2__c;
                }

                // 上传试用表后更新上传时间
                if (oObj.HP_received_sign_rich__c != nObj.HP_received_sign_rich__c && String.isNotBlank(nObj.HP_received_sign_rich__c)){
                    nObj.Consum_Trial_Update_Time__c = System.now();
                }

                // 备品中心确认试用表和回寄后，更新时间
                if((oObj.AssetManageConfirm__c != nObj.AssetManageConfirm__c) && nObj.AssetManageConfirm__c){
                    nObj.Consum_Received_Day__c = System.today();
                }

            }
            if (nObj.demo_purpose2__c == '试用（无询价）'
                    || nObj.demo_purpose2__c == '试用（有询价）'
                    || nObj.demo_purpose2__c == '新产品评价'
                    || nObj.demo_purpose2__c == '其他'
                    || nObj.demo_purpose2__c == '协议借用') {
                //if (trigger.isInsert
                //        || (oObj.Request_shipping_day__c != nObj.Request_shipping_day__c)
                //        || oObj.Hope_Lonaer_date_Num__c != nObj.Hope_Lonaer_date_Num__c) {
                //    if (nObj.Hope_Lonaer_date_Num__c != null && nObj.Request_shipping_day__c != null) {
                //        nObj.Request_return_day__c = (nObj.Request_shipping_day__c + Integer.valueOf(nObj.Hope_Lonaer_date_Num__c));
                //    }
                //    else {
                //        nObj.Request_return_day__c = null;
                //    }
                //}
            }
            else if (nObj.demo_purpose2__c == '一般用户'
                    || nObj.demo_purpose2__c == '保修用户'
                    || nObj.demo_purpose2__c == '再修理'
                    || nObj.demo_purpose2__c == '索赔QIS'
                    || nObj.demo_purpose2__c == '已购待货') {
                // 不需要设置预计归还日
            }
            else if (nObj.demo_purpose2__c == '学会展会') {
                // 不需要设置预计归还日
            }
            // 必ず最後で置く
            nObj.Status_Text__c = nObj.Status__c;
            nObj.RA_Status_Text__c = nObj.RA_Status__c;
            nObj.NotWatch_RA_Status__c = nObj.NotWatch_RA_Status_F__c;
            nObj.Notice_of_Delivery_Hash__c = getHash('SHA-256', nObj.Notice_of_Delivery_Text__c);
            nObj.Assigned_Hash__c = getHash('SHA-256', nObj.Assigned_Text__c);
            // OLY_OCM-621 From WF 设定-申请者相关字段文本化
            if (String.isBlank(nObj.Work_Location_text__c)
                    || String.isBlank(nObj.Owner_province_text__c)
                    || String.isBlank(nObj.Onwer_job_category_text__c)
                    || String.isBlank(nObj.Salesdepartment_text__c)
                    || String.isBlank(nObj.Branch_text__c)
                    || String.isBlank(nObj.Salesdept_text__c)
                    || (Trigger.isUpdate
                            && (oObj.OwnerId != nObj.OwnerId || hasInsert))) {
                // 设定-借出申请人-工作地(文本)
                nObj.Work_Location_text__c = nObj.Work_Location__c;
                // 设定-借出申请人-省(文本)
                nObj.Owner_province_text__c = nObj.Owner_province__c;
                // 设定-借出申请人-职种(文本)
                nObj.Onwer_job_category_text__c = nObj.Onwer_job_category__c;
                // 设定-借出申请人-销售本部(文本)
                nObj.Salesdepartment_text__c = nObj.Salesdepartment__c;
                // 设定-借出申请人-分公司(文本)
                nObj.Branch_text__c = nObj.Branch__c;
                // 设定-申请者销售本部(文本)
                nObj.Salesdept_text__c = nObj.Salesdept__c;

                // OLY_OCM-666 第二次trigger更新正确数据， 新建数据时第二次更新OwnerId无变化， 需要强制更新
                if (Trigger.isInsert) {
                  ConsumApplyTriggerHandler.hasInsert = true;
              }
            }
        }
        //拷贝医院的市字段
        Map<Id, Account> accMap = new Map<Id, Account>();
        if (hpIdSet.size() > 0) {
            accMap.putAll([SELECT Id, City_Master__r.Name, State_Text__c FROM Account WHERE Id IN: hpIdSet]);
            for (Consum_Apply__c nObj : newList) {
                if (accMap.containsKey(nObj.Hospital__c)) {
                    nObj.HP_City__c = accMap.get(nObj.Hospital__c).City_Master__r.Name;
                }
            }
        }

        if (!ApprovalApply.isEmpty()) {
            List<Consum_Apply_Equipment_Set__c> raess = [
                    Select Id
                         //, Loaner_name_F__c
                         , Consum_Apply__c
                         //, Loaner_code_F__c
                         , First_RAESD_Model_No_F__c
                    From Consum_Apply_Equipment_Set__c
                    Where Consum_Apply__c =: ApprovalApply
                    AND Cancel_Select__c = false
                    order by Consum_Apply__c];
            Map<Id, String> raMap = new Map<Id, String>();
            String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
            for (Integer i = 0; i < raess.size(); i ++) {
                Consum_Apply_Equipment_Set__c raes = raess[i];
                if(!raMap.containsKey(raes.Consum_Apply__c)) {
                    raMap.put(raes.Consum_Apply__c, '');
                }
                String str = raMap.get(raes.Consum_Apply__c);
                raMap.put(raes.Consum_Apply__c,str + '备品配套'
                        + (i + 1)
                        + ':<BR>'
                        // + '<a href="'
                        // + baseUrl + '/' + raes.Id
                        // +'">'
                        + '' + raes.First_RAESD_Model_No_F__c
                        // + '  '
                        // + ' 主体明细型号:' + raes.First_RAESD__r.Fixture_Model_No_F__c
                        // + + '</a>' 
                        + '<BR>');
            }
            for (Consum_Apply__c nObj : newList) {
                if (raMap.containsKey(nObj.Id)) {
                    nObj.Email_Consum_Apply_Equipment_Set__c = raMap.get(nObj.id);
                }
            }
        }

        // if (!addApprovalApply.isEmpty()) {
        //     List<Consum_Apply_Equipment_Set_Detail__c> raesds = [SELECT Id
        //                 , Fixture_Model_No_F__c
        //                 , Consum_Apply_Equipment_Set__r.Consum_Apply__c
        //              FROM Consum_Apply_Equipment_Set_Detail__c
        //             WHERE Consum_Apply_Equipment_Set__r.Consum_Apply__c = :addApprovalApply
        //               AND Cancel_Select__c = false
        //               AND ApplyPersonAppended_F__c = true
        //               AND Add_Request_approval_time__c = null
        //               AND Add_Request_demo_time__c = null
        //             ORDER BY Consum_Apply_Equipment_Set__r.Consum_Apply__c];
        //     String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        //     Map<Id, String> raMap = new Map<Id, String>();
        //     for (Integer i = 0; i < raesds.size(); i ++) {
        //         Consum_Apply_Equipment_Set_Detail__c raes = raesds[i];
        //         if(!raMap.containsKey(raes.Consum_Apply_Equipment_Set__r.Consum_Apply__c)) {
        //             raMap.put(raes.Consum_Apply_Equipment_Set__r.Consum_Apply__c, '');
        //         }
        //         String str = raMap.get(raes.Consum_Apply_Equipment_Set__r.Consum_Apply__c);
        //         raMap.put(raes.Consum_Apply_Equipment_Set__r.Consum_Apply__c,str + '备品明细'
        //                 + (i + 1)
        //                 + ':<BR>'
        //                 // + '<a href="'
        //                 // + baseUrl + '/' + raes.Id
        //                 // +'">'
        //                 + '型号:' + raes.Fixture_Model_No_F__c
        //                 // + '</a>'
        //                 + '<BR>');
        //     }
        //     for (Consum_Apply__c nObj : newList) {
        //         if (raMap.containsKey(nObj.Id)) {
        //             nObj.Email_Add_Detail__c = raMap.get(nObj.id);
        //         }
        //     }
        // }
    }

    private void cancelRa() {
        Set<Id> raIdSet = new Set<Id>();
        for (Consum_Apply__c nObj : newList) {
            Consum_Apply__c oObj = oldMap.get(nObj.Id);
            System.debug(Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Qu_Xiao.ordinal()));
            System.debug(oObj.Status__c);
            System.debug(nObj.Status__c);
            if (oObj.Status__c != Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Qu_Xiao.ordinal())
                && nObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Qu_Xiao.ordinal())) {
                raIdSet.add(nObj.Id);
            }
        }
        if (raIdSet.isEmpty()) {
            return;
        }
        List<Consum_Apply_Equipment_Set__c> raess = [Select id, Consum_Apply__r.Cancel_Reason__c,
                Consum_Apply__r.Loaner_cancel_request__c
                FROM Consum_Apply_Equipment_Set__c
                WHERE Consum_Apply__c = :raIdSet
                  AND Cancel_Select__c = false // OLY_OCM-609 已经取消的备品借出一览不再修改取消理由等字段
                ];
        if (raess.size() > 0) {
            for (Consum_Apply_Equipment_Set__c raes : raess) {
                raes.Cancel_Select__c = true;
                raes.Cancel_Reason__c = raes.Consum_Apply__r.Cancel_Reason__c;
                raes.Loaner_cancel_Remarks__c = raes.Consum_Apply__r.Loaner_cancel_request__c;
                raes.Cancel_Mem__c = UserInfo.getUserId();
                raes.Cancel_Date__c = Date.today();
                raes.Cancel_Time__c = MainFixtureSelectController.getCurrentTime();
            }
            update raess;
        }
    }

    // From ConsumApplyApprovalProcess.trigger TODO test
    private void approvalCheck() {
        for (Consum_Apply__c nObj : newList) {
            Consum_Apply__c oObj = null;
            if (Trigger.isUpdate) {
                oObj = oldMap.get(nObj.Id);
            }
            if (
                    (
                        (oObj.Status__c != '已批准' && nObj.Status__c == '已批准')
                            // || (oObj.Status__c != '填写完毕' && nObj.Status__c == '填写完毕')
                    )

                    && nObj.Consum_Apply_Equipment_Set_Cnt__c != 0) {
//bp2               // 自动引当
                // 借出时间check
                String rs1 = ConsumApplyWebService.approvalCheck(nObj.Id);
                if (rs1.startsWith('1') == false) {
                    nObj.addError(rs1);
                }
                else {
                    nObj.Consum_Apply_Detail_ForEmail__c = rs1.removeStart('1');
                }
//bp2               else {
//                  // 正常终了
//                  raesNew.Status__c = '引当完了';
//              }
            }
        }
    }

    //before 数式の値がnullになる可能性がありますのでここでも一回チェックします
    private void formulaToTextCheck() {
        List<Consum_Apply__c> ras = new List<Consum_Apply__c>();
        List<Id> raIds = new List<Id>();
        for (Consum_Apply__c nObj : newList) {
            if (nObj.RA_Status_Text__c != nObj.RA_Status__c
                || nObj.Status_Text__c != nObj.Status__c
                || nObj.NotWatch_RA_Status__c != nObj.NotWatch_RA_Status_F__c) {
                Consum_Apply__c ra = new Consum_Apply__c(Id = nObj.Id);
                ra.RA_Status_Text__c = nObj.RA_Status__c;
                ra.Status_Text__c = nObj.Status__c;
                ra.NotWatch_RA_Status__c = nObj.NotWatch_RA_Status_F__c;
                ras.add(ra);
                // raIds.add(ra.Id);
            }
        }
        if (!ras.isEmpty()) {
            update ras;
        }

        // if (!raIds.isEmpty()) {
        //     ConsumApplyTriggerHandler.someFutureMethod(raIds);
        // }
    }

    // @future
    // public static void someFutureMethod(List<Id> recordIds) {
    //     List<Consum_Apply__c> ras = [Select Id from Consum_Apply__c Where Id IN :recordIds];
    //     update ras;
    //     // process account records to do awesome stuff
    // }

    // afterUpdate 医院确认相关的字段更新的时候要更新一览
    private void reReceivedConfirmStatus() {
        Set<Id> raIdSet = new Set<Id>();
        for (Consum_Apply__c nObj : newList) {
            Consum_Apply__c oObj = oldMap.get(nObj.Id);

            if (nObj.AssetManageConfirm__c != oObj.AssetManageConfirm__c
                    || nObj.HP_received_sign_NG__c != oObj.HP_received_sign_NG__c
                    || nObj.HP_received_sign_day__c != oObj.HP_received_sign_day__c) {
                raIdSet.add(nObj.Id);
            }
        }
         System.debug(raIdSet);
        if (raIdSet.isEmpty()) {
            return;
        }

        List<Consum_Apply_Equipment_Set__c> raess = [Select Id
                From Consum_Apply_Equipment_Set__c
                Where Consum_Apply__c = :raIdSet];
        System.debug(raess.size());
        update raess;
    }

    //
    // private void reApprovalStatus() {
    //     Map<Id, Consum_Apply__c> raIdMap = new Map<Id, Consum_Apply__c>();
    //     for (Consum_Apply__c nObj : newList) {
    //         Consum_Apply__c oObj = oldMap.get(nObj.Id);
    //         if (oObj.Add_Approval_Status__c != nObj.Add_Approval_Status__c
    //             && nObj.Request_approval_day__c != null
    //             && oObj.Request_approval_day__c == nObj.Request_approval_day__c
    //             && nObj.Add_Approval_Status__c != '填写完毕') {
    //             raIdMap.put(nObj.Id, nObj);
    //         }
    //     }

    //     if (raIdMap.isEmpty()) {
    //         return;
    //     }

    //     List<Consum_Apply_Equipment_Set_Detail__c> raesds = [Select Id, Consum_Apply__c
    //             From Consum_Apply_Equipment_Set_Detail__c
    //             Where Consum_Apply__c = :raIdMap.keySet()
    //             AND Select_Time__c = null
    //             AND ApplyPersonAppended_F__c = true
    //             AND Add_Request_approval_time__c = null];
    //     for (Consum_Apply_Equipment_Set_Detail__c raesd : raesds) {
    //         Consum_Apply__c ra = raIdMap.get(raesd.Consum_Apply__c);
    //         if (ra.Add_Approval_Status__c == '申请中') {
    //             raesd.Add_Request_demo_time__c = ra.Add_Request_demo_time__c;
    //         } else if (ra.Add_Approval_Status__c == '已批准') {
    //             raesd.Add_Request_approval_time__c = ra.Add_Request_approval_time__c;
    //         } else if (ra.Add_Approval_Status__c == '草案中') {
    //             raesd.Add_Request_demo_time__c = null;
    //             raesd.Add_Request_approval_time__c = null;
    //         }
    //     }
    //     update raesds;
    // }

    // 申请中的申请书取消时,取消审批流
    private void removedProcessRequest() {
        Set<String> cancelIdSet = new Set<String>();
        for (Consum_Apply__c nObj : newList) {
            Consum_Apply__c oObj = oldMap.get(nObj.Id);
            if (oObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Shen_Qing_Zhong.ordinal())   // '申请中'
                    && nObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Qu_Xiao.ordinal())    // '取消'
            ) {
                cancelIdSet.add(nObj.Id);
            }
        }

        if (cancelIdSet.size() > 0) {
            List<Approval.ProcessWorkitemRequest> requests = new List<Approval.ProcessWorkitemRequest> ();
            Map<ID,ProcessInstance> piMap = New Map<ID,ProcessInstance>([Select Id from ProcessInstance where TargetObjectId IN :cancelIdSet]);
            for(ProcessInstanceWorkItem wi : [Select Id from ProcessInstanceWorkItem where ProcessInstanceId IN :piMap.keySet()]){
                Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                req2.setAction('Removed');
                req2.setWorkitemId(wi.Id);
                requests.add(req2);
            }
            if (requests.size() > 0) {
                Approval.ProcessResult[] processResults = null;
                processResults = Approval.process(requests, true);
            }
        }
    }

    // 删除明细
    // private void  checkStatucDeleteDetail() {
    //     List<Consum_Apply__c> targetList = new List<Consum_Apply__c>();
    //     for (Consum_Apply__c nObj : newList) {
    //         Consum_Apply__c oObj = oldMap.get(nObj.Id);
    //         if ((nObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Qu_Xiao.ordinal())    // '取消'
    //                 || nObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Shan_Chu.ordinal())   // '删除'
    //             )
    //             && (oObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Cao_An_Zhong.ordinal())   // '草案中'
    //                 || oObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Tian_Xie_Wan_Bi.ordinal())   // '填写完毕'
    //                 || oObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Shen_Qing_Zhong.ordinal())   // '申请中'
    //             )
    //         ) {
    //             targetList.add(nObj);
    //         }
    //         else if ((nObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Cao_An_Zhong.ordinal())   // '草案中'
    //                 || nObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Bu_Pi_Zhun.ordinal())   // '不批准'
    //             )
    //             && oObj.Status__c == Consum_ApplyUtil.CaStatusMap.get(Consum_ApplyUtil.CaStatus.Shen_Qing_Zhong.ordinal())   // '申请中'
    //         ) {
    //             targetList.add(nObj);
    //         }
    //     }
    //     if (targetList.isEmpty()) {
    //         return;
    //     }
    //     List<Consum_Apply_Equipment_Set_Detail__c> toDeleteDtlList = ConsumApplyInventoryAutoDeleteBatch.getDeleteDetialList(
    //                 targetList, 0);
    //     FixtureUtil.withoutDelete(toDeleteDtlList);
    // }

    // 字符串转Hash
    public Static String getHash(String digest, String message) {
        if (String.isBlank(message)) {
            message = '';
        }
        return EncodingUtil.convertToHex(Crypto.generateDigest(digest, Blob.valueOf(message)));
    }
    private void setcalendarMap() {
        Set<Date> dSet = new Set<Date>();
        for (Consum_Apply__c nObj : newList) {
            Consum_Apply__c oObj;
            if (Trigger.isUpdate){
                oObj = oldMap.get(nObj.Id);
                // 为了出提醒信息 需要取得申请书作成日
                Date insertCreatedDate = Date.newinstance(nObj.CreatedDate.year(), nObj.CreatedDate.month(), nObj.CreatedDate.day());
                if (calendarMap.containsKey(insertCreatedDate) == false) {
                    dSet.add(insertCreatedDate);
                }
            }
            else{
                oObj = new Consum_Apply__c();
                // 为了出提醒信息 需要取得申请书作成日
                if (calendarMap.containsKey(Date.today()) == false) {
                    dSet.add(Date.today());
                }
            }
            if (oObj.Request_shipping_day__c != nObj.Request_shipping_day__c
                && nObj.Request_shipping_day__c != null
                && calendarMap.containsKey(nObj.Request_shipping_day__c) == false) {
                dSet.add(nObj.Request_shipping_day__c);
            }
        }
        if (dSet.size() > 0) {
            List<OlympusCalendar__c> cList = [SELECT Id
                , Date__c
                , IsWorkDay__c
                , After_1_WorkDay__c
                , After_2_WorkDay__c
                , After_3_WorkDay__c
                , After_4_WorkDay__c
                , After_5_WorkDay__c
                , After_6_WorkDay__c
                , After_7_WorkDay__c
                , After_8_WorkDay__c
                , After_9_WorkDay__c
                , After_10_WorkDay__c
                , After_11_WorkDay__c
                , After_12_WorkDay__c
                , After_13_WorkDay__c
                , After_14_WorkDay__c
                , After_15_WorkDay__c
                , After_16_WorkDay__c
                , After_17_WorkDay__c
                , After_18_WorkDay__c
                , After_19_WorkDay__c
                , After_20_WorkDay__c
                , After_21_WorkDay__c
                , After_22_WorkDay__c
                , After_23_WorkDay__c
                , After_24_WorkDay__c
                , After_25_WorkDay__c
                , After_26_WorkDay__c
                , After_27_WorkDay__c
                , After_28_WorkDay__c
                , After_29_WorkDay__c
                , After_30_WorkDay__c
                , Before_1_WorkDay__c
                , Before_2_WorkDay__c
                , Before_3_WorkDay__c
                , Before_4_WorkDay__c
                , Before_5_WorkDay__c
                , Before_6_WorkDay__c
                , Before_7_WorkDay__c
                , Before_8_WorkDay__c
                , Before_9_WorkDay__c
                , Before_10_WorkDay__c
                , Before_11_WorkDay__c
                , Before_12_WorkDay__c
                , Before_13_WorkDay__c
                , Before_14_WorkDay__c
                , Before_15_WorkDay__c
                , Before_16_WorkDay__c
                , Before_17_WorkDay__c
                , Before_18_WorkDay__c
                , Before_19_WorkDay__c
                , Before_20_WorkDay__c
                , Before_21_WorkDay__c
                , Before_22_WorkDay__c
                , Before_23_WorkDay__c
                , Before_24_WorkDay__c
                , Before_25_WorkDay__c
                , Before_26_WorkDay__c
                , Before_27_WorkDay__c
                , Before_28_WorkDay__c
                , Before_29_WorkDay__c
                , Before_30_WorkDay__c
             FROM OlympusCalendar__c
            WHERE Date__c = :dSet
            ];
            System.debug(dSet);
            System.debug(cList);
            for (OlympusCalendar__c calender: cList) {
                calendarMap.put(calender.Date__c, calender);
            }
        }
    }

    // 设置时间提醒字段
    // before insert/update only
    private void setDateRemind() {
        for (Consum_Apply__c nObj : newList) {
            nObj.ConsumApplyRemind_Text__c = System.Label.ConsumApplyRemind;
        // 因为改为显示固定提示信息 所以不需要动态计算日期了
        //    String dateRemindtext = System.Label.ConsumApplyRemind;

        //    Date applyCreatedDate;
        //    // update 时
        //    if (nObj.CreatedDate != null) {
        //        applyCreatedDate = nObj.CreatedDate.date();
        //    }
        //    // insert 时
        //    else {
        //        applyCreatedDate = Date.today();
        //    }
        //    Date twoDaysAfterCreate;
        //    if (calendarMap.containsKey(applyCreatedDate) && calendarMap.get(applyCreatedDate).After_2_WorkDay__c != null) {
        //        twoDaysAfterCreate = calendarMap.get(applyCreatedDate).After_2_WorkDay__c;
        //    }
        //    else {
        //        twoDaysAfterCreate = Consum_ApplyUtil.getWD_addday(applyCreatedDate, 2);
        //    }
        //    Integer twoDaysAfterCreateMonth = twoDaysAfterCreate.month();
        //    Integer twoDaysAfterCreateDay = twoDaysAfterCreate.day();

        //    String sevenDaysBeforeShipping = nObj.Request_Shipping_7days_Before__c == null ? 'null' : nObj.Request_Shipping_7days_Before__c.format();
        //    List<Object> parameters = new List<Object> {twoDaysAfterCreateMonth, twoDaysAfterCreateDay, sevenDaysBeforeShipping};
        //    String formatted = String.format(dateRemindtext, parameters);
        //    nObj.ConsumApplyRemind__c = formatted;
        }
    }
    @TestVisible private static void test() {
        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++;
    }
}