public without sharing class TSRepairController {

    // 基础Url
    public String baseUrl { get; private set; }
    // 日报ID
    public String repairId {get; set;}
    public TS_Repair__c tsr {get; set;}

    public String datestr;

    public Integer num {get; set{ num = value;}} //添加产品时使用
    public String baIds {get; set{ baIds = value;}} //添加附件时使用

    public Integer BusinessActivitySize {get; set;}

    public String serviceCategoryJSON {get; set;}


    public Date OriginalDate { get; set; }//修改日期查找日报时，错误还原

    public List<Attachment> attachments { get; set; }  //附件

    //页面显示内容
    public List<RepairInfo> RepairInfoList {get; set;}

    public String temp {get; set;}
    // Label
    public Integer initFailureAssetListSize;    //TS日报页面故障机器初始化数量
    public Integer maxFailureAssetListSize;     //TS日报页面故障机器展示最大数量
    public Integer initBusinessActivityListSize;//TS日报页面故业务活动初始化数量

    public User use {get; set;}//用户
    //public List<BusinessActivity__c> activityInItList;
    public Map<String, String> activityInItMap;
    //public Map<String, String> activityInItMap1;

    public String fromUserFaultInfoId {get; set;}
    public String lineno {get; set;}

    public String saveSign;

    public Boolean errorFlag { get; set; }
    public Map<String, List<String>> errorMessageMap;

    public Map<String, List<BusinessActivity__c>> businessActivityListToMap;

    //  王鹏伟定义变量开始
    // 前台点击按钮修改状态
    public String status {get; set;}
    // 前台是否可以点击按钮
    //onclickType=0时只能点击草案，申请；onclickType=1时只能点击驳回，批准
    public String onclickType {get; set;} //onclickType=0时
    //  王鹏伟定义变量结束

    public TSRepairController() {
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0, path.indexOf('/apex'));
        }
        errorFlag = false;
        repairId = System.currentPageReference().getParameters().get('id');
        datestr =  System.currentPageReference().getParameters().get('date');
    }

    public TSRepairController(ApexPages.StandardController stdController) {

        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0, path.indexOf('/apex'));
        }
        errorFlag = false;
        repairId = ApexPages.currentPage().getParameters().get('Id');
        datestr =  System.currentPageReference().getParameters().get('date');

    }

    public PageReference init() {
        errorMessageMap  = new Map<String, List<String>>();
        businessActivityListToMap = new Map<String, List<BusinessActivity__c>>();
        initFailureAssetListSize = Integer.valueOf(System.label.TSRepairPageInitFailureAssetListSize);
        maxFailureAssetListSize = Integer.valueOf(System.label.TSRepairPageMaxFailureAssetListSize);
        initBusinessActivityListSize = Integer.valueOf(System.label.TSRepairPageInitBusinessActivityListSize);
        serviceCategoryJSON = JSON.serialize(TSRepairUtil.GetserviceCategoryMap());
        activityInItMap = new Map<String, String>();

        temp = '0';
        BusinessActivitySize = 0;
        RepairInfoList = new List<RepairInfo>();
        // 王鹏伟 控制前台日报状态按钮
        onclickType = '0';
        List<String> selectUserIdList = new List<String>();
        String userId = UserInfo.getUserId();
        selectUserIdList.add(userId);
        use = TSRepairUtil.GetUserList(selectUserIdList)[0];
        String saveflg = ApexPages.currentPage().getParameters().get('save');
        if (String.isNotBlank(saveflg)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, initPagePrompt(saveflg)));
        }
        if (repairId != null && repairId != '') {

            GetInfoData(repairId, null);
            // TS日报创建人 与 当前用户的对比
            if (tsr.CreatedById != UserInfo.getUserId()) {
                temp = '1';

                onclickType = '-1';
                // TS日报的上级 与 当前用户的对比
                if (tsr.TSRepairSuperior__c == UserInfo.getUserId()) {
                    onclickType = '1';
                }
            }
            if (tsr.CreatedDate != Date.today() && tsr.TSReportStatus__c != '草案中' && tsr.TSReportStatus__c != '驳回') {
                temp = '1';
            }
            if (tsr.TSReportStatus__c == '确认') {
                onclickType = '-1';
            }
        } else {

            if (String.isBlank(datestr)) {
                FindTSRepair();
                if (String.isBlank(repairId)) {
                    GetInfoData('', null);
                } else {
                    return UnabletoEdit('2');
                }

            } else {
                String dateTransform = datestr.split(' ')[0].replaceall('-', '');
                Date updateDate = NFMUtil.parseStr2Date(dateTransform, false);//2020-09-26 00:00:00
                GetInfoData('', updateDate);
            }

        }

        return null;
    }

    public String initPagePrompt(String saveflg) {
        String result = '';
        if (saveflg == '1') {
            result = '服务日报保存成功';
        } else if (saveflg == 'Submit') {
            result = '服务日报提交成功';
        } else if (saveflg == 'Draft') {
            result = '服务日报调回成功';
        } else if (saveflg == 'Approval') {
            result = '服务日报确认成功';
        } else if (saveflg == 'Rejected') {
            result = '服务日报驳回成功';
        } else if (saveflg == '2') {
            result = '服务日报刷新成功';
        }

        return result;
    }

    public PageReference save() {

        errorMessageMap = new Map<String, List<String>>();
        List<BusinessActivity__c> businessActivityList = new List<BusinessActivity__c>();
        Map<Integer, User_FaultInfo__c> userFaultInfoMap = new Map<Integer, User_FaultInfo__c>();
        Map<Integer, List<FailureAsset__c>> failureAssetMap = new Map<Integer, List<FailureAsset__c>>();
        List<String> deleteBusinessActivityIdList = new List<String>();//删除业务活动
        // 业务活动信息是否正确
        if (!AuthenticationInformationSave(RepairInfoList)) {
            return null;
        }

        Savepoint sp = Database.setSavepoint();
        try {
            Boolean tSReportStatusIsApplyFor = false;
            if (String.isBlank(repairId)) {
                repairId = TSRepairAssembled(tsr);//TS日报保存
                if (String.isBlank(repairId)) {
                    return null;
                }
            } else {
                //查找TS日报的状态
                List<TS_Repair__c> tSRepairList = TSRepairUtil.GetTsRepairList(repairId, '', null , null, null, '');
                if (tSRepairList.size() > 0 ) {
                    tSReportStatusIsApplyFor = tSRepairList[0].TSReportStatus__c == '申请中' ? true : false;
                }
                upsert tsr;
                repairId = tsr.Id;
            }

            if ( tSReportStatusIsApplyFor && (tsr.TSReportStatus__c == '驳回' ||
                                              tsr.TSReportStatus__c == '草案中') ) {
                TSRepairStatus();
                return null;

            }


            // 业务活动 解除与 案件的关系
            RepairInfoList = BusinessActivityAndUser_FaultInfoDissociated(RepairInfoList);

            List<String> selectBAIdList = new List<String>();
            for (RepairInfo info : RepairInfoList) {

                if (String.isNotBlank(info.ba.serviceType__c)) {
                    info.ba.BusinessATS__c = repairId;
                    info.ba.BusinessASegment__c = use.TSUserSegment__c;
                    if (String.isBlank(info.ba.Id) &&
                            String.isBlank(info.ba.User_FaultInfo__c) &&
                            info.ba.firstInput__c == '是') {
                        info.ba.AgreeReportDate__c = tsr.TSReportDate__c;
                    }
                    if ('申请中'.equals(tsr.TSReportStatus__c)) {
                        info.ba.BusinessAFirstSubmission__c = Datetime.now();
                    }

                    if (String.isNotBlank(info.ba.Id)) {
                        if (info.ba.BaFromUserFaultInfo__c) {
                            selectBAIdList.add(info.ba.Id);
                        }
                    }
                    info.ba.BaFromUserFaultInfo__c = false;
                    businessActivityList.add(info.ba);


                    info.uf.UFLineNumber__c = info.lineNumber;
                    info.ba.BusinessALineNumber__c = info.lineNumber;
                    failureAssetMap.put(info.lineNumber, info.failureAssetList);
                } else {
                    if (String.isNotBlank(info.ba.Id)) {
                        deleteBusinessActivityIdList.add(info.ba.Id);
                    }
                }
            }
            if (businessActivityList.size() > 0) {


                upsert businessActivityList;
            }
            // 删除业务活动、用户故障信息
            if (deleteBusinessActivityIdList != null && deleteBusinessActivityIdList.size() > 0) {
                TSRepairUtil.deleteBusinessActivityInformation(deleteBusinessActivityIdList);

            }
            // 通过 搜索按钮 查找 用户/故障信息，删除业务活动下的 故障产品信息 和 附件 Start
            if (selectBAIdList.size() > 0) {
                // 查找 业务活动下的 故障产品信息 并删除
                List<FailureAsset__c> deleteFailureAssetList = TSRepairUtil.GetFailureAssetList(null, null, selectBAIdList, null, null);
                if (deleteFailureAssetList.size() > 0) {
                    delete deleteFailureAssetList;
                }
                // 查找 业务活动下的 附件 并删除
                List<String> parentIdList = new List<String>();
                List<Attachment> deleteAttachmentList = TSRepairUtil.GetAttachmentList(selectBAIdList);
                if (deleteAttachmentList.size() > 0) {
                    delete deleteAttachmentList;
                }
            }
            // 通过 搜索按钮 查找 用户/故障信息，删除业务活动下的 故障产品信息 和 附件 End
            if (businessActivityList.size() > 0) {

                Map<String, BusinessActivity__c> updateUserFaultInfoMap = new Map<String, BusinessActivity__c>();
                List<BusinessActivity__c> updateBusinessActivityList = new List<BusinessActivity__c>();

                // upsert businessActivityList;

                //日报状态 确认状态 查找用户/故障信息的 服务内容(汇总)的值
                List<String> selectUfIdListPass = new List<String>();

                for ( BusinessActivity__c  ba : businessActivityList) {
                    updateUserFaultInfoMap.put(ba.Id, ba);

                    if (ba.BusinessAHaveAttachment__c) {
                        // 用户/故障信息下的附件克隆一份至业务活动
                        List<String> selectUfIdList = new List<String>();
                        selectUfIdList.add(ba.User_FaultInfo__c);
                        TSRepairUtil.insertattachmentCloneList(selectUfIdList, ba.Id);

                        ba.BusinessAHaveAttachment__c = false;
                        updateBusinessActivityList.add(ba);
                    }

                    if ('确认'.equals(tsr.TSReportStatus__c)) {
                        selectUfIdListPass.add(ba.User_FaultInfo__c);

                    }
                }

                // 更新 业务活动
                if (updateBusinessActivityList != null && updateBusinessActivityList.size() > 0) {
                    upsert updateBusinessActivityList;
                }

                if ('申请中'.equals(tsr.TSReportStatus__c) || '确认'.equals(tsr.TSReportStatus__c)) {
                    if (updateUserFaultInfoMap != null && updateUserFaultInfoMap.size() > 0) {
                        // 用户故障信息赋值
                        userFaultInfoMap.putAll(UserFaultInfoAssembled(updateUserFaultInfoMap, selectUfIdListPass));
                    }
                    if ('申请中'.equals(tsr.TSReportStatus__c)) {
                        upsertFailureAssetStatus(failureAssetMap, businessActivityList);
                        if ( userFaultInfoMap != null && userFaultInfoMap.size() > 0) {
                            // 用户故障样机赋值
                            upsertFailureAsset(failureAssetMap, userFaultInfoMap);
                        }
                    }

                } else {
                    // 更新故障产品信息的业务活动ID，更新业务活动的合计台数
                    upsertFailureAssetStatus(failureAssetMap, businessActivityList);
                }
            }
        } catch (Exception e) {
            ApexPages.addMessages(e);
            errorFlag = true;
            List<String> errorMessageList = new List<String>();
            errorMessageList.add(e.getMessage());
            errorMessageMap.put('TS日报异常', errorMessageList);
            pagemessages(errorMessageMap);
            Database.rollback(sp);
            return  null;
        }
        saveSign = '1';

        return UnabletoEdit('1');
    }
    // 业务活动解除与案件的关系
    public List<RepairInfo> BusinessActivityAndUser_FaultInfoDissociated(List<RepairInfo> RepairInfoList) {
        List<String> deleteBaIdList = new List<String>();
        List<RepairInfo> RepairInfoListSave = new List<RepairInfo>();
        for (RepairInfo info : RepairInfoList) {

            if (info.ba.firstInput__c == '是') {
                String baId = info.ba.Id;
                // BaFromUserFaultInfo__c为True，为 选择已有案件，又重新选择了 首次登陆案件 为 [是]，不更新 业务活动
                if (info.ba.BaFromUserFaultInfo__c == true) {

                } else {
                    // BaFromUserFaultInfo__c为false，有 Id，检查 原来的业务活动 的首次登陆案件 的 值
                    if (String.isNotBlank(baId) && activityInItMap != null && activityInItMap.containsKey(baId)) {
                        String firstInputOriginalValue = activityInItMap.get(baId);
                        if (firstInputOriginalValue != info.ba.firstInput__c) {
                            // 不相等 删除业务活动
                            deleteBaIdList.add(baId);
                        } else {
                            // 不做特殊处理
                            RepairInfoListSave.add(info);
                        }
                    } else {
                        RepairInfoListSave.add(info);
                    }
                }
            } else {
                RepairInfoListSave.add(info);
            }
        }
        // 删除业务活动
        if (deleteBaIdList.size() > 0) {
            TSRepairUtil.deleteBusinessActivityInformation(deleteBaIdList);
        }

        return RepairInfoListSave;
    }

    // TS日报被驳回或状态由申请中变成草案中，与TS日报下业务活动关联的 用户/故障信息 进行还原或删除
    public Void TSRepairStatus() {
        //获取业务活动关联的用户故障信息Id,取出相关联的业务活动
        List<String> ufIdList = new List<String>();
        List<String> deleteUfIdList =  new List<String>();
        for (RepairInfo info : RepairInfoList) {
            String ufId = info.ba.User_FaultInfo__c;
            if (String.isNotBlank(ufId) && info.ba.firstInput__c == '否') {
                ufIdList.add(ufId);
            } else if (String.isNotBlank(ufId) && info.ba.firstInput__c == '是') {
                deleteUfIdList.add(ufId);
            }
        }
        if (deleteUfIdList.size() > 0) {
            List<BusinessActivity__c> activityList = TSRepairUtil.GetBusinessActivityList(null, deleteUfIdList , null, null, null, '');
            Map<String, List<BusinessActivity__c>> businessActivityListMap = new Map<String, List<BusinessActivity__c>>();
            if (activityList.size() > 0) {
                // 统计用户/故障信息 下 关联的业务活动的数量 Start
                for (BusinessActivity__c ba : activityList) {
                    List<BusinessActivity__c> baList = new List<BusinessActivity__c>();
                    if (businessActivityListMap.containsKey(ba.User_FaultInfo__c)) {
                        baList = businessActivityListMap.get(ba.User_FaultInfo__c);
                    }
                    baList.add(ba);
                    businessActivityListMap.put(ba.User_FaultInfo__c, baList);

                }
                // 统计用户/故障信息 下 关联的业务活动的数量 End
                if (businessActivityListMap != null && businessActivityListMap.size() > 0) {
                    List<String> deleteUfIdList01 = new List<String>();
                    List<BusinessActivity__c> updateBAlist = new List<BusinessActivity__c>();
                    for ( String ufId : businessActivityListMap.keySet()) {
                        // 用户故障信息下只有一个 业务活动
                        if (businessActivityListMap.get(ufId).size() == 1) {
                            // 将业务活动 与 用户/故障信息 相关字段的值 清空 Start
                            BusinessActivity__c updateBA  = businessActivityListMap.get(ufId)[0];
                            updateBA.FindManagementCode__c = null;
                            updateBA.ManagementCode__c = null;
                            updateBA.User_FaultInfo__c = null;
                            updateBAlist.add(updateBA);
                            // 将业务活动 与 用户/故障信息 相关字段的值 清空 End
                            deleteUfIdList01.add(ufId);
                        } else if (businessActivityListMap.get(ufId).size() > 1 ) {
                            ufIdList.add(ufId);
                        }
                    }

                    if (deleteUfIdList01.size() > 0) {
                        // 查找用户/故障信息下的 故障产品信息 并删除
                        List<FailureAsset__c> deleteUFfailureAssetList = TSRepairUtil.GetFailureAssetList(null, deleteUfIdList01, null, null, null);

                        if (deleteUFfailureAssetList.size() > 0) {
                            delete deleteUFfailureAssetList;
                        }
                        // 查找用户/故障信息 并删除
                        List<User_FaultInfo__c> delletefaultInfoList = TSRepairUtil.GetfaultInfoList(deleteUfIdList01, null, null, '');
                        if (delletefaultInfoList.size() > 0) {
                            delete delletefaultInfoList;
                        }
                        // 变更 业务活动
                        if (updateBAlist.size() > 0) {
                            update updateBAlist;
                        }
                    }
                }
            }
        }
        Map<String, BusinessActivity__c> maxSubmissionMap = new Map<String, BusinessActivity__c>();
        // 为 用户/故障信息的 服务内容(汇总) 字段 赋值
        businessActivityListToMap = new Map<String, List<BusinessActivity__c>>();
        if (ufIdList.size() > 0) {
            // 查找与用户/故障信息关联的业务活动
            List<BusinessActivity__c> activityList = TSRepairUtil.GetBusinessActivityList(null, ufIdList , null, null, null, '');
            if (activityList.size() > 0) {

                for (BusinessActivity__c ba : activityList) {

                    if (ba.BusinessATSReportStatus__c == '申请中' ||
                            ba.BusinessATSReportStatus__c == '确认') {
                        // 取 状态是 '申请中'/ '确认' 并且提交时间最大值的业务活动 用于 用户/故障信息的数据 还原 Start
                        String ufId = ba.User_FaultInfo__c;
                        if (maxSubmissionMap.containsKey(ufId)) {
                            if (ba.BusinessAFirstSubmission__c  > maxSubmissionMap.get(ufId).BusinessAFirstSubmission__c) {
                                maxSubmissionMap.put(ufId, ba);
                            }
                        } else {
                            maxSubmissionMap.put(ufId, ba);
                        }
                        // 取 状态是 '申请中'/ '确认' 并且提交时间最大值的业务活动 用于 用户/故障信息的数据 还原 End
                        if (ba.BusinessATSReportStatus__c == '确认') {
                            List<BusinessActivity__c> baList = new List<BusinessActivity__c>();
                            if (businessActivityListToMap.containsKey(ba.User_FaultInfo__c)) {
                                baList = businessActivityListToMap.get(ba.User_FaultInfo__c);
                            }
                            baList.add(ba);
                            businessActivityListToMap.put(ba.User_FaultInfo__c, baList);
                        }


                    }

                }
            }
        }

        if (maxSubmissionMap != null && maxSubmissionMap.size() > 0) {
            Map<String, BusinessActivity__c> baMap = new Map<String, BusinessActivity__c>();
            List<String> ufIdList01 = new List<String>();
            List<String> baIdListGetFailureAsset = new List<String>();
            Map<String, String> BaUfIdMap = new Map<String, String>();
            for (String ufId : maxSubmissionMap.keySet()) {
                BusinessActivity__c ba = maxSubmissionMap.get(ufId);
                ufIdList01.add(ufId);
                baMap.put(ba.Id, ba);
                baIdListGetFailureAsset.add(ba.Id);
                BaUfIdMap.put(ba.Id, ufId);
            }

            //删除 用户/故障信息下的 故障产品信息 Start
            Map<String, List<FailureAsset__c>> selectUFfailureAssetMap = new Map<String, List<FailureAsset__c>>();
            selectUFfailureAssetMap = TSRepairUtil.GetUserFaultInfMap(ufIdList01, null);
            List<FailureAsset__c> deleteFailureAssetList = new List<FailureAsset__c>();
            if (selectUFfailureAssetMap != null && selectUFfailureAssetMap.size() > 0 ) {

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

                    for (FailureAsset__c fa : selectUFfailureAssetMap.get(ufId)) {
                        deleteFailureAssetList.add(fa);
                    }
                }

                if (deleteFailureAssetList.size() > 0) {
                    delete deleteFailureAssetList;
                }
            }
            // 删除 用户/故障信息下的 故障产品信息 End

            //用户/故障信息 数据还原 Start
            List<String> selectUfIdListPass = new List<String>();
            UserFaultInfoAssembled(baMap, selectUfIdListPass);
            //用户/故障信息 数据还原 End

            Map<String, List<FailureAsset__c>> selectBAfailureAssetMap = new Map<String, List<FailureAsset__c>>();
            if (BaUfIdMap != null && BaUfIdMap.size() > 0 ) {
                selectBAfailureAssetMap = TSRepairUtil.GetUserFaultInfMap(null, baIdListGetFailureAsset);
                if ( selectBAfailureAssetMap != null && selectBAfailureAssetMap.size() > 0) {
                    List<FailureAsset__c> baFailureAssetList = new List<FailureAsset__c>();
                    List<User_FaultInfo__c> updateUFlist = new List<User_FaultInfo__c>();
                    for (String baId : selectBAfailureAssetMap.keySet()) {
                        for (FailureAsset__c fa : selectBAfailureAssetMap.get(baId)) {

                            // 将 业务活动下的 故障产品信息 克隆一份 至 用户/故障信息下 Start
                            FailureAsset__c cloneFa = fa.clone();
                            cloneFa.FAActivity__c = null;
                            cloneFa.Id = null;
                            cloneFa.FAUserFaultInfo__c = BaUfIdMap.get(baId);
                            baFailureAssetList.add(cloneFa);
                            // 将 业务活动下的 故障产品信息 克隆一份 至 用户/故障信息下 End
                        }

                        // 汇总 用户/故障信息 下面的 故障产品信息 中 机型/产品系列/机身号/保修状态 Start
                        User_FaultInfo__c updateUserFaultInfo = new  User_FaultInfo__c();
                        updateUserFaultInfo.Id = BaUfIdMap.get(baId);
                        updateUserFaultInfo.UserFaultInfoCombinedAmount__c = selectBAfailureAssetMap.get(baId).size();//合计台数
                        updateUserFaultInfo = Summation(selectBAfailureAssetMap.get(baId), updateUserFaultInfo);
                        updateUFlist.add(updateUserFaultInfo);

                        // 汇总 用户/故障信息 下面的 故障产品信息 中 机型/产品系列/机身号/保修状态 End
                    }

                    if (baFailureAssetList.size() > 0) {
                        insert baFailureAssetList;
                    }

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

    // 新增 TS日报
    public String TSRepairAssembled(TS_Repair__c tsr) {
        String result = '';
        if (tsr.TSReportDate__c == null) {
            tsr.TSReportDate__c = Date.today();
        }
        tsr.TSReportPerson__c = UserInfo.getUserId();

        tsr.TSRepairSuperior__c = use.TSUserSuperior__c ;
        tsr.TSRepairClass__c = use.TSUserClass__c;
        tsr.TSReportPerson__c = use.id;

        if (tsr.TSReportStatus__c != '申请中') {
            tsr.TSReportStatus__c = '草案中';
        }
        tsr.TSRepairDepartment__c = use.TSUserDepartment__c;
        tsr.TSRepairSegment__c = use.TSUserSegment__c;

        List<TS_Repair__c> tSRepairList = TSRepairUtil.GetTsRepairList('', tsr.TSReportPerson__c, tsr.TSReportDate__c , null, null, '');

        if (tSRepairList != null && tSRepairList.size() > 0) {
            List<String> errorMessageList = new List<String>();
            String date01 = String.valueOf(tsr.TSReportDate__c);
            errorMessageList.add(date01 + '日TS日报已存在，请不要重复创建,已存在的TS日报名称:' + tSRepairList[0].Name);
            errorMessageMap.put('TS日报异常', errorMessageList);
            pagemessages(errorMessageMap);
        } else {
            upsert tsr;
            result = tsr.Id;
        }

        return result;
    }

    // 刷新TS日报
    public PageReference UnabletoEdit(String saveSign) {
        String url = '/apex/TSRepair?Id=';
        if (String.isNotBlank(repairId)) {
            url +=  repairId;
        }
        if (String.isNotBlank(saveSign)) {
            url += '&save=' + saveSign;
        }

        PageReference  ref = new Pagereference(url);
        ref.setRedirect(true);
        return ref;
    }
    //业务活动相关字段赋值
    public String ServiceContentNewAssembled(String serviceContentNew) {
        String result = '';
        if ( String.isNotBlank(serviceContentNew)) {
            // 送信者/TS日报报告人
            String username = tsr.TSReportName__c;
            // TS日报 报告日期
            Date dt = tsr.TSReportDate__c;

            // 服务内容
            result += '****** ' + username + ' ' + dt + ' ******\n';
            result += serviceContentNew;
        }

        return result;

    }
    //业务活动相关字段赋值
    public String ServiceContentNewBa(BusinessActivity__c ba) {
        String result = '';
        // if ( String.isNotBlank(serviceContentNew)) {
        // // 送信者/TS日报报告人
        String username = ba.BusinessATSReportReporter__c;
        // // TS日报 报告日期
        Date tSReportDate = ba.BusinessATSReportDay__c;

        // 服务内容
        result += '****** ' + username + ' ' + tSReportDate + ' ******\n';
        result += ba.BusinessAServiceContentNew__c;
        // }

        return result;

    }
    /**
     * [UserFaultInfoAssembled 用户/故障信息字段赋值]
     * @param  updateUserFaultInfoMap [业务活动的基本信息]
     * @return                        [description]
     */
    public Map<Integer, User_FaultInfo__c> UserFaultInfoAssembled(Map<String, BusinessActivity__c> updateUserFaultInfoMap, List<String> selectUfIdListPass) {
        Map<Integer, User_FaultInfo__c> result = new Map<Integer, User_FaultInfo__c>();
        List<User_FaultInfo__c> updateUserFaultInfoList = new List<User_FaultInfo__c>();
        String UserFaultInfoId = '';
        Map<String, List<Attachment>> insertAttachmentMap = new Map<String, List<Attachment>>();
        Map<String, User_FaultInfo__c> findfaultInfoMap = new Map<String, User_FaultInfo__c>();
        if (selectUfIdListPass != null && selectUfIdListPass.size() > 0) {
            findfaultInfoMap = TSRepairUtil.GetfaultInfoMap(selectUfIdListPass);
        }

        for (String baId : updateUserFaultInfoMap.keySet()) {

            BusinessActivity__c ba = updateUserFaultInfoMap.get(baId);
            UserFaultInfoId =  ba.User_FaultInfo__c;
            User_FaultInfo__c updateUserFaultInfo = new User_FaultInfo__c();
            if (String.isBlank(UserFaultInfoId)) {
                updateUserFaultInfo.UserFaultInfoUserArea__c = use.TSUserArea__c;
                updateUserFaultInfo.UserFaultInfoSuperior__c = use.TSUserSuperior__c;
                updateUserFaultInfo.UserFaultInfoDepartment__c = use.TSUserDepartment__c;
                updateUserFaultInfo.UserFaultInfoEmployeeID__c = use.TSEmployeeID__c;
                updateUserFaultInfo.UserFaultInfoReportPerson__c = use.Id;
                updateUserFaultInfo.UserFaultInfoClass__c = use.TSUserClass__c;
                updateUserFaultInfo.UserFaultInfoSegment__c = use.TSUserSegment__c;
                updateUserFaultInfo.UserFaultInfoReportDate__c = tsr.TSReportDate__c;
                // updateUserFaultInfo.RecordTypeId = '0120T0000000zFj';
                updateUserFaultInfo.RecordTypeId = System.label.Case_RecordTypeTSTSReport;
                
            } else {
                //将业务活动下的附件克隆至 用户/故障信息
                List<String> selectBAIdList = new List<String>();
                selectBAIdList.add(baId);
                TSRepairUtil.insertattachmentCloneList(selectBAIdList, UserFaultInfoId);
            }
            updateUserFaultInfo.Id = UserFaultInfoId;
            updateUserFaultInfo.UserFaultInfoServiceType__c = ba.serviceType__c ;//服务类型
            updateUserFaultInfo.UFFaultContent__c = ba.BusinessAFaultContent__c ;//故障内容
            updateUserFaultInfo.UFRepairDate__c = ba.BusinessARepairDate__c ;//报修日期
            updateUserFaultInfo.UFDetermineDate__c = ba.BusinessADetermineDate__c;//判断日期
            updateUserFaultInfo.UFDateRequest__c = ba.BusinessADateRequest__c ;//要求服务日期
            updateUserFaultInfo.UFMessageSource__c = ba.BusinessAMessageSource__c ;//信息来源
            updateUserFaultInfo.UFNatureService__c = ba.BusinessANatureService__c ;//服务性质
            updateUserFaultInfo.UFWithoutReason__c = ba.BusinessAWithoutReason__c ;//无偿原因
            updateUserFaultInfo.UFDateApproval__c = ba.BusinessADateApproval__c ;//同意报价日期
            updateUserFaultInfo.UserFaultInfoDateQuotation__c = ba.BusinessADateQuotation__c;//报价日期
            if ('确认'.equals(tsr.TSReportStatus__c)) {//服务内容(汇总)

                String getserviceContent  = findfaultInfoMap.get(UserFaultInfoId).UserFaultInfoServiceContent__c;
                String  serviceContent = ServiceContentNewAssembled(ba.BusinessAServiceContentNew__c);

                if (String.isNotBlank(getserviceContent)) {
                    updateUserFaultInfo.UserFaultInfoServiceContent__c = getserviceContent + '\n';
                    updateUserFaultInfo.UserFaultInfoServiceContent__c += serviceContent;
                } else {
                    updateUserFaultInfo.UserFaultInfoServiceContent__c = serviceContent;
                }
            }

            updateUserFaultInfo.UserFaultInfoServicePlace__c = ba.BusinessAServicePlace__c ;//服务场所
            updateUserFaultInfo.UserFaultInfoBusinessTrip__c = ba.BusinessABusinessTrip__c ;//出差地
            updateUserFaultInfo.UserFaultInfoCompletionDate__c = ba.BusinessACompletionDate__c ;//案件完成日
            updateUserFaultInfo.UserFaultInfoNextService__c = ba.BusinessANextService__c ;//下次服务时间
            updateUserFaultInfo.UFAccount__c = ba.BusinessAAccount__c ;//客户单位(查找)
            updateUserFaultInfo.UserFaultInfoCustomerUnit__c = ba.BusinessACustomerUnit__c ;//客户单位(文本)
            updateUserFaultInfo.UFContact__c = ba.BusinessAContact__c ;//联系人
            updateUserFaultInfo.UFPhone__c = ba.BusinessAPhone_F__c ;//联系电话

            updateUserFaultInfo.UserFaultInfoServiceCategory__c = ba.BusinessAServiceCategory__c ;//服务范畴
            updateUserFaultInfo.UFLineNumber__c = ba.BusinessALineNumber__c;
            updateUserFaultInfo.UserFaultInfoServiceContractNo__c = ba.BusinessAServiceContractNo__c;//服务合同号
            updateUserFaultInfo.UserFaultInfoServiceResult__c = ba.BusinessAServiceResult__c;//服务结果
            List<String> selectUserFaultInfoIdList = new List<String>();
            selectUserFaultInfoIdList.add(UserFaultInfoId);

            updateUserFaultInfoList.add(updateUserFaultInfo);

            // 删除 用户/故障信息下的附件
            List<Attachment> delectUFAttachmentList = TSRepairUtil.GetAttachmentList(selectUserFaultInfoIdList);
            if (delectUFAttachmentList != null && delectUFAttachmentList.size() > 0) {
                delete delectUFAttachmentList;
            }


        }


        if (updateUserFaultInfoList.size() > 0 ) {
            upsert updateUserFaultInfoList;
            List<String> ufIdList = new List<String>();

            for (User_FaultInfo__c uf : updateUserFaultInfoList) {
                ufIdList.add(uf.Id);
            }
            // 查找 用户故障信息 并将Name赋值给业务活动相关的值
            List<User_FaultInfo__c> faultInfoList = TSRepairUtil.GetfaultInfoList(ufIdList, null, null, '');
            List<BusinessActivity__c> updateBusinessActivityList = new List<BusinessActivity__c>();
            Map<String, BusinessActivity__c> updateBusinessActivityMap = new Map<String, BusinessActivity__c>();

            for (String baId : updateUserFaultInfoMap.keySet()) {
                BusinessActivity__c ba = updateUserFaultInfoMap.get(baId);
                for (User_FaultInfo__c uf : faultInfoList) {
                    // if (String.isBlank(ba.FindManagementCode__c)) {
                    if (ba.User_FaultInfo__c == uf.Id || ba.BusinessALineNumber__c == uf.UFLineNumber__c) {
                        ba.ManagementCode__c = uf.Name;
                        ba.FindManagementCode__c = uf.Name;
                        ba.User_FaultInfo__c = uf.Id;
                        updateBusinessActivityList.add(ba);
                        //将业务活动下的附件克隆至 用户/故障信息
                        List<String> selectBAIdList = new List<String>();
                        selectBAIdList.add(baId);
                        TSRepairUtil.insertattachmentCloneList(selectBAIdList, uf.Id);
                    }
                    // }
                    result.put(Integer.valueOf(uf.UFLineNumber__c), uf);
                }
            }

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

        }

        return result;
    }

    //日报状态是草案中或驳回状态 故障产品赋值
    //更新故障产品信息的业务活动ID，更新业务活动的合计台数
    public void upsertFailureAssetStatus(Map<Integer, List<FailureAsset__c>> failureAssetMap, List<BusinessActivity__c> businessActivityList) {
        List<FailureAsset__c> upsertFailureAssetList = new List<FailureAsset__c>();
        Map<String, List<FailureAsset__c>> combinedAmountMap = new Map<String, List<FailureAsset__c>>();
        for (BusinessActivity__c ba : businessActivityList) {

            Integer  lineNumber = Integer.valueOf(ba.BusinessALineNumber__c);
            List<FailureAsset__c>  combinedAmountList = new List<FailureAsset__c>();
            if ( failureAssetMap != null && failureAssetMap.size() > 0) {
                for (FailureAsset__c  fa : failureAssetMap.get(lineNumber)) {
                    if (String.isNotBlank(fa.model__c)) {

                        if (String.isBlank(fa.Id)) {
                            fa.FAActivity__c = ba.Id;
                        }
                        upsertFailureAssetList.add(fa);
                        combinedAmountList.add(fa);
                    }

                }
            }

            combinedAmountMap.put(ba.Id, combinedAmountList);
        }

        if (upsertFailureAssetList.size() > 0 ) {
            upsert upsertFailureAssetList;
        }

        if (combinedAmountMap != null && combinedAmountMap.size() > 0) {
            List<BusinessActivity__c> updateCombinedAmount = new List<BusinessActivity__c>();
            for (String baId : combinedAmountMap.keySet()) {
                BusinessActivity__c updateBa = new BusinessActivity__c();
                updateBa.Id = baId;
                updateBa.BusinessACombinedAmount__c = combinedAmountMap.get(baId).size();
                updateCombinedAmount.add(updateBa);
            }

            update updateCombinedAmount;
        }
    }

    //保存用户/故障样机
    public void upsertFailureAsset(Map<Integer, List<FailureAsset__c>> failureAssetMap, Map<Integer, User_FaultInfo__c> userFaultInfoMap) {

        List<FailureAsset__c> upsertFailureAssetList = new List<FailureAsset__c>();
        List<FailureAsset__c> deleteFailureAssetList = new List<FailureAsset__c>();
        Map<String, User_FaultInfo__c> updateUserFaultInfoMap = new Map<String, User_FaultInfo__c>();
        List<String> selectUfIdList = new List<String>();

        Map<String, List<FailureAsset__c>> combinedAmountMap = new Map<String, List<FailureAsset__c>>();
        for (Integer lineNumber : failureAssetMap.keySet()) {

            User_FaultInfo__c updateUserFaultInfoOriginal = userFaultInfoMap.get(lineNumber);
            User_FaultInfo__c updateUserFaultInfo = new  User_FaultInfo__c();
            updateUserFaultInfo.Id = updateUserFaultInfoOriginal.Id;
            if (failureAssetMap.get(lineNumber).size() > 0) {
                selectUfIdList.add(updateUserFaultInfo.Id);
            }
            List<FailureAsset__c>  combinedAmountList = new List<FailureAsset__c>();
            String baId = '';

            for (FailureAsset__c fa : failureAssetMap.get(lineNumber)) {
                if (String.isNotBlank(fa.model__c)) {
                    // 获取业务活动ID
                    baId = fa.FAActivity__c;
                    // 故障样机 Start
                    fa.FAUserFaultInfo__c = updateUserFaultInfo.Id;
                    fa.Id = null;
                    fa.FAActivity__c = null;
                    upsertFailureAssetList.add(fa);
                    // 故障样机 End
                    combinedAmountList.add(fa);

                } else {
                    // 用户故障样机的机型为空，并且样机存在Id，那么删除这个样机
                    if (String.isNotBlank(fa.Id)) {
                        deleteFailureAssetList.add(fa);
                    }
                }
            }

            if (String.isNotBlank(baId)) {
                combinedAmountMap.put(baId, combinedAmountList);
            }
            updateUserFaultInfo.UserFaultInfoCombinedAmount__c = combinedAmountList.size();
            updateUserFaultInfo.UserFaultInfoApprovalDate__c = updateUserFaultInfoOriginal.UserFaultInfoApprovalDate__c;
            updateUserFaultInfo = Summation(failureAssetMap.get(lineNumber), updateUserFaultInfo);
            updateUserFaultInfoMap.put(updateUserFaultInfo.Id, updateUserFaultInfo);

        }
        if (selectUfIdList.size() > 0) {
            List<FailureAsset__c> deleteUFfailureAssetList = TSRepairUtil.GetFailureAssetList(null, selectUfIdList, null, null, null);

            if (deleteUFfailureAssetList.size() > 0) {
                delete deleteUFfailureAssetList;
            }
        }

        if (combinedAmountMap != null && combinedAmountMap.size() > 0) {
            List<BusinessActivity__c> updateCombinedAmount = new List<BusinessActivity__c>();
            for (String baId : combinedAmountMap.keySet()) {
                BusinessActivity__c updateBa = new BusinessActivity__c();
                updateBa.Id = baId;
                updateBa.BusinessACombinedAmount__c = combinedAmountMap.get(baId).size();
                updateCombinedAmount.add(updateBa);
            }

            update updateCombinedAmount;
        }

        // 更新/新增 故障样机
        if (upsertFailureAssetList.size() > 0) {
            upsert upsertFailureAssetList;
        }
        // 删除 故障样机
        if (deleteFailureAssetList.size() > 0) {
            delete deleteFailureAssetList;
        }
        // 更新 用户/故障样机 机型/产品系列/机身号/保修状态
        if (updateUserFaultInfoMap != null && updateUserFaultInfoMap.size() > 0) {
            upsert updateUserFaultInfoMap.values();
        }
    }
    /**
     * [getValue description]数据拼接
     * @param  originalValue [原始值]
     * @param  addValue      [新增值]
     * @return               [description]
     */
    public String getValue(String originalValue, String addValue) {
        // originalValue 空 addValue 不空 数据拼接
        // originalValue 空 addValue 空
        // originalValue 不空 addValue 空
        // originalValue 不空 addValue 不空 数据拼接
        if (String.isBlank(originalValue) && String.isNotBlank(addValue)) {
            originalValue = addValue;
        } else if (String.isNotBlank(originalValue) && String.isNotBlank(addValue)) {
            originalValue += ';' + addValue;
        }

        return originalValue;

    }
    // 机型/产品系列/机身号/保修状态 汇总
    public User_FaultInfo__c Summation(List<FailureAsset__c> failureAssetList, User_FaultInfo__c updateUserFaultInfo) {
        String userFaultInfoModel = '';
        String userFaultInfoProductSeries = '';
        String userFaultInfoSerialNumber = '';
        String userFaultInfoWarrantyStatus = '';

        for (FailureAsset__c fa : failureAssetList) {
            if (String.isNotBlank(fa.model__c)) {

                // 机型/产品系列/机身号/保修状态 汇总 Start
                userFaultInfoModel = getValue(userFaultInfoModel, fa.model__c);
                userFaultInfoProductSeries = getValue(userFaultInfoProductSeries, fa.FAProductSeries__c);
                userFaultInfoSerialNumber = getValue(userFaultInfoSerialNumber, fa.SerialNumber__c);
                userFaultInfoWarrantyStatus = getValue(userFaultInfoWarrantyStatus, fa.WarrantyStatus__c);
                // 机型/产品系列/机身号/保修状态 汇总 End
            }

            updateUserFaultInfo.UserFaultInfoModel__c = userFaultInfoModel;//机型
            updateUserFaultInfo.UserFaultInfoProductSeries__c = userFaultInfoProductSeries;//产品系列
            updateUserFaultInfo.UserFaultInfoSerialNumber__c = userFaultInfoSerialNumber;//机身号
            updateUserFaultInfo.UserFaultInfoWarrantyStatus__c = userFaultInfoWarrantyStatus;//保修状态
        }

        return updateUserFaultInfo;
    }

    // 初始化TS日报
    public void GetInfoData(String repairId, Date dd) {
        activityInItMap = new Map<String, String>();
        //activityInItMap1 = new Map<String, String>();

        if (String.isNotBlank(repairId)) {

            List<TS_Repair__c> TSRepairs = TSRepairUtil.GetTsRepairList(repairId, '', null, null, null, '');
            tsr = TSRepairs[0];
            List<String> selectRepairIdList = new List<String>();
            selectRepairIdList.add(repairId);
            List<BusinessActivity__c> activityList = TSRepairUtil.GetBusinessActivityList(selectRepairIdList, null, null, null, null, '');

            // 用户故障信息
            Map<String, User_FaultInfo__c> user_FaultMap = new Map<String, User_FaultInfo__c>();
            // 用户故障样机
            Map<String, List<FailureAsset__c>> failureAssetMap = new Map<String, List<FailureAsset__c>>();
            // 查找业务活动下的附件
            Map<String, List<Attachment>> attachmentsMap = new Map<String, List<Attachment>>();

            if (activityList.size() > 0) {
                //activityInItList = activityList
                List<String> selectUfIdList = new List<String>();
                List<String> selectbaIdList = new List<String>();
                for (BusinessActivity__c ba : activityList) {
                    selectUfIdList.add(ba.User_FaultInfo__c);
                    selectbaIdList.add(ba.Id);
                    activityInItMap.put(ba.Id, ba.firstInput__c );
                    //activityInItMap1.put(ba.Id,ba.firstInput__c);
                }
                //system.debug('activityInItMap--->'+activityInItMap);
                user_FaultMap = TSRepairUtil.GetfaultInfoMap(selectUfIdList);
                failureAssetMap = TSRepairUtil.GetUserFaultInfMap(null, selectbaIdList);
                attachmentsMap =  TSRepairUtil.GetAttachmentMap(selectbaIdList);
                DataAssembly(activityList, user_FaultMap, failureAssetMap, attachmentsMap);
            } else {
                additionBusinessActivity(0);
            }
        } else {
            //初始化 日报
            tsr = new TS_Repair__c();
            if (dd != null) {
                tsr.TSReportDate__c = dd;
            } else {
                tsr.TSReportDate__c = Date.today();
            }
            tsr.TSReportPerson__c = UserInfo.getUserId();

            tsr.TSRepairSuperior__c = use.TSUserSuperior__c ;
            tsr.TSRepairClass__c = use.TSUserClass__c;
            tsr.TSReportPerson__c = use.id;
            tsr.TSReportStatus__c = '草案中';
            tsr.TSRepairDepartment__c = use.TSUserDepartment__c;
            tsr.TSRepairSegment__c = use.TSUserSegment__c;

            List<BusinessActivity__c> activityList = new List<BusinessActivity__c>();
            DataAssembly(activityList, null, null, null);
        }

    }
    // 页面数据组装
    public void DataAssembly(List<BusinessActivity__c> activityList,
                             Map<String, User_FaultInfo__c> user_FaultMap,
                             Map<String, List<FailureAsset__c>> failureAssetMap,
                             Map<String, List<Attachment>> attachmentsMap) {
        RepairInfoList = new List<RepairInfo>();

        User_FaultInfo__c uf = new User_FaultInfo__c();


        for (BusinessActivity__c ba : activityList) {
            // 页面显示 用户/故障信息
            if (user_FaultMap != null && user_FaultMap.size() > 0) {
                if (user_FaultMap.containsKey(ba.User_FaultInfo__c)) {
                    uf = user_FaultMap.get(ba.User_FaultInfo__c);
                }
            }
            // 页面显示 故障样机
            List<FailureAsset__c> faList = new List<FailureAsset__c>();
            if (failureAssetMap != null && failureAssetMap.size() > 0) {
                if (failureAssetMap.containsKey(ba.Id)) {
                    faList = failureAssetMap.get(ba.Id);
                }
                Integer size = faList.size();
                if ( size < initFailureAssetListSize) {

                    faList = getFailureAssetList(faList, size);
                }
            } else {
                faList = getFailureAssetList(null, 0);
            }
            // 页面显示 附件
            List<Attachment> attachments = new List<Attachment>();
            if (attachmentsMap.containsKey(ba.Id)) {
                attachments = attachmentsMap.get(ba.Id);
            }
            RepairInfo re = new RepairInfo(tsr, ba, uf, faList, BusinessActivitySize, attachments);
            RepairInfoList.add(re);
            BusinessActivitySize++;
        }

        Integer index = activityList.size();
        additionBusinessActivity(index);
    }

    //添加业务活动
    public void addBusinessActivity () {
        // 用户/故障信息 初始化赋值
        User_FaultInfo__c uf = new User_FaultInfo__c();
        uf.UserFaultInfoUserArea__c = use.TSUserArea__c;
        uf.UserFaultInfoSuperior__c = use.TSUserSuperior__c;
        uf.UserFaultInfoDepartment__c = use.TSUserDepartment__c;
        uf.UserFaultInfoEmployeeID__c = use.TSEmployeeID__c;
        uf.UserFaultInfoReportPerson__c = use.Id;
        uf.UserFaultInfoClass__c = use.TSUserClass__c;
        uf.UserFaultInfoSegment__c = use.TSUserSegment__c;
        uf.UserFaultInfoReportDate__c = Date.today();

        List<String> selectUfIdList = new List<String>();
        selectUfIdList.add(uf.Id);
        List<User_FaultInfo__c> uflist = TSRepairUtil.GetfaultInfoList(selectUfIdList, null, null, '');
        //初始化业务活动
        BusinessActivity__c ba = new BusinessActivity__c();
        ba.StartTimeHour__c = '0';
        ba.StartTimeMinute__c = '00';
        ba.EndTimeHour__c = '0';
        ba.EndTimeMinute__c = '00';
        ba.workingHours__c = 0.00;
        ba.firstInput__c = '是';
        ba.BusinessAFirstSubmission__c = null;
        List<FailureAsset__c> faList = getFailureAssetList(null, 0);
        List<Attachment> attachments = new List<Attachment>();
        RepairInfo re = new RepairInfo(tsr, ba, uf, faList, BusinessActivitySize, attachments);

        BusinessActivitySize++;
        RepairInfoList.add(re);

    }
    //添加产品
    public void addFailureAsset() {
        for (RepairInfo ri : RepairInfoList) {
            if (ri.lineNumber == num) {
                if (ri.failureAssetList.size() < maxFailureAssetListSize) {
                    FailureAsset__c fa = new FailureAsset__c();
                    ri.failureAssetList.add(fa);
                    if (ri.failureAssetList.size() == maxFailureAssetListSize) {
                        ri.disabled = true;
                    }
                }
            }
        }
    }
    // 服务范畴 赋值
    public void updateServiceCategory() {

        for (RepairInfo ri : RepairInfoList) {
            if (ri.lineNumber == num) {
                Map<String, String>  serviceCategoryMap = TSRepairUtil.GetserviceCategoryMap();
                String serviceType = serviceCategoryMap.get(ri.ba.serviceType__c);
                ri.ba.BusinessAServiceCategory__c = serviceType;

            }
        }
    }
    // TS日报页面初始化 显示 业务活动 数量
    public void additionBusinessActivity(Integer index) {
        for (Integer i = index ; i < initBusinessActivityListSize; i++) {
            addBusinessActivity();
        }
    }
    //  TS日报页面初始化 显示 故障样机 数量
    public List<FailureAsset__c> getFailureAssetList(List<FailureAsset__c> faList, Integer index) {
        List<FailureAsset__c> result = new List<FailureAsset__c>();
        if (faList != null && faList.size() > 0) {
            result = faList;
        }
        for (Integer i = index ; i < initFailureAssetListSize; i++) {
            FailureAsset__c fa = new FailureAsset__c();
            result.add(fa);
        }

        return result;
    }

    //TS日报页面，修改日期查找对应日期的TS日报
    public PageReference checkReportDate() {
        Date tsDate = tsr.TSReportDate__c;
        if (tsDate == null) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '报告日期为空请确认'));
            tsr.TSReportDate__c  = OriginalDate;
            return null;
        }
        String userId = UserInfo.getUserId();
        List<TS_Repair__c> TSRepairs = TSRepairUtil.GetTsRepairList('', userId, tsDate, null, null, '');
        if (TSRepairs != null && TSRepairs.size() > 0) {

            repairId = TSRepairs[0].Id;
            return UnabletoEdit('2');
        } else {

            return SkipNewTSRepairPage(tsDate);
        }
    }
    // 跳转至新页面
    public PageReference SkipNewTSRepairPage(Date newDate) {

        PageReference   ref = new Pagereference('/apex/TSRepair?date=' + newDate);

        ref.setRedirect(true);
        return ref;
    }

    //跳转到上传附件页面
    public PageReference uploadingAttachment() {
        save();
        if (errorMessageMap != null && errorMessageMap.size() > 0) {
            return null;
        }
        String pid = getParentId();
        if (String.isBlank(pid)) {
            return null;
        }
        PageReference ref = new Pagereference('/p/attach/NoteAttach?pid=' + pid + '&retURL=%2Fapex/TSRepair?id=' + repairId);
        ref.setRedirect(true);
        return ref;
    }
    // 获取附件的父Id
    public String getParentId() {
        String result = '';
        if (String.isNotBlank(baIds.split('/')[0])) {
            result = baIds.split('/')[0];
        } else {
            Integer lineNumber = Integer.ValueOf(baIds.split('/')[1]);
            // 根据TS日报查找业务活动
            List<String> selectRepairIdList = new List<String>();
            selectRepairIdList.add(repairId);
            List<BusinessActivity__c> activityList = TSRepairUtil.GetBusinessActivityList(selectRepairIdList, null, null, null, null, '');
            if (activityList.size() > 0) {
                for (BusinessActivity__c ba : activityList) {
                    if (ba.BusinessALineNumber__c == lineNumber) {
                        result = ba.Id;
                    }
                }
            }

            if (String.isBlank(result)) {
                List<String> errorMessageList = new List<String>();
                errorMessageList.add('附件上传失败，服务类型为空，请确认');
                errorMessageMap.put(baIds.split('/')[1], errorMessageList);
                pagemessages(errorMessageMap);
            }
        }


        return result;
    }

    // 查找当天的TS日报
    public void FindTSRepair() {
        Date  tSReportDate = Date.today();
        String ownId = UserInfo.getUserId();

        List<TS_Repair__c>  tsRepairList = TSRepairUtil.GetTsRepairList('', ownId, tSReportDate, null, null, '');

        if (tsRepairList.size() > 0) {
            repairId = tsRepairList[0].Id;
        }

    }

