/**
 * @description       : 
 * @author            : ChangeMeIn@UserSettingsUnder.SFDoc
 * @group             : 
 * @last modified on  : 04-21-2022
 * @last modified by  : ChangeMeIn@UserSettingsUnder.SFDoc
**/
public without sharing class loanerAppTriggerHandler {
    /**
     * [changeFollowOpp description] 跟进询价改变时修改跟进询价(文本)
     * Date 2020/8/20
     */
    public static void changeFollowOpp(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
        // List<loaner_application__c> upList = new List<loaner_application__c>();
        // newList = [select id,Equipment_Type__c,Follow_Opp__c,Follow_Opp_text__c from loaner_application__c where id = 'a0Q0K00000JO2FfUAL'];
        List<String> idList = new List<String>();
        System.debug('newList'+newList);
        for(loaner_application__c la : newList){
            loaner_application__c oldla = oldMap.get(la.Id);
            if(la.Equipment_Type__c == 'BS' && la.Follow_Opp__c != oldla.Follow_Opp__c && la.Follow_Opp__c != null){
                idList.add(la.Follow_Opp__c);
            }
            if(la.Equipment_Type__c == 'BS' && la.Follow_Opp__c != oldla.Follow_Opp__c && la.Follow_Opp__c == null){
                la.Follow_Opp_text__c = null;
            }
        }

        if(idList.size() > 0){

            List<Opportunity> oppList = new List<Opportunity>();
            oppList = [select id,InquiryNumber__c from Opportunity where id in :idList];
            for(loaner_application__c la : newList){
                if(idList.contains(la.Follow_Opp__c)){
                    for(Opportunity opp : oppList){
                        if(opp.Id == la.Follow_Opp__c){
                            la.Follow_Opp_text__c = opp.InquiryNumber__c;
                        }
                    }
                }
            }
        }
    }

    public static void transferBack(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
        System.debug('newList' + newList);
        System.debug('oldList' + oldList);
        List<String> idList = new List<String>();
        for(loaner_application__c la : newList){
            loaner_application__c old = oldMap.get(la.Id);
            if(old.Status__c == '申请中' && la.Status__c == '草案中' && la.Equipment_Type__c == 'BS' && la.Loaner_LendOrder__c == true){
                idList.add(la.Id);
            }
        }
        System.debug(idList);
        if(idList.size() > 0){
            List<String> laIdList = new List<String>();
            List<Asset> pss = new List<Asset>();
            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
                                                        LOANER__r.RecordTypeId,LOANER__r.status,
                                                        loaner_application__r.Loaner_LendOrder__c
                                                From loaner_application_detail__c
                                                Where loaner_application__c in: idList];
            for(loaner_application_detail__c l2s : ps){
                Asset p2s = new Asset();
                p2s.Id =  l2s.LOANER__c;
                p2s.Status = '出借';
                pss.add(p2s);
                laIdList.add(l2s.LOANER__c);
            }
            if(pss.size() > 0 ) update pss;
            if(laIdList.size() > 0){
                List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where LOANER__c in : laIdList and (RAESD_Status__c = '申请者已收货' or RAESD_Status__c = '申请者已装机确认')];
                System.debug('^^^^^^^'+ladList);
                if(ladList.size() > 0){
                    for (loaner_application_detail__c lad : ladList ) {
                        lad.is_distribution__c = false;
                    }
                    System.debug('^^^^^^^'+ladList);
                    update(ladList);
                }
            }
        }
        List<String> idList2 = new List<String>();
        for(loaner_application__c la : newList){
            loaner_application__c old = oldMap.get(la.Id);
            if( la.Status__c == '申请中' && la.Equipment_Type__c == 'BS' && la.Loaner_LendOrder__c == true){
                idList2.add(la.Id);
            }
        }
        System.debug('!@#'+idList2);
        if(idList2.size() > 0){
            List<String> laIdList = new List<String>();
            List<Asset> pss = new List<Asset>();
            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
                                                        LOANER__r.RecordTypeId,LOANER__r.status,
                                                        loaner_application__r.Loaner_LendOrder__c
                                                From loaner_application_detail__c
                                                Where loaner_application__c in: idList2];
            for(loaner_application_detail__c l2s : ps){
                laIdList.add(l2s.LOANER__c);
            }
            //if(pss.size() > 0 ) update pss;
            if(laIdList.size() > 0){
                List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where LOANER__c in : laIdList and (RAESD_Status__c = '申请者已收货' or RAESD_Status__c = '申请者已装机确认')];
                System.debug('^^^^^^^'+ladList);
                if(ladList.size() > 0){
                    for (loaner_application_detail__c lad : ladList ) {
                        lad.is_distribution__c = true;
                    }
                    System.debug('^^^^^^^'+ladList);
                    update(ladList);
                }
            }
        }
    }

    public static String upsertAssetSubmit(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
    {
        List<String> p2ids = new List<String>();
        for (loaner_application__c local : newList) {
            loaner_application__c old = oldMap.get(local.Id);
            if ((old.Status__c != local.Status__c || (local.Equipment_Type__c == 'IE' && local.Approval_Step__c == 2)) && local.Status__c == '申请中') {
                p2ids.add(local.id);
            }
        }

        List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
                                                        LOANER__r.RecordTypeId,LOANER__r.status,
                                                        loaner_application__r.Loaner_LendOrder__c
                                                From loaner_application_detail__c
                                                Where loaner_application__c in: p2ids];
        List<Asset> pss = new List<Asset>();
        for(loaner_application_detail__c l2s : ps){
            if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 
                && l2s.loaner_application__r.Loaner_LendOrder__c == false){
                if (l2s.LOANER__r.status != '在库' )
                {
                    return '样机 ' + l2s.LOANER__r.Name + ' 目前状态是' + l2s.LOANER__r.status + ',请确认';
                }
                else{
                    Asset p2s = new Asset();
                    p2s.Id =  l2s.LOANER__c;
                    p2s.Status = '冻结';
                    pss.add(p2s);
                }
            }
            l2s.RAESD_Status__c = '申请中';
        }
        upsert(pss);
        upsert(ps);
        return '';
    }
    public static void upsertAssetApproval(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
    {
        List<String> p2ids = new List<String>();
        for (loaner_application__c local : newList) {
            loaner_application__c old = oldMap.get(local.Id);
            if (old.Status__c != local.Status__c && local.Status__c == '已批准') {
                p2ids.add(local.id);
            }
        }
         List<loaner_application_detail__c> ps = new List<loaner_application_detail__c>();
        if(p2ids.size() > 0){
            ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
                    LOANER__r.RecordTypeId,LOANER__r.status,
                    loaner_application__r.Loaner_LendOrder__c
                    From loaner_application_detail__c
                    Where loaner_application__c in: p2ids];
        
            //Map <String,Asset> psmap = new Map<String,Asset>();
            List<Asset> pss = new List<Asset>();
            for(loaner_application_detail__c l2s : ps){
                if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
                    if (l2s.LOANER__r.status == '在库' && l2s.loaner_application__r.Loaner_LendOrder__c == false){
                        Asset p2s = new Asset();
                        p2s.Id =  l2s.LOANER__c;
                        p2s.Status = '冻结';
                        pss.add(p2s);
                    }
                }
                l2s.RAESD_Status__c = '已批准';
            }
            if(pss.size()>0) upsert(pss);
            if(ps.size() >0) upsert(ps);
        }
    }

    public static void cancelLoanerApplication(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
    {
        List<String> p2ids = new List<String>();
        for (loaner_application__c local : newList) {
            loaner_application__c old = oldMap.get(local.Id);
            if (old.Status__c != local.Status__c && local.Status__c == '取消') {
                p2ids.add(local.id);
            }
        }
        if(p2ids.size() >0){
            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,Equipment_Type__c,
                                                            LOANER__r.RecordTypeId,LOANER__r.status,loaner_application__r.Loaner_LendOrder__c
                                                        From loaner_application_detail__c
                                                        Where loaner_application__c in: p2ids];
            List<Asset> pss = new List<Asset>();
            List<String> laIdList = new List<String>();
            for(loaner_application_detail__c l2s : ps){
                if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1){
                    if (l2s.LOANER__r.status != '在库' && l2s.loaner_application__r.Loaner_LendOrder__c == false){
                        Asset p2s = new Asset();
                        p2s.Id =  l2s.LOANER__c;
                        p2s.Status = '在库';
                        pss.add(p2s);
                    }else if(l2s.loaner_application__r.Loaner_LendOrder__c == true && l2s.Equipment_Type__c == 'BS'){
                        Asset p2s = new Asset();
                        p2s.Id =  l2s.LOANER__c;
                        p2s.Status = '出借';
                        pss.add(p2s);
                        laIdList.add(l2s.LOANER__c);
                    }
                }
                l2s.RAESD_Status__c = '取消';
                l2s.Cancel_Date__c  = Date.today();
                System.debug('@@@@@@@@@'+laIdList);
                if(laIdList.size() > 0){
                    List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where LOANER__c in : laIdList and (RAESD_Status__c = '申请者已收货' or RAESD_Status__c = '申请者已装机确认')];
                    System.debug('@@@@@@@@@@@'+ladList);
                    if(ladList.size() > 0){
                        for (loaner_application_detail__c lad : ladList ) {
                            lad.is_distribution__c = false;
                        }
                        System.debug('@@@@@@@@@@@'+ladList);
                        update(ladList);
                    }
                }
            }
            if(pss.size() > 0) upsert(pss);
            if(ps.size() > 0) upsert(ps);
        }
    }
    public static void upsertAssetCancle(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
    {
        List<String> p2ids = new List<String>();
        for (loaner_application__c local : newList) {
            loaner_application__c old = oldMap.get(local.Id);
            if (old.Status__c != local.Status__c && local.Status__c == '驳回') {
                p2ids.add(local.id);
            }
        }
        if(p2ids.size() > 0){
            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,
                                                            LOANER__r.RecordTypeId,LOANER__r.status,Equipment_Type__c,
                                                            loaner_application__r.Loaner_LendOrder__c 
                                                        From loaner_application_detail__c 
                                                        Where loaner_application__c in: p2ids];
            //Map <String,Asset> psmap = new Map<String,Asset>();
            List<Asset> pss = new List<Asset>();
            List<String> laIdList = new List<String>();
            for(loaner_application_detail__c l2s : ps){
                if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 
                    && l2s.loaner_application__r.Loaner_LendOrder__c == false){
                    Asset p2s = new Asset();
                    p2s.Id =  l2s.LOANER__c;
                    p2s.Status = '在库';
                    pss.add(p2s);
                }else if(String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 
                    && l2s.loaner_application__r.Loaner_LendOrder__c == true && l2s.Equipment_Type__c == 'BS'){
                    Asset p2s = new Asset();
                    p2s.Id = l2s.LOANER__c;
                    p2s.Status = '出借';
                    pss.add(p2s);
                    laIdList.add(l2s.LOANER__c);
                }
                l2s.RAESD_Status__c = '驳回';
                System.debug('#######'+laIdList);
                if(laIdList.size() > 0){
                    List<loaner_application_detail__c> ladList = [select id from loaner_application_detail__c where LOANER__c in : laIdList and (RAESD_Status__c = '申请者已收货' or RAESD_Status__c = '申请者已装机确认')];
                    System.debug('#######'+ladList);
                    if(ladList.size() > 0){
                        for (loaner_application_detail__c lad : ladList ) {
                            lad.is_distribution__c = false;
                        }
                        System.debug('#######'+ladList);
                        update(ladList);
                    }
                }
            }
            if(pss.size() > 0) upsert(pss);
            if(ps.size() > 0) upsert(ps);
        }
    }

    public static void upsertAssetcallback(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) 
    {
        List<String> p2ids = new List<String>();
        for (loaner_application__c local : newList) {
            loaner_application__c old = oldMap.get(local.Id);
            if ((old.Status__c != local.Status__c && old.Status__c == '申请中' && local.Status__c == '草案中') 
                || (old.Status__c == '申请中' && local.Status__c == '销售担当批准' && local.Equipment_Type__c == 'IE')) {
                p2ids.add(local.id);
            }
        }
        if(p2ids.size() >0 ){
            List<loaner_application_detail__c> ps = [select Id,Name,RAESD_Status__c,LOANER__c,LOANER__r.Name,LOANER__r.RecordTypeId,
                                                            LOANER__r.status,loaner_application__r.Loaner_LendOrder__c 
                                                            From loaner_application_detail__c 
                                                            Where loaner_application__c in: p2ids];
            //Map <String,Asset> psmap = new Map<String,Asset>();
            List<Asset> pss = new List<Asset>();
            for(loaner_application_detail__c l2s : ps){
                if (String.valueOf(l2s.LOANER__r.RecordTypeId).subString(0,15) == System.label.Asset_Record_Type1 && l2s.loaner_application__r.Loaner_LendOrder__c == false){
                    Asset p2s = new Asset();
                    p2s.Id =  l2s.LOANER__c;
                    p2s.Status = '在库';
                    pss.add(p2s);
                }
                l2s.RAESD_Status__c = '已分配';
            }
            if(pss.size() > 0) upsert(pss);
            if(ps.size() > 0) upsert(ps);
        }
    }
    //RVI样机管理员审批时，判断有没有填写借出开始日和借出结束日
    public static void rental_Datejudgment(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
        LoanerAppDetailTriggerHandler.runTrigger = false;
        List<String> p2ids = new List<String>();
        List<String> detids = new List<String>();
        Map<Id,loaner_application_detail__c> olddetsMap = new Map<Id,loaner_application_detail__c>();
        for (loaner_application__c local : newList) {
            loaner_application__c oldLA = oldMap.get(local.Id);
            if (local.RVI_Manager_Approval__c != oldLA.RVI_Manager_Approval__c && local.RVI_Manager_Approval__c == true && (local.Rental_Start_Date__c == null || local.Rental_End_Date__c == null)){
                local.addError('请输入借出开始日和借出结束日。');
            }
            if(local.Loaner_LendOrder__c == true && local.Detail_count__c  == 0 && (local.Status__c == '已批准' || local.Status__c == '销售担当批准')){
                local.addError('请先分配样机在审批通过');
            }
        }
        
    }
    public static void serviceApproval(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
        LoanerAppDetailTriggerHandler.runTrigger = false;
        for(loaner_application__c la : newList){
            loaner_application__c old = oldMap.get(la.Id);
            if(la.Service_Approval__c != old.Service_Approval__c && la.Service_Approval__c == true && la.Engineer_FW__c == null){
                la.addError('审批前请填写:工程师名称(服务).');
            }
            if(la.Product_Approval__c != old.Product_Approval__c && la.Product_Approval__c == true && la.Engineer_CP__c == null){
                la.addError('审批前请填写:工程师名称(产品).');
            }
        }

    }
    //转借批准后，状态改为 全部发货
    public static void GoToNextStatusHead(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
        LoanerAppDetailTriggerHandler.runTrigger = false;
        List<String> p2ids = new List<String>();
        List<String> detids = new List<String>();
        Map<Id,loaner_application_detail__c> olddetsMap = new Map<Id,loaner_application_detail__c>();
        for (loaner_application__c local : newList) {
            loaner_application__c oldLA = oldMap.get(local.Id);
            if (local.Status__c != oldLA.Status__c && local.Status__c == '申请中'){
                if((String.isBlank(local.Loaner_receive_staff__c)|| String.isBlank(local.direct_shippment_address__c)|| String.isBlank(local.Loaner_receive_staff_phone__c)|| 
                   String.isBlank(local.Post_Code__c)) && local.pickup_time__c == null){
                    local.addError('收货人信息或者自提时间请填写一项。');
                }
                if((!String.isBlank(local.Loaner_receive_staff__c)||!String.isBlank(local.direct_shippment_address__c)|| !String.isBlank(local.Loaner_receive_staff_phone__c)|| 
                   !String.isBlank(local.Post_Code__c)) && local.pickup_time__c != null){
                    local.addError('收货人信息或者自提时间请填写一项。');
                }
            }
        }
        for (loaner_application__c local : newList) {
            loaner_application__c oldLA = oldMap.get(local.Id);
            if (local.Status__c != oldLA.Status__c && local.Status__c == '已批准' && (local.Rental_Start_Date__c == null || local.Rental_End_Date__c == null)){
                local.addError('请输入借出开始日和借出结束日。');
            }
        }
        for (loaner_application__c local : newList) {
            loaner_application__c oldLA = oldMap.get(local.Id);
            if (local.Status__c != oldLA.Status__c && local.Status__c == '销售担当批准' && local.Detail_count__c == 0 && local.Approval_Step__c  == 1 && local.Equipment_Type__c  == 'IE'){
                local.addError('必须先做样机分配后再审批.');
            }
        }
    }


    public static void setSubmitUser(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
        for (loaner_application__c local : newList) {
            loaner_application__c old = oldMap.get(local.Id);
            Id submitUser = UserInfo.getUserId();
            if (old.Status__c != local.Status__c && (local.Status__c == '已提交' || local.Status__c == '申请中')
                && String.isBlank(local.ApplyPerson__c)) {
                local.ApplyPerson__c = submitUser;
            }
        }
    }

    public static void setApprover(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
        List<String> ApproverIdList = new List<String>();
        List<String> loaner_appList = new List<String>();
        List<String> productIDList = new List<String>();
        Map<String,String> loanerapplicationToApprover = new Map<String,String>();
        For (loaner_application__c newloanerapplication: newList) {
            loaner_application__c oldloanerapplication = oldMap.get(newloanerapplication.Id);
//            if (oldloanerapplication.Approver__c != newloanerapplication.Approver__c || Trigger.isInsert == true) {
                loaner_appList.add(newloanerapplication.Id);
                ApproverIdList.add(newloanerapplication.Approver__c);
                loanerapplicationToApprover.put(newloanerapplication.Id, newloanerapplication.Approver__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum1__c)) productIDList.add(newloanerapplication.ProductNameNum1__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum2__c)) productIDList.add(newloanerapplication.ProductNameNum2__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum3__c)) productIDList.add(newloanerapplication.ProductNameNum3__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum4__c)) productIDList.add(newloanerapplication.ProductNameNum4__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum5__c)) productIDList.add(newloanerapplication.ProductNameNum5__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum6__c)) productIDList.add(newloanerapplication.ProductNameNum6__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum7__c)) productIDList.add(newloanerapplication.ProductNameNum7__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum8__c)) productIDList.add(newloanerapplication.ProductNameNum8__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum9__c)) productIDList.add(newloanerapplication.ProductNameNum9__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum10__c)) productIDList.add(newloanerapplication.ProductNameNum10__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum11__c)) productIDList.add(newloanerapplication.ProductNameNum11__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum12__c)) productIDList.add(newloanerapplication.ProductNameNum12__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum13__c)) productIDList.add(newloanerapplication.ProductNameNum13__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum14__c)) productIDList.add(newloanerapplication.ProductNameNum14__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum15__c)) productIDList.add(newloanerapplication.ProductNameNum15__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum16__c)) productIDList.add(newloanerapplication.ProductNameNum16__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum17__c)) productIDList.add(newloanerapplication.ProductNameNum17__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum18__c)) productIDList.add(newloanerapplication.ProductNameNum18__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum19__c)) productIDList.add(newloanerapplication.ProductNameNum19__c);
                if(String.isNotBlank(newloanerapplication.ProductNameNum20__c)) productIDList.add(newloanerapplication.ProductNameNum20__c);
