using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Request;
using Siger.Middlelayer.Log;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace Siger.ApiTPM.Utilities
{
    public class AppRepairHelper
    {
        private readonly int _projectId;
        private readonly int _userId;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IRepairRepository _repairRepository;
        private readonly IPlanRepository _planRepository;
        private readonly ISigerUserRepository _sigerUserRepository;
        private readonly IRepairListRepository _repairListRepository;
        private readonly IRepairReportRepository _repairReportRepository;
        private readonly IWorkingCalendarRepository _calendarRepository;
        private readonly ISigerProjectShiftRepository _projectShiftRepository;
        private readonly ISigerSystemConfigRepository _systemConfigRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly ISigerAppMessageRepository _sigerAppMessage;
        private readonly ISigerProjectUserRepository _projectUserRepository;
        private readonly ISigerAppProjectConfigRepository _configRepository;
        private readonly ISigerAppMuteRepository _appMuteRepository;
        private readonly ISigerAndonInfoRepository _andonInfoRepository;
        private readonly ISigerAndonExpectionTypeRepository _expectionTypeRepository;
        //private readonly IWorkingMachineSetRepository _machineSetRepository;
        private readonly IWorkingRelationUserRepository _workingRelationUser;
        private readonly IWorkingRelationMachineRepository _workingRelationMachine;

        public AppRepairHelper(AppRepairCondition condition)
        {
            _projectId = condition.projectId;
            _userId = condition.userId;
            _unitOfWork = condition.unitOfWork;
            _repairRepository = condition.repairRepository;
            _planRepository = condition.planRepository;
            _sigerUserRepository = condition.sigerUserRepository;
            _repairListRepository = condition.repairListRepository;
            _repairReportRepository = condition.repairReportRepository;
            _calendarRepository = condition.calendarRepository;
            _projectShiftRepository = condition.projectShiftRepository;
            _systemConfigRepository = condition.systemConfigRepository;
            _machineRepository = condition.machineRepository;
            _sigerAppMessage = condition.sigerAppMessage;
            _projectUserRepository = condition.projectUserRepository;
            _configRepository = condition.configRepository;
            _appMuteRepository = condition.appMuteRepository;
            _andonInfoRepository = condition.andonInfoRepository;
            _expectionTypeRepository = condition.expectionTypeRepository;
            //_machineSetRepository = condition.machineSetRepository;
            _workingRelationMachine = condition.workingRelationMachine;
            _workingRelationUser = condition.workingRelationUser;
        }

        public async Task<bool> SubmitRepairAsync(RequestSubmitRepair req)
        {
            return await Task.Run(() => SubmitRepair(req));
        }

        public bool SubmitRepair(RequestSubmitRepair req)
        {
            if (req.machineid == 0)
            {
                throw new ServerException(900027);
            }

            if (!string.IsNullOrEmpty(req.remark) && RegexHelper.InputRegex(req.remark))
            {
                throw new ServerException(800064);
            }
            
            var time = UnixTimeHelper.GetNow();
            var userSectionType = _repairRepository.GetSectionByUserId(_userId);
            if (userSectionType == null)
            {
                throw new ServerException(900706);
            }

            if (req.real_faultid != 0)
            {
                var repairs = _repairRepository.GetList(t => t.machineid == req.machineid && t.real_faultid == req.real_faultid && t.projectid == _projectId
                    && t.status > 0 && t.status < (int)MachineRepairStatus.Completed).ToList();
                if (repairs.Any())
                {
                    throw new ServerException(1057);
                }
            }
            
            var userRelation = _workingRelationUser.Get(f => f.projectid == _projectId && f.employ==_userId);
            if (userRelation == null)
            {
                throw new ServerException(700074);
            }
            var machineRelation = _workingRelationMachine.Get(f => f.projectid == _projectId && f.machine == req.machineid && f.workgroup_id==userRelation.workgroup_id);
            if (machineRelation == null)
            {
                throw new ServerException(700074);
            }


            //检查报修权限
            var cals = _calendarRepository.GetList(q => q.date.Date == DateTime.Now.Date && q.working_group== machineRelation.workgroup_id && q.user_mid == _userId && q.project_id == _projectId);
            //var cals = _calendarRepository.GetList(q => q.date.Date == DateTime.Now.Date && q.machine_id == req.machineid && q.user_mid == _userId && q.project_id == _projectId);
            if (!cals.Any())
            {
                throw new ServerException(700074); 
            }
            var nowDate = UnixTimeHelper.GetUnixByDate(DateTime.Now.ToShortDateString());
            var flag = false;
            foreach (var cal in cals.ToList())
            {
                var shift = _projectShiftRepository.Get(q => q.id == cal.shift_id && q.projectid == _projectId && q.status == (int)RowState.Valid);
                if(shift != null)
                {
                    //零点到零点的，全部都算
                    if (shift.start_time == 0 && shift.end_time == 0)
                    {
                        flag = true;
                        break;
                    }
                    //在时间范围内的
                    else if (nowDate + shift.start_time <= time && nowDate + shift.end_time >= time)
                    {
                        flag = true;
                        break;
                    }
                    //结束时间小于开始时间
                    else if (shift.end_time <= shift.start_time)
                    {
                        if (nowDate + shift.start_time <= time)
                        {
                            flag = true;
                            break;
                        }
                    }
                }
            }
            if (!flag)
            {
                throw new ServerException(700074);
            }
            var addRepair = new siger_project_repair
            {
                remark = req.remark ?? "",
                machineid = req.machineid,
                mid = _userId,
                status = 1,
                createtime = time,
                projectid = _projectId,
                offlinestatus = req.offlinestatus,
                images = req.images ?? "",
                report_level = 0,
                faultid = req.faultid > 0 ? req.faultid : 0,
                real_faultid = req.real_faultid > 0 ? req.real_faultid : 0,
                work_order = req.work_order.ToStr(),
                expection_id = req.expection_id > 0 ? req.expection_id : 0,
            };
            _repairRepository.Insert(addRepair);
            if (_unitOfWork.Commit() > 0)
            {
                var isTranslate = _planRepository.GetProjectLanguage(_projectId) == (int)LanguageType.EN;
                var translateHelper = new TranslateHelper(isTranslate);
                var addRepairList = new siger_project_repair_list
                {
                    repairid = addRepair.id,
                    projectid = _projectId,
                    mid = _userId,
                    title = ((int)RepairListStatus.TobeTaken).ToString(),
                    status = (int)MachineRepairStatus.WaitingForOrders
                };

                var userType = "";
                var userName = "";

                if (userSectionType != null)
                {
                    userType = userSectionType.type == (int)SectionType.Maintenance
                        ? translateHelper.GetTranslateText(TranslateEnEnum.MaintenanceStaff)
                        : translateHelper.GetTranslateText(TranslateEnEnum.ProductionStaff);
                }

                var userInfo = _sigerUserRepository.Get(t => t.id == _userId);
                if (userInfo != null)
                {
                    userName = userInfo.nickname + "(" + userInfo.mobile + ")";
                }

                addRepairList.content = userType + userName +
                                        translateHelper.GetTranslateText(TranslateEnEnum
                                            .RepairReportWorkOrderGenerated);
                addRepairList.creattime = time;
                _repairListRepository.Insert(addRepairList);
                var fault = "";
                var locationHelper = new MachineLocationHelper(_projectId, _planRepository);
                var location = string.Join('-', locationHelper.GetPositionByMachineId(req.machineid));
                if (_unitOfWork.Commit() > 0)
                {
                    if (string.IsNullOrEmpty(addRepair.work_order))
                    {
                        var model = _repairRepository.Get(f => f.id == addRepair.id);
                        model.work_order = model.id.ToStr();
                        _repairRepository.Update(model);
                        if (_unitOfWork.Commit() <= 0)
                        {
                            throw new BadRequestException(CommonEnum.Fail);
                        }
                    }
                    if (req.real_faultid > 0)
                    {
                        var machineFault = _repairRepository.GetMachineFaultByFaultId(req.real_faultid, _projectId).ToList();
                        if (machineFault.Any())
                        {
                            var faultlist = machineFault[0].title;
                            fault = faultlist;
                            //var machineFault1 = _repairRepository.GetMachineFaultByFaultId(req.real_faultid, _projectId)
                            //    .ToList();
                            //if (machineFault1.Any())
                            //{
                            //    var faultcontent = machineFault1[0].title;
                            //    fault += " - " + faultcontent;
                            //}
                        }
                    }

                    fault = string.IsNullOrWhiteSpace(fault)
                        ? "- " + translateHelper.GetTranslateText(TranslateEnEnum.Other) + "-"
                        : fault;
                    var content = "【" + location + "】" + fault;
                    var paras = new Dictionary<string, string>
                    {
                        { "location",  location},
                        { "fault",  fault}
                    };
                    SendMessage(addRepair.id, req.machineid, (int)MachineRepairStatus.WaitingForOrders,
                        translateHelper.GetTranslateText(TranslateEnEnum.TobeTaken), content, 1, _userId,
                        SMSTemplateConst.WaitingForOrders, isTranslate, paras);
                }
                return true;
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        public bool CloseRepair(RequestDataByRepairId req)
        {
            if (req.repairid == 0)
            {
                throw new ServerException(900027);
            }
            var repairInfo = _repairRepository.Get(t => t.projectid == _projectId && t.id == req.repairid);
            if (repairInfo == null)
            {
                throw new ServerException(100282);
            }
            if (repairInfo.status > (int)MachineRepairStatus.WaitingForRepair || repairInfo.status == 0)
            {
                throw new ServerException(900708);
            }
            var userSectionType = _repairRepository.GetSectionByUserId(_userId);
            if (userSectionType == null)
            {
                throw new ServerException(100283);
            }
            var time = UnixTimeHelper.GetNow();
            //var machineIds = _machineSetRepository.GetList(q =>
            //        q.user_mid == _userId && q.project_id == _projectId && q.status == (int)RowState.Valid).Select(q => q.machine_id)
            //    .Distinct().ToList();

            var userRelation = _workingRelationUser.Get(f => f.employ == _userId && f.projectid == _projectId && f.status == (int)RowState.Valid);
            var machineIds = userRelation != null ? userRelation.machineSplit : new List<int>();

            //获取报修/接单/签到人
            var midList = new List<int>
            {
                repairInfo.mid,
                repairInfo.takemid,
                repairInfo.signmid,
                repairInfo.completemid,
                repairInfo.checkmid
            };
            //获取合作维修人员
            var repairadd = _repairRepository.GetAddUserListByRepairId(req.repairid).ToList();
            if (repairadd.Any())
            {
                foreach (var addRepair in repairadd)
                {
                    midList.Add(addRepair.mid);
                }
            }
            midList = midList.Where(t => t > 0).Distinct().ToList();
            var repairListInfo = new siger_project_repair_list
            {
                repairid = req.repairid,
                projectid = _projectId,
                mid = _userId,
                status = 0
            };
            var isTranslate = _planRepository.GetProjectLanguage(_projectId) == (int)LanguageType.EN;
            var translateHelper = new TranslateHelper(isTranslate);
            var userType = "";
            var userName = "";
            if (userSectionType != null)
            {
                userType = userSectionType.type == (int)SectionType.Maintenance
                    ? translateHelper.GetTranslateText(TranslateEnEnum.MaintenanceStaff)
                    : translateHelper.GetTranslateText(TranslateEnEnum.ProductionStaff);
            }
            var userInfo = _sigerUserRepository.Get(t => t.id == _userId);
            if (userInfo != null)
            {
                userName = userInfo.nickname + "(" + userInfo.mobile + ")";
            }
            var newRepairInfo = repairInfo;
            //userSectionType.type == (int)SectionType.ProduceSection &&
            if (machineIds.Contains(repairInfo.machineid) || midList.Contains(_userId))
            {
                newRepairInfo.status = 0;
                newRepairInfo.repairmid = _userId;
                newRepairInfo.repairtime = time;
                newRepairInfo.repair_remark = req.remark;
                //工单详情记录
                repairListInfo.title = ((int)RepairListStatus.WorkOrderCancelled).ToString();
                repairListInfo.content = userType + userName +
                                         translateHelper.GetTranslateText(TranslateEnEnum
                                             .MaintenanceOrderCancelledMaintenanceOrderClosed);
                //推送
                var locationHelper = new MachineLocationHelper(_projectId, _planRepository);
                var location = string.Join('-', locationHelper.GetPositionByMachineId(repairInfo.machineid));
                var content = "【" + location + "】" + "，" + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum.WorkOrderBeCancelled);

                _repairRepository.Update(newRepairInfo);
                //工单记录
                repairListInfo.creattime = time;
                _repairListRepository.Insert(repairListInfo);
                if (_unitOfWork.Commit() > 0)
                {
                    var paras = new Dictionary<string, string> { { "location", location }, { "username", userName } };
                    SendMessage(req.repairid, repairInfo.machineid, newRepairInfo.status,
                        translateHelper.GetTranslateText(TranslateEnEnum.WorkOrderCancelled), content, 1, _userId,
                        SMSTemplateConst.Deleted, isTranslate, paras);
                    return true;
                }
                else
                {
                    throw new ServerException(900651);
                }
            }
            else
            {
                throw new ServerException(900706);
            }
        }
        private void SendMessage(int repairid, int machineid, int status, string title, string content, int level,
            int mymid, int templateId, bool isTranslate, Dictionary<string, string> paras)
        {
            //根据工单状态查询midlist
            var repairInfo = _repairRepository.Get(t => t.id == repairid && t.projectid == _projectId);
            if (repairInfo == null)
            {
                throw new ServerException(100282);
            }

            var time = UnixTimeHelper.GetNow();
            
            var repairReportLevelHelper =
                new RepairReportLevelHelper(_projectId, _repairRepository, _repairReportRepository, _calendarRepository, _projectShiftRepository,_workingRelationUser,_workingRelationMachine);
            var config = _systemConfigRepository.Get(q =>
                 q.key == SystemConfigKey.MessageRepeatTime && q.status == (int)RowState.Valid);
            var configTime = (config != null ? config.value : "15").ToInt();
            //查询推送人员
            var machine = _machineRepository.Get(t => t.id == repairInfo.machineid);
            var machinelevel = 1;
            if (machine != null)
            {
                machinelevel = machine.machinelevel > 0 ? machine.machinelevel : 1;
            }
            var midList = repairReportLevelHelper.GetReportPushAndSectionMidList(repairInfo, machineid, time, configTime, level, _projectId, machinelevel);
            var messagepush = new PushHelper(_projectId, _sigerAppMessage, _projectUserRepository, _configRepository);
            var sectionMidList = midList[(int)AppPushType.SaveNotPush];
            var reportMidList = midList[(int)AppPushType.PushAndSave];
            //foreach (var mid in sectionMidList)
            foreach (var mid in reportMidList)
            {
                if (mid == mymid || mid <= 0)
                {
                    continue;
                }

                //if (!reportMidList.Contains(mid))
                //{
                //    continue;
                //}
                try
                {
                    if (isTranslate)
                    {
                        templateId = TemplateHelper.GetSmsEnTemplateId(templateId);
                    }
                    var mute = _appMuteRepository.Get(t =>
                        t.projectid == _projectId && t.status == 0 && (t.repairid == repairid || t.repairid == 0) &&
                        t.mid == mid);
                    var isPush = mute == null;
                    if (templateId > 0 && isPush)
                    {
                        var messageInfo = new siger_app_project_message
                        {
                            tomid = mid,
                            projectid = _projectId,
                            repairid = repairid,
                            create_time = time,
                            type = (int)RepairOrPlanStatus.Repair,
                            title = title,
                            content = content,
                            read_sign = 0,
                            status = status,
                        };
                        messagepush.Push(messageInfo, isPush, templateId, paras);
                        SendWeXinMessage(messageInfo.title, messageInfo.content, time, messageInfo.tomid,
                            TemplateHelper.GetWxTempleteId(isTranslate));
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteLineError("push message error :" + ex);
                }
            }
        }
        private void SendWeXinMessage(string title, string content, int time, int tomid, string templeteId)
        {
            if (tomid == 0)
            {
                return;
            }

            var date = UnixTimeHelper.ConvertIntDateTime(time);

            var openid = _planRepository.GetUserOpenId(tomid, _projectId);
            if (string.IsNullOrEmpty(openid))
            {
                return;
            }

            MessageBean msgcont = new MessageBean();

            ContBean prmBean = new ContBean
            {
                value = title,
                color = "#173177"
            };

            msgcont.firstPrm = prmBean;

            List<ContBean> datas = new List<ContBean>();
            prmBean = new ContBean
            {
                value = date,
                color = "#173177"
            };
            datas.Add(prmBean);

            prmBean = new ContBean
            {
                value = content,
                color = "#173177"
            };
            datas.Add(prmBean);

            msgcont.keywordsPrm = datas;

            prmBean = new ContBean
            {
                value = "",
                color = "#173177"
            };
            msgcont.remarkPrm = prmBean;

            WeChatPushHelper.sendMsg(openid, templeteId, msgcont);
        }

        public bool RecoveryLine(RequestRepairExecution req)
        {
            var userSectionType = _repairRepository.GetSectionByUserId(_userId);
            //var machineIds = _machineSetRepository.GetList(q =>
            //        q.user_mid == _userId && q.project_id == _projectId && q.status == (int)RowState.Valid).Select(q => q.machine_id)
            //    .Distinct().ToList();
            var userRelation = _workingRelationUser.Get(f => f.employ == _userId && f.projectid == _projectId && f.status == (int)RowState.Valid);
            var machineIds = userRelation != null ? userRelation.machineSplit : new List<int>();

            var repairInfo = _repairRepository.Get(t => t.projectid == _projectId && t.id == req.repairid);
            //获取报修/接单/签到人
            var midList = new List<int>
            {
                repairInfo.mid,
                repairInfo.takemid,
                repairInfo.signmid,
                repairInfo.completemid,
                repairInfo.checkmid
            };
            //获取合作维修人员
            var repairAddUser = _repairRepository.GetAddUserListByRepairId(req.repairid).ToList();
            if (repairAddUser.Any())
            {
                midList.AddRange(repairAddUser.Select(t => t.mid).Distinct().ToList());
            }
            midList = midList.Where(t => t > 0).Distinct().ToList();
            var newRepairInfo = repairInfo;
            newRepairInfo.offlinestatus = req.is_shutdown;
            //推送信息
            var time = UnixTimeHelper.GetNow();
            var locationHelper = new MachineLocationHelper(_projectId, _planRepository);
            var location = string.Join('-', locationHelper.GetPositionByMachineId(repairInfo.machineid));
            var pushTitle = "";
            var paras = new Dictionary<string, string>();
            var repairListInfo = new siger_project_repair_list
            {
                repairid = req.repairid,
                projectid = _projectId,
                mid = _userId,
                status = req.repairstatus + 1
            };
            var isTranslate = _planRepository.GetProjectLanguage(_projectId) == (int)LanguageType.EN;
            var translateHelper = new TranslateHelper(isTranslate);
            var userType = "";
            var userName = "";
            if (userSectionType != null)
            {
                userType = userSectionType.type == (int)SectionType.Maintenance
                    ? translateHelper.GetTranslateText(TranslateEnEnum.MaintenanceStaff)
                    : translateHelper.GetTranslateText(TranslateEnEnum.ProductionStaff);
            }
            var userInfo = _sigerUserRepository.Get(t => t.id == _userId);
            if (userInfo != null)
            {
                userName = userInfo.nickname + "(" + userInfo.mobile + ")";
            }
            //待基础配置设备绑定正确后放开此处代码
            if (userSectionType?.type == (int)SectionType.ProduceSection && (machineIds.Contains(repairInfo.machineid) || midList.Contains(_userId)))
            {
                var content = "";
                var templateId = 0;
                if (req.checkstatus == 1)
                {
                    newRepairInfo.status = (int)MachineRepairStatus.WaitingForFeedback;
                    newRepairInfo.report_level = 0;
                    newRepairInfo.checktime = time;
                    newRepairInfo.checkmid = _userId;
                    //newRepairInfo.offlinestatus = 0;
                    newRepairInfo.appraise = req.appraise.ToInt();
                    //工单详情记录
                    repairListInfo.title = ((int)RepairListStatus.TobeFeedBack).ToString();
                    repairListInfo.content = userType + " " + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum.ConfirmedRestoreProductionLine);
                    //推送信息
                    content = "【" + location + "】" + "，" + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum.ConfirmedRestoreProductionLine);
                    templateId = SMSTemplateConst.WaitingForFeedback;
                    paras.Add("location", location);
                    paras.Add("userName", userName);
                }
                else if (req.checkstatus == 2)//让步复线
                {
                    newRepairInfo.status = (int)MachineRepairStatus.WaitingForFeedback;
                    pushTitle = translateHelper.GetTranslateText(TranslateEnEnum.ConcessionRecovered);
                    newRepairInfo.report_level = 0;
                    newRepairInfo.checktime = time;
                    newRepairInfo.checkmid = _userId;
                    newRepairInfo.appraise = req.appraise.ToInt();
                    //工单详情记录
                    repairListInfo.title = ((int)RepairListStatus.ConcessionRecovered).ToString();
                    repairListInfo.content = userType + " " + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum.ConcessionRecoveredGeneratingWorkOrder);
                    //推送信息
                    content = "【" + location + "】" + "，" + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum.ConcessionRecoveredGeneratingWorkOrder);
                    templateId = SMSTemplateConst.WaitingForFeedback;
                    paras.Add("location", location);
                    paras.Add("userName", userName);
                    _repairRepository.Update(newRepairInfo);
                    //工单记录
                    repairListInfo.creattime = time;
                    _repairListRepository.Insert(repairListInfo);
                    var expectiontype = _andonInfoRepository.Get(f => f.work_order == repairInfo.work_order && f.status != (int)RowState.Invalid)?.expection_type ?? 0;
                    var expection = _expectionTypeRepository.Get(f => f.id == expectiontype);
                    var expectionName = string.Empty;
                    if (expection != null)
                    {
                        if (expection.level <= 2)
                        {
                            expectionName = expection.name;
                        }
                        else
                        {
                            var parentexpection = _expectionTypeRepository.Get(f => f.id == expection.parent);
                            expectionName = parentexpection != null ? parentexpection.name : "";
                        }
                    }

                    var workorderList = repairInfo.work_order.Split('_');
                    var workorder = repairInfo.work_order;
                    if (workorderList.Count() > 2)
                    {
                        workorder = $"{workorderList[0]}_{workorderList[1]}_{workorderList[2].ToInt() + 1}";
                    }
                    else if (workorderList.Count() == 2)
                    {
                        workorder = $"B{repairInfo.work_order.TrimStart('A')}_1";
                    }
                    var relateRepair = new siger_project_repair
                    {
                        remark = $"{repairInfo.work_order},{expectionName} {translateHelper.GetTranslateText(TranslateEnEnum.ConcessionRecoveredGeneratingWorkOrder)}",
                        machineid = newRepairInfo.machineid,
                        //sectionid = sectionid > 0 ? sectionid : (newRepairInfo.sectionid > 0 ? newRepairInfo.sectionid : 0),
                        mid = _userId,
                        status = (int)MachineRepairStatus.WaitingForOrders,
                        createtime = time,
                        projectid = _projectId,
                        offlinestatus = newRepairInfo.offlinestatus,
                        images = "",
                        report_level = 0,
                        faultid = newRepairInfo.faultid,
                        real_faultid = newRepairInfo.real_faultid,
                        relate_repairid = newRepairInfo.id,
                        work_type = (int)WorkCode_Type.afterRepair,
                        work_order = workorder,
                        expection_id= repairInfo.expection_id
                    };
                    _repairRepository.Insert(relateRepair);
                    if (_unitOfWork.Commit() > 0 && templateId > 0)
                    {
                        paras.Add("repairid", relateRepair.id + "");
                        //消息推送
                        SendMessage(req.repairid, repairInfo.machineid, newRepairInfo.status, pushTitle, content + " " + relateRepair.id, 1, _userId, templateId, isTranslate, paras);

                        repairListInfo.relate_repairid = relateRepair.id;
                        newRepairInfo.relate_repairid = relateRepair.id;
                        //故障类型 失效模式
                        var relate_fault = "";
                        if (relateRepair.faultid > 0)
                        {
                            var machineFault = _repairRepository.GetMachineFaultByFaultId(relateRepair.faultid, _projectId).ToList();
                            if (machineFault.Any())
                            {
                                var faultlist = machineFault[0].title;
                                relate_fault = faultlist;
                                var machineFault1 = _repairRepository.GetMachineFaultByFaultId(relateRepair.real_faultid, _projectId)
                                    .ToList();
                                if (machineFault1.Any())
                                {
                                    var faultcontent = machineFault1[0].title;
                                    relate_fault += " - " + faultcontent;
                                }
                            }
                        }
                        relate_fault = string.IsNullOrWhiteSpace(relate_fault)
                            ? "- " + translateHelper.GetTranslateText(TranslateEnEnum.Other) + "-"
                            : relate_fault;
                        var relate_content = "【" + location + "】" + relate_fault;
                        var relate_paras = new Dictionary<string, string>
                                    {
                                        { "location",  location},
                                        { "fault",  relate_fault}
                                    };
                        var repairList_content = userType + userName + translateHelper.GetTranslateText(TranslateEnEnum
                                .RepairReportWorkOrderGenerated);
                        var addRepairList = new siger_project_repair_list
                        {
                            mid = _userId,
                            repairid = relateRepair.id,
                            relate_repairid = newRepairInfo.id,
                            content = repairList_content,
                            title = ((int)RepairListStatus.TobeTaken).ToString(),
                            creattime = UnixTimeHelper.GetNow(),
                            projectid = _projectId
                        };
                        _repairListRepository.Insert(addRepairList);
                        var relate_title = translateHelper.GetTranslateText(TranslateEnEnum.TobeTaken);
                        if (_unitOfWork.Commit() > 0)
                        {
                            //消息推送
                            SendMessage(relateRepair.id, repairInfo.machineid, (int)MachineRepairStatus.WaitingForOrders, relate_title, relate_content, 1, _userId
                                , templateId, isTranslate, relate_paras);
                        }
                        return true;
                    }
                    else
                    {
                        throw new ServerException(900651);
                    }
                }
                else
                {
                    newRepairInfo.status = (int)MachineRepairStatus.WaitingForRepair;
                    pushTitle = translateHelper.GetTranslateText(TranslateEnEnum.UnderRepair);
                    newRepairInfo.report_level = 0;
                    newRepairInfo.appraise = req.appraise.ToInt();
                    //工单详情记录
                    repairListInfo.title = ((int)RepairListStatus.UnderRepair).ToString();
                    repairListInfo.content =
                        userType + " " + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum
                            .NoRewiringMaintenanceStaffPleaseContinueMaintenance);
                    //推送信息
                    content = "【" + location + "】" + "，" + userName + " " + translateHelper.GetTranslateText(
                                  TranslateEnEnum.NoMultipleConnectionPleaseContinueMaintenance);
                    templateId = SMSTemplateConst.RenewFail;
                    paras.Add("location", location);
                    paras.Add("username", userName);
                }
                //工单记录
                repairListInfo.creattime = time;
                _repairListRepository.Insert(repairListInfo);
                _repairRepository.Update(newRepairInfo);
            }
            else
            {
                throw new ServerException(900706);
            }
            return true;
        }
    }

    public class AppRepairCondition
    {
        public int projectId { get; set; }
        public int userId { get; set; }
        public IRepairRepository repairRepository { get; set; }
        public IUnitOfWork unitOfWork { get; set; }
        public IPlanRepository planRepository { get; set; }
        public ISigerUserRepository sigerUserRepository { get; set; }
        public IRepairListRepository repairListRepository { get; set; }
        public IRepairReportRepository repairReportRepository { get; set; }
        public IWorkingCalendarRepository calendarRepository { get; set; }
        public ISigerProjectShiftRepository projectShiftRepository { get; set; }
        public ISigerSystemConfigRepository systemConfigRepository { get; set; }
        public ISigerProjectMachineRepository machineRepository { get; set; }
        public ISigerAppMessageRepository sigerAppMessage { get; set; }
        public ISigerProjectUserRepository projectUserRepository { get; set; }
        public ISigerAppProjectConfigRepository configRepository { get; set; }
        public ISigerAppMuteRepository appMuteRepository { get; set; }
        public ISigerAndonInfoRepository andonInfoRepository { get; set; }
        public ISigerAndonExpectionTypeRepository expectionTypeRepository { get; set; }
        //public IWorkingMachineSetRepository machineSetRepository { get; set; }
        public IWorkingRelationUserRepository workingRelationUser { get; set; }
        public IWorkingRelationMachineRepository workingRelationMachine { get; set; }
    }
}