// 王鹏伟 前台点击按钮修改状态
    public PageReference setStatus() {

        if (status != null && status != '') {

            if (approvalOfValidationPass(status, RepairInfoList)) {
                tsr.TSReportStatus__c = status;
                save();
            }

            if (errorMessageMap != null && errorMessageMap.size() > 0) {
                if ('申请中'.equals(status)) {
                    status = '草案中';
                }
                pagemessages(errorMessageMap);

                return null;
            }
        }
        String statusSign = '1';

        if ('申请中'.equals(status)) {
            statusSign = 'Submit';
        } else if ('草案中'.equals(status)) {
            statusSign = 'Draft';
        } else if ('确认'.equals(status)) {
            statusSign = 'Approval';
        } else if ('驳回'.equals(status)) {
            statusSign = 'Rejected';
        }
        return UnabletoEdit(statusSign);
    }
    public Boolean approvalOfValidationPass(String status, List<RepairInfo> RepairInfoList) {
        errorMessageMap  = new Map<String, List<String>>();
        errorFlag = false;
        List<String> errorMessageList = new List<String>();

        List<TS_Repair__c> TSRepairs = TSRepairUtil.GetTsRepairList(repairId, '', null, null, null, '');


        for (RepairInfo info : RepairInfoList) {

            String code = info.ba.FindManagementCode__c;

            if ('确认'.equals(status)) {

                // 验证是否符合批准规则
                Boolean haveRead = info.ba.BusinessAApprovalOpinion__c != '同意';//审批意见 不是 同意

                if (String.isNotBlank(info.ba.Id) && haveRead) {

                    errorFlag = true;
                    String errorMessage = '业务活动 管理编码 [ ' + code + ' ] 审批意见不是同意不能审批' ;
                    errorMessageList.add(errorMessage);
                    continue;
                }
                // 判断业务活动的 案件完成日 来修改 用户故障信息的 批准日 BusinessACompletionDate__c
                if (info.ba.BusinessACompletionDate__c != null ) {
                    info.uf.UserFaultInfoApprovalDate__c = Date.today();
                }
                // 设置日报批准日
                tsr.TSApprovalDate__c = Date.today();

            }  else if ('申请中'.equals(status)) {

            }
        }

        if ('确认'.equals(status)) {

            //判断TS日报最后修改日期是否一致
            if (tsr.LastModifiedDate != TSRepairs[0].LastModifiedDate) {
                errorFlag = true;
                String errorMessage = '日报已被提交人更新，请刷新后再确认';
                errorMessageList.add(errorMessage);

            }

        }  else if ('申请中'.equals(status)) {

            if (!AuthenticationInformation(RepairInfoList)) {
                errorFlag = true;
            }
            if (tsr.TSRepairFirstSubmission__c == null) {
                tsr.TSRepairFirstSubmission__c = Datetime.now();

            }
        }  else if ('驳回'.equals(status)) {

            //判断TS日报最后修改日期是否一致
            if (tsr.LastModifiedDate != TSRepairs[0].LastModifiedDate) {
                errorFlag = true;
                String errorMessage = '日报已被提交人更新，请刷新后再确认信息';
                errorMessageList.add(errorMessage);

            }

            if (String.isBlank(tsr.TSRepairDismissReason__c)) {
                errorFlag = true;
                String errorMessage = '驳回理由不能为空，请确认';
                errorMessageList.add(errorMessage);
            }
        }
        if (errorMessageList.size() > 0) {
            errorMessageMap.put('TS日报异常', errorMessageList);
        }

        if (errorFlag && errorMessageMap != null && errorMessageMap.size() > 0) {
            pagemessages(errorMessageMap);
            return false;
        }

        return true;
    }
    // 获取时间戳
    public Long GetTimestamp(String timenow, Integer hour, Integer minute, Date tsReportDate) {
        Long result = null;

        if (String.isNotBlank(timenow)) {
            List<String> timeList = timenow.split('-');

            Integer year = Integer.valueOf(timeList[0]);
            Integer month = Integer.valueOf(timeList[1]);
            Integer day = Integer.valueOf(timeList[2]);
            Integer timehour = Integer.valueOf(timeList[3]);
            Integer timeminute = Integer.valueOf(timeList[4]);
            result =  Datetime.newInstanceGmt(year, month, day, timehour, timeminute, 0).getTime();
        } else {
            Integer year = tsReportDate.year();
            Integer month = tsReportDate.month();
            Integer day = tsReportDate.day();
            result =  Datetime.newInstanceGmt(year, month, day, hour, minute, 0).getTime();
        }
        return result;
    }

    public void initBusinessActivity() {
        if (String.isNotBlank(fromUserFaultInfoId)) {
            List<String> ufIdList = new List<String>();
            ufIdList.add(fromUserFaultInfoId);
            List<User_FaultInfo__c> faultInfoList = TSRepairUtil.GetfaultInfoList(ufIdList, null, null, '');
            BusinessActivity__c ba = TSRepairUtil.BusinessActivityAssembled(faultInfoList);
            // 查询附件
            List<Attachment> attachmentList =  TSRepairUtil.GetAttachmentCloneList(ufIdList);
            // 查询 用户故障样机
            List<FailureAsset__c> failureAssetList = TSRepairUtil.GetFailureAssetList(null, ufIdList, null, null, null);
            List<FailureAsset__c> baFailureAssetList = new List<FailureAsset__c>();
            if (failureAssetList.size() > 0) {

                for (FailureAsset__c fa : failureAssetList) {
                    FailureAsset__c cloneFa = fa.clone();
                    cloneFa.FAActivity__c = null;
                    cloneFa.Id = null;
                    cloneFa.FAUserFaultInfo__c = null;
                    baFailureAssetList.add(cloneFa);
                }
            }

            if (baFailureAssetList.size() < 3) {
                baFailureAssetList = getFailureAssetList(baFailureAssetList, baFailureAssetList.size());
            }
            for (RepairInfo repairInfo : RepairInfoList) {
                Integer linenoInteger = Integer.valueof(lineno);
                if (repairInfo.lineNumber == linenoInteger) {
                    String baId = null;
                    if (String.isNotBlank(repairInfo.ba.Id)) {
                        baId = repairInfo.ba.Id;
                    }
                    repairInfo.ba = ba;
                    repairInfo.ba.Id = baId;
                    repairInfo.attachmentLsit = attachmentList;
                    repairInfo.failureAssetList = baFailureAssetList;
                }
            }
        }
    }
    // 异常信息提示
    public void pagemessages(Map<String, List<String>> errorMessageMap) {
        for (String key : errorMessageMap.keySet()) {
            String  title = '';
            if ('TS日报异常'.equals(key)) {
                title = 'TS日报异常信息如下：';
            } else {
                title = '业务活动 [ ' + key + ' ] 异常信息如下：' ;
            }
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, title));
            for (String errorMessage : errorMessageMap.get(key)) {

                String body = '业务活动 [ ' + key + ' ], ' + errorMessage + '';
                if ('TS日报异常'.equals(key)) {
                    body = errorMessage;
                }
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, body));
            }
        }
    }

    //正常保存时 验证 字段有值 是否满足条件
    public Boolean AuthenticationInformationSave(List<RepairInfo>  RepairInfoList) {
        errorFlag = false;
        for (RepairInfo info : RepairInfoList) {

            List<String> errorMessageList = new List<String>();
            String key = PromptMessage(info.ba, info.lineNumber);
            if (String.isNotBlank(info.ba.serviceType__c)) {

                if (String.isBlank(key)) {
                    continue;
                }
                // 案件完成日
                if (info.ba.BusinessACompletionDate__c != null) {
                    if (info.ba.BusinessACompletionDate__c != tsr.TSReportDate__c) {
                        errorFlag = true;
                        String errorMessage =  '案件完成日只能是报告日期，请确认\n';
                        errorMessageList.add(errorMessage);
                    }
                }

                if ('否'.equals(info.ba.firstInput__c) && String.isBlank(info.ba.User_FaultInfo__c)) {
                    errorFlag = true;
                    String errorMessage =  '请检索有效的管理编码\n';
                    errorMessageList.add(errorMessage);
                }

                Boolean ServiceCategoryIsRepair = info.ba.BusinessAServiceCategory__c == 'Repair';
                // 服务范畴 为 Repair 必填验证
                if (ServiceCategoryIsRepair) {

                    String accountId = info.ba.BusinessAAccount__c;

                    if (String.isBlank(accountId)) {

                        //1> 客户单位 Id 为空 报错
                        errorFlag = true;
                        String errorMessage = '客户单位 名称 为空,请确认\n';
                        errorMessageList.add(errorMessage);
                    }
                    // 4> 根据联系人Id 确认该联系人是否是 客户单位下的联系人
                    String contactId = info.ba.BusinessAContact__c;
                    if (String.isNotBlank(contactId)) {
                        List<Contact> contactList = TSRepairUtil.GetContactList(contactId, null, null, '');
                        if (contactList.size() <= 0) {
                            String errorMessage =  '联系人 无效 请确认\n';
                            errorFlag = true;
                            errorMessageList.add(errorMessage);
                        } else {
                            // 查找联系人 获取 联系人的客户 与客户单位进行比对
                            String contactAccountId = contactList[0].AccountId__c;
                            if (String.isNotBlank(accountId)) {
                                accountId = accountId.substring(0, 15);
                                String contactName = contactList[0].Name;
                                if (!accountId.equals(contactAccountId)) {
                                    String errorMessage = '联系人 [ ' + contactName + ' ] 不是客户下的联系人 请确认\n';
                                    errorFlag = true;
                                    errorMessageList.add(errorMessage);
                                }
                            } else {
                                String errorMessage =  '客户单位为空  联系人无法验证是否有效 请确认\n';
                                errorFlag = true;
                                errorMessageList.add(errorMessage);
                            }


                        }

                    }

                    // 判断日期
                    if (info.ba.BusinessADetermineDate__c != null &&  info.ba.BusinessARepairDate__c != null) {
                        if (info.ba.BusinessARepairDate__c > info.ba.BusinessADetermineDate__c) {
                            // 报错
                            String errorMessage = '判断日期小于报修日期，请确认';
                            errorMessageList.add(errorMessage);
                        }
                    }

                    // 要求服务日期
                    if (info.ba.BusinessADateRequest__c != null && info.ba.BusinessARepairDate__c != null) {
                        if (info.ba.BusinessARepairDate__c > info.ba.BusinessADateRequest__c) {
                            // 报错
                            String errorMessage = '要求服务日期小于报修日期，请确认';

                            errorMessageList.add(errorMessage);
                        }
                    }

                    if (info.ba.BusinessANatureService__c == '有偿') {

                        if (info.ba.BusinessADateApproval__c > tsr.TSReportDate__c) {
                            String errorMessage = '同意报价日期 不能大于报告日期，请确认';
                            errorMessageList.add(errorMessage);
                        }

                        if (info.ba.BusinessADateQuotation__c != null && info.ba.BusinessARepairDate__c != null) {

                            if (info.ba.BusinessADateQuotation__c < info.ba.BusinessARepairDate__c) {
                                String errorMessage = '报价日期 不能早于报修日期，请确认';
                                errorMessageList.add(errorMessage);
                            }

                        }
                    }


                }

            } else {
                //if (String.isNotBlank(info.ba.Id) && tsr.TSRepairFirstSubmission__c != null) {
                //    String errorMessage = '已申请过的业务活动，不可删除';

                //    errorMessageList.add(errorMessage);

                //}
            }

            if ( errorMessageList.size() > 0) {
                errorFlag = true;

                errorMessageMap.put(key, errorMessageList);
            }

        }
        if (errorFlag) {
            pagemessages(errorMessageMap);
            return false;
        }
        return true;
    }

    // TS日报申请时验证活动信息
    public Boolean AuthenticationInformation(List<RepairInfo>  RepairInfoList) {
        errorFlag = false;
        Integer serviceTypeQuantity = 0;
        for (RepairInfo info : RepairInfoList) {

            if (String.isNotBlank(info.ba.serviceType__c)) {
                serviceTypeQuantity = 1;
                String key = PromptMessage(info.ba, info.lineNumber);
                List<String> errorMessageList = new List<String>();
                if (String.isBlank(key)) {
                    continue;
                }
                Boolean isNotZero = info.ba.BusinessACombinedAmount__c != null && info.ba.BusinessACombinedAmount__c != 0 ; //合计台数 不为 0
                String code = info.ba.FindManagementCode__c;
                //若用户在添加完用户故障样机 直接点击 申请中
                Boolean needVerification = false;
                for (FailureAsset__c fa : info.failureAssetList) {
                    //1>若 故障样机 的 机型不为空 我们就要验证
                    if (!needVerification) {
                        if (String.isNotBlank(fa.model__c)) {
                            needVerification = true;
                        }
                    }

                }

                if (String.isBlank(info.ba.BusinessAServiceCategory__c)) {
                    String errorMessage = '服务范畴 不能为空，请确认\n';
                    errorMessageList.add(errorMessage);
                }

                if ('否'.equals(info.ba.firstInput__c) && String.isBlank(info.ba.User_FaultInfo__c)) {
                    errorFlag = true;
                    String errorMessage =  '请检索有效的管理编码\n';
                    errorMessageList.add(errorMessage);
                }
                // 获取当前时间的时间戳
                String timenow = Datetime.now().format('yyyy-MM-dd-HH-mm-ss');
                Long timestampNow = GetTimestamp(timenow, null, null, null);

                if (info.ba.workingHours__c == null || info.ba.workingHours__c <= 0) {
                    errorFlag = true;
                    String errorMessage = '业务活动 工作时间填写错误，请确认\n';
                    errorMessageList.add(errorMessage);
                } else {
                    Integer baEndHour = Integer.valueOf(info.ba.EndTimeHour__c);
                    Integer baEndMinute = Integer.valueOf(info.ba.EndTimeMinute__c);
                    // 获取报告日期
                    Date reportDate = tsr.TSReportDate__c ;
                    Long timestamp = GetTimestamp('', baEndHour, baEndMinute, reportDate);

                    if (timestampNow < timestamp) {
                        errorFlag = true;
                        String errorMessage = '请在今天最终事件结束之后再提交日报';
                        errorMessageList.add(errorMessage);
                    }
                }

                // 案件完成日
                if (info.ba.BusinessACompletionDate__c != null) {

                    if (info.ba.BusinessACompletionDate__c != tsr.TSReportDate__c) {
                        errorFlag = true;
                        String errorMessage =  '案件完成日只能是报告日期，请确认\n';

                        errorMessageList.add(errorMessage);
                    }
                }
                if (info.ba.workingHours__c == null || info.ba.workingHours__c <= 0) {
                    errorFlag = true;
                    String errorMessage =  '工作时间填写错误，请确认\n';
                    errorMessageList.add(errorMessage);
                }

                if (String.isBlank(info.ba.firstInput__c)) {
                    errorFlag = true;
                    String errorMessage =  '首次登录案件 为空，请确认\n';
                    errorMessageList.add(errorMessage);
                }

                if (String.isBlank(info.ba.BusinessAServiceContentNew__c)) {
                    errorFlag = true;
                    String errorMessage =  '服务内容 为空，请确认\n';
                    errorMessageList.add(errorMessage);
                }
                Boolean ServiceCategoryIsRepair = info.ba.BusinessAServiceCategory__c == 'Repair';
                Boolean ServiceCategoryIsSevice = info.ba.BusinessAServiceCategory__c == 'Sevice';
                // 服务范畴 为 Repair 必填验证
                if (ServiceCategoryIsRepair) {


                    String accountId = info.ba.BusinessAAccount__c;
                    if (String.isBlank(accountId)) {
                        // 1> 客户单位 名称 为空 报错 // 2> 客户单位 Id 为空 报错
                        errorFlag = true;
                        String errorMessage = '客户单位 名称 为空,请确认\n';
                        errorMessageList.add(errorMessage);
                    }
                    // 4> 根据联系人Id 确认该联系人是否是 客户单位下的联系人
                    String contactId = info.ba.BusinessAContact__c;
                    if (String.isNotBlank(contactId)) {
                        List<Contact> contactList = TSRepairUtil.GetContactList(contactId, null, null, '');
                        if (contactList.size() <= 0) {
                            String errorMessage =  '联系人 无效 请确认\n';
                            errorFlag = true;
                            errorMessageList.add(errorMessage);
                        } else {
                            // 查找联系人 获取 联系人的客户 与客户单位进行比对
                            String contactAccountId = contactList[0].AccountId__c;
                            if (String.isNotBlank(accountId)) {
                                accountId = accountId.substring(0, 15);
                                String contactName = contactList[0].Name;
                                if (!accountId.equals(contactAccountId)) {
                                    String errorMessage = '联系人 [ ' + contactName + ' ] 不是客户下的联系人 请确认';

                                    errorFlag = true;
                                    errorMessageList.add(errorMessage);
                                }
                            } else {
                                String errorMessage =  '客户单位为空  联系人无法验证是否有效 请确认';
                                errorFlag = true;
                                errorMessageList.add(errorMessage);
                            }


                        }

                    } else {
                        String errorMessage =  '联系人为空 请确认';
                        errorFlag = true;
                        errorMessageList.add(errorMessage);
                    }

                    // 验证故障样机 必填字段
                    if (info.failureAssetList.size() > 0 ) {
                        for (FailureAsset__c fa : info.failureAssetList) {
                            // 机型
                            if (String.isNotBlank(fa.model__c)) {
                                // 产品系列
                                if (String.isBlank(fa.FAProductSeries__c)) {
                                    errorFlag = true;
                                    String errorMessage =  '机型 [ ' + fa.model__c + ' ] 产品系列为空，请确认';
                                    errorMessageList.add(errorMessage);
                                }
                                // 保修状态
                                if (String.isBlank(fa.WarrantyStatus__c) ) {
                                    errorFlag = true;
                                    String errorMessage =  '机型 [ ' + fa.model__c + ' ] 保修状态为空，请确认';
                                    errorMessageList.add(errorMessage);
                                }
                            }
                        }

                    } else {
                        // 错误提醒
                        String errorMessage = '未填写故障机器，请确认';
                        errorMessageList.add(errorMessage);
                    }

                    // 故障内容
                    if ( String.isBlank(info.ba.BusinessAFaultContent__c)) {
                        errorFlag = true;
                        String errorMessage =  '故障内容为空 请确认';
                        errorMessageList.add(errorMessage);
                    }
                    // 报修日期
                    if (info.ba.BusinessARepairDate__c == null) {
                        // 报错
                        String errorMessage = '报修日期为空，请确认';
                        errorMessageList.add(errorMessage);
                    }
                    // 判断日期
                    if (info.ba.BusinessADetermineDate__c == null) {
                        // 报错
                        String errorMessage = '判断日期为空，请确认';
                        errorMessageList.add(errorMessage);
                    } else {
                        if (info.ba.BusinessARepairDate__c > info.ba.BusinessADetermineDate__c) {
                            // 报错
                            String errorMessage = '判断日期小于报修日期，请确认';
                            errorMessageList.add(errorMessage);
                        }
                    }
                    // 要求服务日期
                    if (info.ba.BusinessADateRequest__c == null) {
                        String errorMessage = '要求服务日期为空，请确认';

                        errorMessageList.add(errorMessage);
                    } else {
                        if (info.ba.BusinessARepairDate__c > info.ba.BusinessADateRequest__c) {
                            // 报错
                            String errorMessage = '要求服务日期小于报修日期，请确认';

                            errorMessageList.add(errorMessage);
                        }
                    }
                    // 信息来源
                    if (String.isBlank(info.ba.BusinessAMessageSource__c)) {
                        // 报错
                        String errorMessage = '信息来源为空，请确认';

                        errorMessageList.add(errorMessage);
                    }
                    // 服务性质
                    if (String.isBlank(info.ba.BusinessANatureService__c)) {
                        // 报错
                        String errorMessage = '服务性质为空，请确认';

                        errorMessageList.add(errorMessage);
                    } else {
                        // 无偿原因
                        if (info.ba.BusinessANatureService__c == '无偿' && String.isBlank(info.ba.BusinessAWithoutReason__c)) {
                            // 报错
                            String errorMessage = '无偿原因为空，请确认';

                            errorMessageList.add(errorMessage);

                        } else if (info.ba.BusinessANatureService__c == '有偿' && info.ba.BusinessADateApproval__c == null && info.ba.BusinessACompletionDate__c != null) {// 服务范畴为Repair，[服务性质]="有偿"，案件完成日不为空的情况下
                            // 报错
                            String errorMessage = '同意报价日期为空，请确认';

                            errorMessageList.add(errorMessage);
                        } else if (info.ba.BusinessANatureService__c == '有偿' ) {

                            // 同意报价日期
                            if ( info.ba.BusinessADateApproval__c > tsr.TSReportDate__c) {
                                String errorMessage = '同意报价日期 不能大于报告日期，请确认';

                                errorMessageList.add(errorMessage);
                            }

                            if (info.ba.BusinessADateQuotation__c == null ) {
                                String errorMessage = '报价日期 不能为空，请确认';

                                errorMessageList.add(errorMessage);
                            } else {
                                // 报价日期
                                if (info.ba.BusinessADateQuotation__c < info.ba.BusinessARepairDate__c) {
                                    String errorMessage = '报价日期 不能早于报修日期，请确认';

                                    errorMessageList.add(errorMessage);
                                }
                            }
                        }

                    }
                    // 服务场所
                    if (String.isBlank(info.ba.BusinessAServicePlace__c)) {
                        errorFlag = true;
                        String errorMessage =  '服务场所 为空，请确认';
                        errorMessageList.add(errorMessage);
                    }
                }
                if (ServiceCategoryIsRepair || ServiceCategoryIsSevice) {
                    Boolean  cmpletionDateIsNotNull = info.ba.BusinessACompletionDate__c != null;//案件完成日
                    // 服务结果
                    if (cmpletionDateIsNotNull && String.isBlank(info.ba.BusinessAServiceResult__c)) {
                        errorFlag = true;
                        String errorMessage =  '服务结果 为空，请确认';
                        errorMessageList.add(errorMessage);
                    }
                }

                if ( errorMessageList.size() > 0) {
                    errorFlag = true;

                    errorMessageMap.put(key, errorMessageList);
                }
            }

        }


        if (serviceTypeQuantity == 0) {
            errorFlag = true;
            String errorMessage =  '所有业务活动的服务类型都为空，提交失败，请确认';
            List<String> errorMessageList = new List<String>();
            errorMessageList.add(errorMessage);
            errorMessageMap.put('TS日报异常', errorMessageList);

        }

        if (errorFlag) {
            pagemessages(errorMessageMap);
            return false;
        }
        return true;
    }

    // 提示信息标记
    public String PromptMessage(BusinessActivity__c ba, Integer lineNumber) {

        String result = '';

        // 业务活动管理编码
        String code = ba.FindManagementCode__c;
        // 业务活动Id
        String baId = ba.Id;

        if (String.isNotBlank(baId)) {
            if (String.isNotBlank(code)) {
                result = code;
            } else {
                result = String.valueOf(lineNumber + 1) ;
            }
        } else {
            result = String.valueOf(lineNumber + 1);
        }

        return result;
    }

    public class RepairInfo {

        public BusinessActivity__c ba {get; set;} //业务活动
        public User_FaultInfo__c uf {get; set;}  //用户故障信息
        public List<FailureAsset__c> failureAssetList {get; set;} //故障样机
        public List<Attachment> attachmentLsit {get; set;}//附件信息
        public String baServiceType {get; set;} //服务类型
        public Integer lineNumber {get; set;}
        public String BusinessActivityId {get; set;} //业务活动Id
        public Boolean disabled {get; set;}//添加产品 按钮 禁用
        public Boolean firstSubmission {get; private set;}
        public Boolean approvalOpinionDisabled {get; set;} //审批意见/意见 不可修改
        public String firstinputOriginalValue {get; set;} // 首次登陆案件
        public RepairInfo (TS_Repair__c tsr, BusinessActivity__c ba_in , User_FaultInfo__c uf_in , List<FailureAsset__c> faList , Integer num_in, List<Attachment> attachments) {
            ba = ba_in;
            baServiceType = ba.serviceType__c;
            firstinputOriginalValue = ba.firstInput__c;
            BusinessActivityId = ba.Id;
            uf = uf_in;
            failureAssetList = faList;
            attachmentLsit = attachments;
            lineNumber = num_in;
            firstSubmission = false;
            String  firstSubmissionStr = String.valueOf(ba.BusinessAFirstSubmission__c);
            if (String.isNotBlank(firstSubmissionStr)) {
                firstSubmission = true;
            }

            Integer maxFailureAssetListSize = Integer.valueOf(System.label.TSRepairPageMaxFailureAssetListSize);
            if (faList == null || faList.size() < maxFailureAssetListSize) {
                disabled = false;
            } else {
                disabled = true;
            }
            //用户不是TS日报创建人的上级，审批意见、意见 不可修改
            if (tsr.TSRepairSuperior__c != UserInfo.getUserId()) {
                approvalOpinionDisabled = true;
            }
        }

    }
}