public without sharing class UserFaultInfoHandler {

    public static void UserFaultInfoWorkingHoursAssignment(List<User_FaultInfo__c> newList, Map<Id, User_FaultInfo__c> newMap, List<User_FaultInfo__c> oldList, Map<Id, User_FaultInfo__c> oldMap, String type) {
        // 获取用户/故障信息下的业务活动
        List<String> selectUserFaultInfoIdList = new List<String>();
        for (User_FaultInfo__c uf : newList) {
            selectUserFaultInfoIdList.add(uf.Id);
        }

        // 查找用户故障信息下所有的业务活动
        List<BusinessActivity__c> businessActivityList = TSRepairUtil.GetBusinessActivityList(null, selectUserFaultInfoIdList, null, null, null, '');
        // 用户/故障信息 根据 审批意见 类型与 工时组成的Map
        Map<String, Decimal> OpinionMap = new Map<String, Decimal>();
        // 用户/故障信息 Id与工时组成的Map
        Map<String, Map<String, Decimal>> WorkingHourMap = new Map<String, Map<String, Decimal>>();
        if (businessActivityList != null && businessActivityList.size() > 0) {

            for (BusinessActivity__c getba : businessActivityList) {

                String ufId =  getba.User_FaultInfo__c;
                String opinion = getba.BusinessAApprovalOpinion__c;
                Decimal workingHours = 0;
                Map<String, Decimal> ufOpinionMap = new Map<String, Decimal>();

                if (WorkingHourMap.containsKey(ufId)) {

                    ufOpinionMap = WorkingHourMap.get(ufId);

                    if (ufOpinionMap.containsKey(opinion)) {

                        workingHours = ufOpinionMap.get(opinion);
                        workingHours += getba.workingHours__c;
                        ufOpinionMap.put(opinion, workingHours);
                    } else {

                        workingHours += getba.workingHours__c;
                        ufOpinionMap.put(opinion, workingHours);
                    }
                } else {

                    workingHours += getba.workingHours__c;
                    ufOpinionMap.put(opinion, workingHours);
                }
                WorkingHourMap.put(ufId, ufOpinionMap);

            }
            List<User_FaultInfo__c> updateUserFaultInfoList = new List<User_FaultInfo__c>();

            for (User_FaultInfo__c uf : newList) {

                for (String ufId : WorkingHourMap.keySet() ) {

                    if (uf.Id.equals(ufId)) {

                        Map<String, Decimal> ufOpinionMap = WorkingHourMap.get(ufId);
                        uf.UserFaultInfoWorkingHours__c = 0;
                        uf.UserFaultInfoUnconfirmedTime__c = 0;

                        for (String opinion : ufOpinionMap.keySet()) {
                            if ('同意'.equals(opinion)) {
                                uf.UserFaultInfoWorkingHours__c = ufOpinionMap.get(opinion);
                            } else {
                                uf.UserFaultInfoUnconfirmedTime__c = ufOpinionMap.get(opinion);
                            }
                        }
                    }

                }

                if ('insert'.equals(type)) {
                    updateUserFaultInfoList.add(uf);
                }
            }

            if (updateUserFaultInfoList.size() > 0) {
                update updateUserFaultInfoList;
            }


        }

    }

    public static void BeforeSendEmail(List<User_FaultInfo__c> newList, Map<Id, User_FaultInfo__c> newMap, List<User_FaultInfo__c> oldList, Map<Id, User_FaultInfo__c> oldMap) {
        for (User_FaultInfo__c newUf : newList) {
            newUf.IsSendEmail__c = true;
        }

    }

    // Case 上 ASSIGNED TO 变更 发送邮件
    public static void ASSIGNEDTOChange(List<User_FaultInfo__c> newList, Map<Id, User_FaultInfo__c> newMap, List<User_FaultInfo__c> oldList, Map<Id, User_FaultInfo__c> oldMap) {
        List<User_FaultInfo__Share> insertShareList = new List<User_FaultInfo__Share>();
        List<String> deleteShareList = new List<String>();

        for (User_FaultInfo__c newUf : newList) {

            Boolean beforUpdate = false;
            Boolean isSendEmail = false;

            Boolean afterInsert = false;
            Boolean changeASSIGNED_TO = false;
            Boolean changeCONTACT = false;

            if (Trigger.isBefore && Trigger.isUpdate) {
                isSendEmail = true;
                User_FaultInfo__c oldUf = oldMap.get(newUf.Id);
                // ASSIGNED TO 变更时发送邮件
                if (String.isNotBlank(newUf.ASSIGNED_TO__c) && oldUf.ASSIGNED_TO__c != newUf.ASSIGNED_TO__c) {
                    //变更时发送邮件
                    beforUpdate = true;
                    changeASSIGNED_TO = true;
                    insertShareList.add(ShareToUser(newUf.Id, newUf.ASSIGNED_TO__c));
                    deleteShareList.add(newUf.Id);
                }
                // CONTACT 变更时发送邮件
                if (String.isNotBlank(newUf.CONTACT__c) && oldUf.CONTACT__c != newUf.CONTACT__c) {
                    beforUpdate = true;
                    changeCONTACT = true;
                }

                if (oldUf.INTERNAL_ONLY__c != newUf.INTERNAL_ONLY__c && newUf.INTERNAL_ONLY__c) {
                    beforUpdate = true;
                    changeASSIGNED_TO = true;
                }

                if (oldUf.SEND_TO_CUSTOMER__c != newUf.SEND_TO_CUSTOMER__c && newUf.SEND_TO_CUSTOMER__c) {
                    beforUpdate = true;
                    changeCONTACT = true;
                }
            } else if (Trigger.isAfter && Trigger.isInsert) {
                if (String.isNotBlank(newUf.ASSIGNED_TO__c)) {
                    insertShareList.add(ShareToUser(newUf.Id, newUf.ASSIGNED_TO__c));
                    //新增时发送邮件
                    afterInsert = true;

                }
            }


            String userId = '';
            String contactId = '';
            String subjectStr = '';
            String messageStr = newUf.Interactions__c  == null ? '' : newUf.Interactions__c + '\n';
            messageStr += 'Case Details Link:\n';
            messageStr += System.Label.EnvironmentLink + newUf.Id;

            if (newUf.INTERNAL_ONLY__c || changeASSIGNED_TO) {
                userId = newUf.ASSIGNED_TO__c;
            }

            if (newUf.SEND_TO_CUSTOMER__c || changeCONTACT) {
                contactId =  newUf.CONTACT__c;
            }
            if (newUf.Interactions__c != null) {

                if (afterInsert) {

                } else {
                    newUf.interactionsHistory__c =  interactionsHistory(newUf);
                    newUf.Interactions__c = null;
                    beforUpdate = true;
                    if (newUf.IsSendEmail__c) {
                        beforUpdate = false;
                        newUf.IsSendEmail__c = false;
                    }

                }
            } else {
                if (isSendEmail) {
                    if (newUf.IsSendEmail__c) {
                        newUf.IsSendEmail__c = false;
                    }
                }

            }
            if (beforUpdate) {
                subjectStr = 'You have connected a new case, please follow up in time.';
                SendEmail(userId, contactId, newUf.Id, subjectStr, messageStr, 'update');

            }
            if (afterInsert) {
                subjectStr = 'A case has been created, please follow up in time.';
                SendEmail(userId, contactId , newUf.Id, subjectStr, messageStr, 'insert');
            }
        }
        // 删除数据共享
        if (deleteShareList.size() > 0) {
            String rowCause = Schema.User_FaultInfo__Share.RowCause.shareToUser__c;
            List<User_FaultInfo__Share> deleteList = [SELECT Id FROM User_FaultInfo__Share WHERE RowCause = :rowCause AND ParentId IN :deleteShareList];
            if (deleteList.size() > 0) {
                delete deleteList;
            }
        }
        // 新增数据共享
        if (insertShareList.size() > 0) {
            insert insertShareList;
        }
    }

    public static void SendEmail(String userId, String contactId, String ufId, String subjectStr, String messageStr, String type) {
        User_FaultInfo__c getCase = [ SELECT Id, Name, NUMBER__c, SUBJECT__c, COMPANY__r.Name FROM User_FaultInfo__c WHERE Id = :ufId];
        String caseName =  getCase.Name;
        // 保存之后要拼接 Case 的Name
        if ('insert'.equals(type)) {
            caseName = getCase.NUMBER__c + '-' + getCase.SUBJECT__c + '-' + getCase.COMPANY__r.Name;
            if (caseName.length() > 80) {
                caseName = caseName.substring(0, 80);
            }

        }

        List<String> toAddresses = new List<String>();
        if (String.isNotBlank(userId)) {
            User user = [select Name, Email from User where id = :userId limit 1];
            if (user != null && String.isNotBlank(user.Email)) {
                toAddresses.add(user.Email);
            }
        }

        if (String.isNotBlank(contactId)) {
            List<Contact> contactList = [SELECT Id, Name, AccountId__c, EmailD__c FROM Contact WHERE Id = :contactId limit 1];
            if (contactList.size() > 0 && String.isNotBlank(contactList[0].EmailD__c)) {
                toAddresses.add(contactList[0].EmailD__c);
            }
        }

        if (toAddresses.size() > 0) {

            String subject = subjectStr + ' ~Case:' + caseName;
            String message = messageStr;
            List<String> ccAddresses = new List<String>();
            Messaging.SingleEmailMessage sendMail = new Messaging.SingleEmailMessage();
            sendMail.setToAddresses(toAddresses);
            sendMail.setSubject(subject);
            sendMail.setPlainTextBody(message);
            sendMail.setBccSender(false);
            sendMail.setUseSignature(false);
            ccAddresses.add(System.label.EmailComeBackListen);
            ccAddresses.add('Dai_Prectech@olympus.com.cn');
            // ccAddresses.add('xinhonglu@prec-tech.com');
            ccAddresses.add('Xin_Prectech@olympus.com.cn');

            sendMail.setCcAddresses(ccAddresses);
            Messaging.SendEmailResult[] result_list = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { sendMail });
        }
    }
    /*
    parentId:数据Id
    userOrGroupId：待分享的用户Id
    创建数据共享
     */
    public static User_FaultInfo__Share ShareToUser (String parentId, String userOrGroupId) {
        String rowCause = Schema.User_FaultInfo__Share.RowCause.shareToUser__c;
        User_FaultInfo__Share apexShare = new User_FaultInfo__Share(
            RowCause = rowCause,
            ParentId = parentId,
            UserOrGroupId = userOrGroupId,
            AccessLevel = 'Edit');
        return apexShare;
    }
    public static String interactionsHistory(User_FaultInfo__c uf) {
        // 送信者
        String username = UserInfo.getName();
        // 发送时间
        Datetime dt = Datetime.now();

        // 现留言
        String temp = '';
        temp += '****** ' + username + ' ' + dt.format() + ' ******\n';
        temp += uf.Interactions__c;
        String oldResponse =  uf.interactionsHistory__c;
        if (oldResponse != null && oldResponse.trim().length() > 0) {
            temp += '\n\n' + oldResponse;
        }
        // uf.Interactions__c = null;
        // uf.interactionsHistory__c = temp;
        return temp;
    }

}