//            }
        }
        Map<Id, Product2> copyProductMap = new Map<Id, Product2>([
            SELECT Id, Product_ECCode__c
            FROM Product2
            WHERE Id IN :productIDList
        ]);
        Map<Id, User> copyUserMap = new Map<Id, User>([
            SELECT Id, Name, SalesAsistManager__c, BusinessDepOwner_Tax__c,BusinessDepOwner_WithoutTax__c, 
                SalesManager__c, AsistGenManger__c,CRM_Owner__c 
            FROM User 
            WHERE Id IN :ApproverIdList
        ]);
        Map<Id, loaner_application__c> loaner_appMap = new Map<Id, loaner_application__c>([
            select id,name,CreatorUserType__c,CreatedBy.Contact.AccountId__c,AccountId__c,ProductNameNum1__c,
                   ProductNameNum2__c,ProductNameNum3__c,ProductNameNum4__c,ProductNameNum5__c,
                   ProductNameNum6__c,ProductNameNum7__c,ProductNameNum8__c,ProductNameNum9__c,
                   ProductNameNum10__c,ProductNameNum11__c,ProductNameNum12__c,ProductNameNum13__c,
                   ProductNameNum14__c,ProductNameNum15__c,ProductNameNum16__c,ProductNameNum17__c,
                   ProductNameNum18__c,ProductNameNum19__c,ProductNameNum20__c
              from  loaner_application__c WHERE Id IN :loaner_appList
        ]);

        for (loaner_application__c newloanerapplication: newList){
            loaner_application__c oldloanerapplication = loaner_appMap.get(newloanerapplication.Id);
            newloanerapplication.EC_Code_1__c = '';
            newloanerapplication.EC_Code_2__c = '';
            newloanerapplication.EC_Code_3__c = '';
            newloanerapplication.EC_Code_4__c = '';
            newloanerapplication.EC_Code_5__c = '';
            newloanerapplication.EC_Code_6__c = '';
            newloanerapplication.EC_Code_7__c = '';
            newloanerapplication.EC_Code_8__c = '';
            newloanerapplication.EC_Code_9__c = '';
            newloanerapplication.EC_Code_10__c = '';
            newloanerapplication.EC_Code_11__c = '';
            newloanerapplication.EC_Code_12__c = '';
            newloanerapplication.EC_Code_13__c = '';
            newloanerapplication.EC_Code_14__c = '';
            newloanerapplication.EC_Code_15__c = '';
            newloanerapplication.EC_Code_16__c = '';
            newloanerapplication.EC_Code_17__c = '';
            newloanerapplication.EC_Code_18__c = '';
            newloanerapplication.EC_Code_19__c = '';
            newloanerapplication.EC_Code_20__c = '';

            if(String.isNotBlank(newloanerapplication.ProductNameNum1__c)) newloanerapplication.EC_Code_1__c = copyProductMap.get(newloanerapplication.ProductNameNum1__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum2__c)) newloanerapplication.EC_Code_2__c = copyProductMap.get(newloanerapplication.ProductNameNum2__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum3__c)) newloanerapplication.EC_Code_3__c = copyProductMap.get(newloanerapplication.ProductNameNum3__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum4__c)) newloanerapplication.EC_Code_4__c = copyProductMap.get(newloanerapplication.ProductNameNum4__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum5__c)) newloanerapplication.EC_Code_5__c = copyProductMap.get(newloanerapplication.ProductNameNum5__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum6__c)) newloanerapplication.EC_Code_6__c = copyProductMap.get(newloanerapplication.ProductNameNum6__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum7__c)) newloanerapplication.EC_Code_7__c = copyProductMap.get(newloanerapplication.ProductNameNum7__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum8__c)) newloanerapplication.EC_Code_8__c = copyProductMap.get(newloanerapplication.ProductNameNum8__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum9__c)) newloanerapplication.EC_Code_9__c = copyProductMap.get(newloanerapplication.ProductNameNum9__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum10__c)) newloanerapplication.EC_Code_10__c = copyProductMap.get(newloanerapplication.ProductNameNum10__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum11__c)) newloanerapplication.EC_Code_11__c = copyProductMap.get(newloanerapplication.ProductNameNum11__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum12__c)) newloanerapplication.EC_Code_12__c = copyProductMap.get(newloanerapplication.ProductNameNum12__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum13__c)) newloanerapplication.EC_Code_13__c = copyProductMap.get(newloanerapplication.ProductNameNum13__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum14__c)) newloanerapplication.EC_Code_14__c = copyProductMap.get(newloanerapplication.ProductNameNum14__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum15__c)) newloanerapplication.EC_Code_15__c = copyProductMap.get(newloanerapplication.ProductNameNum15__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum16__c)) newloanerapplication.EC_Code_16__c = copyProductMap.get(newloanerapplication.ProductNameNum16__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum17__c)) newloanerapplication.EC_Code_17__c = copyProductMap.get(newloanerapplication.ProductNameNum17__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum18__c)) newloanerapplication.EC_Code_18__c = copyProductMap.get(newloanerapplication.ProductNameNum18__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum19__c)) newloanerapplication.EC_Code_19__c = copyProductMap.get(newloanerapplication.ProductNameNum19__c).Product_ECCode__c;
            if(String.isNotBlank(newloanerapplication.ProductNameNum20__c)) newloanerapplication.EC_Code_20__c = copyProductMap.get(newloanerapplication.ProductNameNum20__c).Product_ECCode__c;
            if (oldloanerapplication.CreatorUserType__c == 'PowerPartner' ) {
                newloanerapplication.Agent__c = oldloanerapplication.AccountId__c;
            }
        }

        for (loaner_application__c newloanerapplication: newList){
            loaner_application__c oldloanerapplication = oldMap.get(newloanerapplication.Id);
                User u = copyUserMap.get(loanerapplicationToApprover.get(newloanerapplication.Id));
                if (u != null && (u.SalesAsistManager__c != null || u.BusinessDepOwner_Tax__c != null || u.BusinessDepOwner_WithoutTax__c != null || u.SalesManager__c != null || u.AsistGenManger__c != null)) {
                    newloanerapplication.DeputyApproveManager__c = u.SalesAsistManager__c == null ? u.Id : u.SalesAsistManager__c;
                    newloanerapplication.ApproveManager__c = u.SalesManager__c == null ? u.Id : u.SalesManager__c;
                }
                if(newloanerapplication.Equipment_Type__c == 'IE' &&  newloanerapplication.loaner_place__c == '上海OSH'){
                    newloanerapplication.loaner_Manager__c = System.label.IE_SH;
                }
                if(newloanerapplication.Equipment_Type__c == 'IE' && newloanerapplication.loaner_place__c == '上海嘉华'){
                     newloanerapplication.loaner_Manager__c = System.label.IE_SHJH;
                }
                if(newloanerapplication.Equipment_Type__c == 'IE' && newloanerapplication.loaner_place__c == '广州办'){
                    newloanerapplication.loaner_Manager__c = System.label.IE_GZB;
                }
                if(newloanerapplication.Equipment_Type__c == 'IE' && newloanerapplication.loaner_place__c == '北京酒仙桥'){
                    newloanerapplication.loaner_Manager__c = System.label.IE_BJ;
                }
                if(newloanerapplication.Equipment_Type__c == 'IE' && newloanerapplication.loaner_place__c == '上海明园'){
                    newloanerapplication.loaner_Manager__c = System.label.IE_SHMY;
                }

                if(newloanerapplication.Equipment_Type__c == 'RVI'){
                    newloanerapplication.loaner_Manager__c = System.label.RVI_Manager;
                }
                if(newloanerapplication.Equipment_Type__c == 'BS' && newloanerapplication.loaner_place__c == '北京酒仙桥'){
                     newloanerapplication.loaner_Manager__c = System.label.BS_JXQ;
                }
                if(newloanerapplication.Equipment_Type__c == 'BS' && newloanerapplication.loaner_place__c == '广州办'){
                    newloanerapplication.loaner_Manager__c = System.label.BS_GZB;
                }
//            }
        }
    }

    public static void BackToPreStatus(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
        if(oldMap == null){
            return;
        }
        for (loaner_application__c newLA : newList) {
            if(newLA == null){
                break;
            }
            loaner_application__c oldLA = oldMap.get(newLA.Id);
            // String profileId = UserInfo.getProfileId();
            if (newLA.BackToPreStatus__c != oldLA.BackToPreStatus__c && newLA.BackToPreStatus__c == true){
                newLA.Status__c = newLA.BeforeSubmitStatus__c;
                newLA.BackToPreStatus__c = false;
            }
        }
        Map<String,Date> dateRangeMap = new Map<String,Date>();

        for (loaner_application__c local : newList) {
            loaner_application__c old = oldMap.get(local.Id);
            if (old.Status__c != local.Status__c && local.Status__c == '申请中') {
                if(local.Request_shipping_Date__c!= null){
                    if(!dateRangeMap.containsKey('BigDate')){
                        dateRangeMap.put('BigDate', local.Request_shipping_Date__c);
                    }else if(local.Request_shipping_Date__c > dateRangeMap.get('BigDate')){
                        dateRangeMap.put('BigDate', local.Request_shipping_Date__c);
                    }

                    if(!dateRangeMap.containsKey('SmaDate')){
                        dateRangeMap.put('SmaDate', local.Request_shipping_Date__c);
                    }else if(local.Request_shipping_Date__c < dateRangeMap.get('SmaDate')){
                        dateRangeMap.put('SmaDate', local.Request_shipping_Date__c);
                    }
                }
            }
        }
        if(dateRangeMap.size()>0){
            Map<String,OlympusCalendar__c> olyCalendarMap = calendarUtil.getCalendarMap(dateRangeMap.get('SmaDate').addDays(-15),dateRangeMap.get('BigDate').addDays(1));

            for (loaner_application__c local : newList) {
                if(local.Request_shipping_Date__c != null){
                    local.Remind_Date__c = calendarUtil.getCorrespondingDate(olyCalendarMap,local.Request_shipping_Date__c,-3);
                }
            }
        }

        
    }


    public static void setRemind_Date(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap) {
        Map<String,Date> dateRangeMap = new Map<String,Date>();

        for (loaner_application__c local : newList) {
            //if (local.CreatorUserType__c == 'Standard' ) {
                if(local.Request_shipping_Date__c!= null ){
                    System.debug('Request_shipping_Date__c:'+local.Request_shipping_Date__c);
                    if(!dateRangeMap.containsKey('BigDate')){
                        dateRangeMap.put('BigDate', local.Request_shipping_Date__c);
                    }else if(local.Request_shipping_Date__c > dateRangeMap.get('BigDate')){
                        dateRangeMap.put('BigDate', local.Request_shipping_Date__c);
                    }

                    if(!dateRangeMap.containsKey('SmaDate')){
                        dateRangeMap.put('SmaDate', local.Request_shipping_Date__c);
                    }else if(local.Request_shipping_Date__c < dateRangeMap.get('SmaDate')){
                        dateRangeMap.put('SmaDate', local.Request_shipping_Date__c);
                    }   
                }
            //}
            System.debug('dateRangeMap:'+dateRangeMap);
        }
        if(dateRangeMap.size()>0){
            System.debug(dateRangeMap.get('SmaDate'));
            System.debug(dateRangeMap.get('BigDate'));
            Map<String,OlympusCalendar__c> olyCalendarMap = calendarUtil.getCalendarMap(dateRangeMap.get('SmaDate').addDays(-40),dateRangeMap.get('BigDate').addDays(15));
            System.debug(olyCalendarMap);
            for (loaner_application__c local : newList) {
                if(local.Request_shipping_Date__c != null){
                    local.Remind_Date__c = calendarUtil.getCorrespondingDate(olyCalendarMap,local.Request_shipping_Date__c,-3);
                }
            }
        }
    }


    public static void emailDate(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
        List<String> remindId = new List<String>();
        for(loaner_application__c la : newList){
            loaner_application__c old = oldMap.get(la.id);
            if(la.Rental_End_Date__c != old.Rental_End_Date__c){
                remindId.add(la.id);
            }
        }
        Map<String,OlympusCalendar__c> oCalendar = calendarUtil.getCalendarMap(Date.today().addDays(-240),Date.today().addDays(240));
        List<loaner_application__c> remindList = new List<loaner_application__c>();
        if(remindId.size()>0){
            remindList = [select id,Rental_End_Date__c,Equipment_Type__c from loaner_application__c where id= :remindId];
            for(loaner_application__c remind : remindList){
                if(remind.Equipment_Type__c == 'NDT' || remind.Equipment_Type__c == 'ANI'){
                    remind.Remind_Request_Date__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Rental_End_Date__c,-1);
                    remind.First_timeOut__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Rental_End_Date__c,2);
                    remind.Second_timeOut__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Rental_End_Date__c,4);

                }else{
                    remind.Remind_Request_Date__c = calendarUtil.getCorrespondingDate(oCalendar,remind.Rental_End_Date__c,-3);
                }
            }
        }
        if(remindList.size()>0) update remindList;
    }

   /* public static void unlock(List<loaner_application__c> newList, Map<Id, loaner_application__c> newMap, List<loaner_application__c> oldList, Map<Id, loaner_application__c> oldMap){
        List<String> laIdList = new List<String>();

        for(loaner_application__c la : newList){
            loaner_application__c old = oldMap.get(la.Id);
            if(la.Status__c != old.Status__c && la.Status__c == '全部回收' 
                && (la.Equipment_Type__c == 'NDT' || la.Equipment_Type__c == 'ANI') 
                && la.Is_time_out__c){
                laIdList.add(la.Id);
            }
        }

        if(laIdList.size() == 0){
            return;
        }
        //
        List<String> userIdList = new List<String>();
        List<User_Violations__c> uvList = [SELECT Id,Violations_User__c FROM User_Violations__c WHERE Violations_Loaner__c IN :laIdList];

        if(uvList != null && uvList.size() > 0){
            for(User_Violations__c uv : uvList){
                uv.Is_effective__c = false;
                uv.Is_locking__c = false;
                uv.is_Alone__c = true;
                userIdList.add(uv.Violations_User__c);
            }
        }

        List<User_Violations__c> uv1List = [select id,Violations_User__c,Is_locking__c from User_Violations__c where Is_effective__c = true order by Violations_User__c];
        Map<String,Integer> userMap = new Map<String,Integer>();
        Map<String,String> user_vMap = new Map<String,String>();
        for(User_Violations__c uv : uv1List){
            if(userMap.containsKey(uv.Violations_User__c)){
                userMap.put(uv.Violations_User__c, userMap.get(uv.Violations_User__c)+1);
            }else{
                userMap.put(uv.Violations_User__c, 1);
            }
            if(uv.Is_locking__c = true){
                user_vMap.put(uv.Violations_User__c,uv.Id);
            }
        }


    }*/
   

}