using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Exceptions;
using Siger.ApiTPM.Utilities;
using Siger.ApiTPM.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Data.Tpm;
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.TpmRepository.Response;
using Siger.Middlelayer.Utility.Helpers;
using UnixTimeHelper = Siger.Middlelayer.Common.Helpers.UnixTimeHelper;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Repository.Response;

namespace Siger.ApiTPM.Controllers
{
    public class AppRepairController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IRepairRepository _repairRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly ISigerAppProjectConfigRepository _configRepository;
        private readonly ISigerUserRepository _sigerUserRepository;
        private readonly IRepairListRepository _repairListRepository;
        private readonly ISparepartRepository _sparepartRepository;
        private readonly ISparepartRecordRepository _sparepartRecordRepository;
        private readonly ISigerAppMuteRepository _appMuteRepository;
        private readonly IRepairAddUserRepository _addUserRepository;
        private readonly ISigerAppMessageRepository _sigerAppMessage;
        private readonly ISigerProjectUserRepository _projectUserRepository;
        private readonly IRepairReportRepository _repairReportRepository;
        private readonly IPlanRepository _planRepository;
        private readonly ISigerSystemConfigRepository _systemConfigRepository;
        private readonly ISparepartAuditRepository _auditRepository;
        private readonly IWorkingCalendarRepository _calendarRepository;
        private readonly ISigerProjectShiftRepository _projectShiftRepository;
        private readonly IRepairEditRecordRepository _editRecordRepository;
        private readonly ISigerAndonInfoRepository _andonInfoRepository;
        private readonly ISigerAndonExpectionTypeRepository _andonExpectionTypeRepository;
        private readonly IFaultTypeRepository _faultTypeRepository;
        //private readonly IWorkingMachineSetRepository _machineSetRepository;
        private readonly ISigerProjectMachineAttributionRepository _machineAttributionRepository;
        private readonly IWorkingRelationUserRepository _workingRelationUser;
        private readonly IWorkingRelationMachineRepository _workingRelationMachine;

        public AppRepairController(IUnitOfWork unitOfWork, IRepairRepository repairRepository, ISigerAppProjectConfigRepository configRepository,
            ISigerProjectMachineRepository machineRepository, ISigerUserRepository sigerUserRepository, IRepairListRepository repairListRepository,
            ISparepartRepository sparepartRepository, ISparepartRecordRepository sparepartRecordRepository, ISigerAppMuteRepository appMuteRepository,
            IRepairAddUserRepository addUserRepository, ISigerAppMessageRepository sigerAppMessage, ISigerProjectUserRepository projectUserRepository,
            IRepairReportRepository repairReportRepository, IPlanRepository planRepository, ISigerSystemConfigRepository systemConfigRepository,
            ISparepartAuditRepository auditRepository, IWorkingCalendarRepository calendarRepository, ISigerProjectShiftRepository projectShiftRepository,
            IRepairEditRecordRepository editRecordRepository, ISigerAndonInfoRepository andonInfoRepository,
            ISigerAndonExpectionTypeRepository andonExpectionTypeRepository, IFaultTypeRepository faultTypeRepository,
            ISigerProjectMachineAttributionRepository machineAttributionRepository,IWorkingRelationUserRepository workingRelationUser,IWorkingRelationMachineRepository workingRelationMachine)
        {
            _unitOfWork = unitOfWork;
            _repairRepository = repairRepository;
            _configRepository = configRepository;
            _machineRepository = machineRepository;
            _sigerUserRepository = sigerUserRepository;
            _repairListRepository = repairListRepository;
            _sparepartRepository = sparepartRepository;
            _sparepartRecordRepository = sparepartRecordRepository;
            _appMuteRepository = appMuteRepository;
            _addUserRepository = addUserRepository;
            _sigerAppMessage = sigerAppMessage;
            _projectUserRepository = projectUserRepository;
            _repairReportRepository = repairReportRepository;
            _planRepository = planRepository;
            _systemConfigRepository = systemConfigRepository;
            _auditRepository = auditRepository;
            _calendarRepository = calendarRepository;
            _projectShiftRepository = projectShiftRepository;
            _editRecordRepository = editRecordRepository;
            _andonInfoRepository = andonInfoRepository;
            _andonExpectionTypeRepository = andonExpectionTypeRepository;
            _faultTypeRepository = faultTypeRepository;
            //_machineSetRepository = machineSetRepository;
            _machineAttributionRepository = machineAttributionRepository;
            _workingRelationUser = workingRelationUser;
            _workingRelationMachine = workingRelationMachine;
        }

        /// <summary>
        /// 获取维修状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetAppRepairCount()
        {
            var response = new List<ResponseGetMachineRepair>();
            //var sectionIds = _repairRepository.GetStationID(UserId, UnixTimeHelper.GetNow()).Select(t => t.sectionid).ToList();
            //var machineIds = _repairRepository.GetMahinesBySectionIds(sectionIds, ProjectId).Select(t=>t.id).Distinct().ToList();
            //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.projectid == ProjectId && f.employ == UserId && f.status == (int)RowState.Valid);
            var machineIds = userRelation != null ? userRelation.machineSplit : new List<int>();
            var minStatus = _repairRepository.GetRepairListByMachineArr(machineIds, 0, ProjectId, UserId);
            response.Add(new ResponseGetMachineRepair
            {
                name = "200032",
                status = (int)MachineRepairStatus.WaitingForOrders,
                count = minStatus.Count(m => m.status == 1)
            });
            response.Add(new ResponseGetMachineRepair
            {
                name = "200033",
                status = (int)MachineRepairStatus.WaitingForCheckIn,
                count = minStatus.Count(m => m.status == 2)
            });
            response.Add(new ResponseGetMachineRepair
            {
                name = "200034",
                status = (int)MachineRepairStatus.WaitingForRepair,
                count = minStatus.Count(m => m.status == 3)
            });
            response.Add(new ResponseGetMachineRepair
            {
                name = "200035",
                status = (int)MachineRepairStatus.WaitingForRenew,
                count = minStatus.Count(m => m.status == 4)
            });
            response.Add(new ResponseGetMachineRepair
            {
                name = "900704",
                status = (int)MachineRepairStatus.WaitingForFeedback,
                count = minStatus.Count(m => m.status == 5)
            });

            var startTime = UnixTimeHelper.GetTodayUnix();
            var endTime = UnixTimeHelper.GetNow();
            //维修完成只取当日完成
            response.Add(new ResponseGetMachineRepair
            {
                name = "500097",
                status = (int)MachineRepairStatus.Completed,
                count = minStatus.Count(m => m.status == 6 && m.repairtime >= startTime && m.repairtime <= endTime)
            });

            return new ObjectResult(response);
        }

        /// <summary>
        /// 前7天的mttr和mtbf;当月的mttr和mtbf
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetMachineMTTRBFIndex()
        {
            //取当前用户下负责的设备
            var result = new APPMttrbfResult
            {
                Month = DateTime.Now.ToString(ParameterConstant.YearMonthFormat)
            };

            var startTime = DateTime.Now.AddDays(-7);
            var endTime = DateTime.Now.AddDays(-1).ToString(ParameterConstant.DateToEnd);
            DateTime dtDay;
            for (dtDay = startTime; dtDay.CompareTo(DateTime.Now.AddDays(-1)) <= 0; dtDay = dtDay.AddDays(1))
            {
                result.MTTR.date.Add(dtDay.Month + "." + dtDay.Day);
                result.MTBF.date.Add(dtDay.Month + "." + dtDay.Day);
            }
            //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.projectid == ProjectId && f.employ == UserId && f.status == (int)RowState.Valid);
            var machineIds = userRelation != null ? userRelation.machineSplit : new List<int>();
            if (!machineIds.Any())
            {
                return new ObjectResult(result);
            }

            var repairs = _repairRepository.GetAppRepairsForMTTR(machineIds, (int)UnixTimeHelper.ConvertDataTimeLong(startTime),
                UnixTimeHelper.GetUnixByShortDate(endTime), ProjectId).ToList();
            if (!repairs.Any())
            {
                return new ObjectResult(result);
            }

            for (dtDay = startTime; dtDay.CompareTo(DateTime.Now.AddDays(-1)) <= 0; dtDay = dtDay.AddDays(1))
            {
                result.MTTR.value.Add(MachineMTTRBFHelper.GetMachineMTTRBF(dtDay, dtDay.AddDays(1).AddSeconds(-1), repairs, 1));
                result.MTBF.value.Add(MachineMTTRBFHelper.GetMachineMTTRBF(dtDay, dtDay.AddDays(1).AddSeconds(-1), repairs, 1, 2));
            }

            result.MTTR.month = MachineMTTRBFHelper.GetMachineMTTRBF(DateTime.Parse(DateTime.Now.ToString(ParameterConstant.MouthFirstDay)), DateTime.Now, repairs, 1);
            result.MTBF.month = MachineMTTRBFHelper.GetMachineMTTRBF(DateTime.Parse(DateTime.Now.ToString(ParameterConstant.MouthFirstDay)), DateTime.Now, repairs, 1, 2);

            return new ObjectResult(result);
        }

        /// <summary>
        /// 应急维修首页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RepairList([FromBody]RequestDataByStatus req)
        {
            var response = new List<ResponseGetStatusRepair>();
            var datalist = new List<StatusRepairModel>();
            //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.projectid == ProjectId && f.employ == UserId && f.status == (int)RowState.Valid);
            var machineIds = userRelation != null ? userRelation.machineSplit : new List<int>();
            var repairList = _repairRepository.GetRepairListByMachineArr(machineIds, req.status, ProjectId, UserId);

      
            var locationHelper = new MachineLocationHelper(ProjectId, _planRepository);
            var mids = repairList.Select(m => m.machineid).Distinct().ToList();
            //var names = locationHelper.GetPositionByMachineId(mids);
            foreach (var repair in repairList)
            {
                //var name = names.FirstOrDefault(q => q.id == repair.machineid);
              
                var model = new StatusRepairModel
                {
                    machineid = repair.machineid,
                    //location = name != null ? name.title.Split('-').ToList() : new List<string>(),
                    location = locationHelper.GetPositionByMachineId(repair.machineid),
                    createtime = repair.createtimeformat,
                    faultlist = repair.faultlist ?? "",
                    faultcontent = repair.faultcontent ?? "",
                    repairremark = repair.remark,
                    status = repair.status,
                    repairid = repair.repairid,
                    offlinetime = repair.offlinetime,
                    mutestatus = repair.mutestatus,
                    markself = repair.markself,
                    report_level = repair.report_level,
                    work_order = repair.work_order
                };
                if (repair.real_raultid > 0)
                {
                    model.faultcontent = _faultTypeRepository.Get(f => f.id == repair.real_raultid)?.title ?? "";
                }
                //工单是否与自己有关
                var userList = repair.usermids;
                if (!string.IsNullOrWhiteSpace(repair.add_repairmid))
                {
                    var addrepairmid = repair.add_repairmid.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    foreach (var midstr in addrepairmid)
                    {
                        userList.Add(midstr.ToInt());
                    }
                }
                model.markself = userList.Contains(UserId) ? 1 : 0;
                datalist.Add(model);
            }

            var data = datalist.Where(m => m.status == 1).ToList();
            response.Add(new ResponseGetStatusRepair
            {
                name = "200032",
                status = (int)MachineRepairStatus.WaitingForOrders,
                count = data.Count,
                repairlist = data
            });
            data = datalist.Where(m => m.status == 2).ToList();
            response.Add(new ResponseGetStatusRepair
            {
                name = "200033",
                status = (int)MachineRepairStatus.WaitingForCheckIn,
                count = data.Count,
                repairlist = data
            });
            data = datalist.Where(m => m.status == 3).ToList();
            response.Add(new ResponseGetStatusRepair
            {
                name = "200034",
                status = (int)MachineRepairStatus.WaitingForRepair,
                count = data.Count,
                repairlist = data
            });
            data = datalist.Where(m => m.status == 4).ToList();
            response.Add(new ResponseGetStatusRepair
            {
                name = "200035",
                status = (int)MachineRepairStatus.WaitingForRenew,
                count = data.Count,
                repairlist = data
            });
            data = datalist.Where(m => m.status == 5).ToList();
            response.Add(new ResponseGetStatusRepair
            {
                name = "900704",
                status = (int)MachineRepairStatus.WaitingForFeedback,
                count = data.Count,
                repairlist = data
            });

            var startTime = UnixTimeHelper.GetTodayUnix() - 7 * 86400;
            var endTime = UnixTimeHelper.GetTodayUnix() + 86399;
            var repairids = repairList
                .Where(m => m.status == 6 && m.repairtime >= startTime && m.repairtime <= endTime)
                .Select(t => t.repairid).ToList();
            data = datalist.Where(t => repairids.Contains(t.repairid)).ToList();
            response.Add(new ResponseGetStatusRepair
            {
                name = "500097",
                status = (int)MachineRepairStatus.Completed,
                count = data.Count,
                repairlist = data
            });

            return new ObjectResult(response);
        }

        /// <summary>
        /// 获取应急维修当月报修列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MouthSubmitRepairList()
        {
            var res = new List<StatusRepairModel>();
            var endTime = UnixTimeHelper.GetNow();
            var startTime = (int)UnixTimeHelper.ConvertDataTimeLong(DateTime.Now.ToString(ParameterConstant.YearMonthFormat).ToDateTime());
            //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.projectid == ProjectId && f.employ == UserId && f.status == (int)RowState.Valid);
            var machineIds = userRelation != null ? userRelation.machineSplit : new List<int>();

            var statusRepair = _repairRepository.GetRepairListByMachineArr(machineIds, 0, ProjectId, UserId).ToList();
            var repairs = statusRepair.Where(t => t.mid == UserId && t.createtime <= endTime && t.createtime >= startTime).ToList();
            var repairList = ConvertRepairList(repairs).OrderByDescending(t => t.offlinetime).ToList();
            var locationHelper = new MachineLocationHelper(ProjectId, _planRepository);
            var levelSections = _repairRepository.GetAllSections(ProjectId).ToList();
            foreach (var repair in repairList)
            {
                var model = new StatusRepairModel
                {
                    machineid = repair.machineid,
                    location = locationHelper.GetLocationsByMahcineIdForLoop(repair.machineid, levelSections),
                    //location = new List<string> { repair.levelLocation },
                    createtime = repair.createtimeformat,
                    faultlist = repair.faultlist ?? "",
                    faultcontent = repair.faultcontent ?? "",
                    repairremark = repair.repairremark,
                    status = repair.status,
                    repairid = repair.repairid,
                    offlinetime = repair.offlinetime,
                    mutestatus = repair.mutestatus,
                    markself = repair.markself,
                    report_level = repair.report_level
                };
                res.Add(model);
            }
            return new ObjectResult(res);
        }

        /// <summary>
        /// 获取当月维修列表,我操作过或者参与维修的
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MouthRepairList()
        {
            var res = new List<StatusRepairModel>();
            var endTime = UnixTimeHelper.GetNow();
            var startTime = (int)UnixTimeHelper.ConvertDataTimeLong(DateTime.Now.ToString(ParameterConstant.YearMonthFormat).ToDateTime());
            //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.projectid == ProjectId && f.employ == UserId && f.status == (int)RowState.Valid);
            var machineIds = userRelation != null ? userRelation.machineSplit : new List<int>();

            var statusRepair = _repairRepository.GetRepairListByMachineArr(machineIds, 0, ProjectId, UserId).ToList();
            var repairs = statusRepair.Where(t => t.mid != UserId && t.createtime <= endTime && t.createtime >= startTime).ToList();
            var repairList = ConvertRepairList(repairs).Where(t => t.markself == 1)
                .OrderByDescending(t => t.offlinetime).ToList();
            var locationHelper = new MachineLocationHelper(ProjectId, _planRepository);
            var levelSections = _repairRepository.GetAllSections(ProjectId);
            foreach (var repair in repairList)
            {
                var model = new StatusRepairModel
                {
                    machineid = repair.machineid,
                    location = locationHelper.GetLocationsByMahcineIdForLoop(repair.machineid, levelSections),
                    //location = new List<string> { repair.levelLocation },
                    createtime = repair.createtimeformat,
                    faultlist = repair.faultlist ?? "",
                    faultcontent = repair.faultcontent ?? "",
                    repairremark = repair.repairremark,
                    status = repair.status,
                    repairid = repair.repairid,
                    offlinetime = repair.offlinetime,
                    mutestatus = repair.mutestatus,
                    markself = repair.markself,
                    report_level = repair.report_level
                };
                res.Add(model);
            }
            return new ObjectResult(res);
        }

        private List<GetStatusRepairList> ConvertRepairList(List<GetStatusRepairList> lists)
        {
            var res = new List<GetStatusRepairList>();
            if (!lists.Any())
            {
                return res;
            }
            foreach (var repair in lists)
            {
                var createtime = UnixTimeHelper.ConvertIntDateTime(repair.createtime);
                repair.serial_number = repair.createtime.ToString();
                repair.faultcontent = "";
                repair.faultlist = "";

                switch (repair.status)
                {
                    case 2:
                        createtime = UnixTimeHelper.ConvertIntDateTime(repair.taketime);
                        break;
                    case 3:
                        createtime = UnixTimeHelper.ConvertIntDateTime(repair.signtime);
                        break;
                    case 4:
                        createtime = UnixTimeHelper.ConvertIntDateTime(repair.completetime);
                        break;
                    case 5:
                        createtime = UnixTimeHelper.ConvertIntDateTime(repair.checktime);
                        break;
                    case 6:
                        createtime = UnixTimeHelper.ConvertIntDateTime(repair.repairtime);
                        break;
                }
                var offlineTime = 0;
                //计算停线时间
                if (repair.status < (int)MachineRepairStatus.WaitingForFeedback)
                {
                    if (repair.offlinestatus == 1)
                    {
                        offlineTime = (int)Math.Ceiling((decimal)(UnixTimeHelper.GetNow() - repair.createtime) / 60);
                    }
                }
                repair.offlinetime = offlineTime;
                //是否免打扰
                repair.mutestatus = (int)MuteStatus.Close;
                var mute = _repairRepository.GetAppMuteByRepairId(repair.repairid, ProjectId, UserId);
                if (mute != null)
                {
                    repair.mutestatus = mute.status == (int)MuteStatus.Open
                        ? (int)MuteStatus.Open
                        : (int)MuteStatus.Close;
                }
                //工单是否与自己有关
                var addUser = _repairRepository.GetAddUserListByRepairId(repair.repairid).ToList();
                var userList = addUser.Select(t => t.mid).ToList();
                if (!addUser.Any())
                {
                    var addrepairmid = repair.add_repairmid.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    foreach (var midstr in addrepairmid)
                    {
                        userList.Add(midstr.ToInt());
                    }
                }
                userList.Add(repair.mid);
                userList.Add(repair.takemid);
                userList.Add(repair.signmid);
                userList.Add(repair.checkmid);
                userList.Add(repair.completemid);
                userList.Add(repair.repairmid);

                repair.markself = userList.Contains(UserId) ? 1 : 0;

                if (repair.faultid > 0)
                {
                    var machineFault = _repairRepository.GetMachineFaultByFaultId(repair.faultid, ProjectId).ToList();
                    if (machineFault.Any())
                    {
                        repair.faultlist = machineFault[0].title;
                        repair.answer = machineFault[0].answer;
                    }
                }

                if (repair.expection != 0)
                {
                    var expection = _andonExpectionTypeRepository.GetExpectionParent(repair.expection, ProjectId).FirstOrDefault(f => f.level == 2)?.name ?? "";
                    repair.faultcontent = expection;
                }

                var sparepartArr = new List<sparepartidcount>();
                if (!string.IsNullOrEmpty(repair.sparepartid))
                {
                    var spareparts = repair.sparepartid.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    foreach (var spa in spareparts)
                    {
                        var idcount = spa.Split('*', StringSplitOptions.RemoveEmptyEntries);
                        if (idcount.Any() && idcount.Length > 1 && idcount[0].ToInt() > 0 && idcount[1].ToInt() > 0)
                        {
                            sparepartArr.Add(new sparepartidcount
                            {
                                sparepartid = idcount[0].ToInt(),
                                num = idcount[1].ToInt()
                            });
                        }

                    }
                }
                repair.sparepartoutArr = sparepartArr;

                repair.createtimeformat = createtime;
                repair.createtime = repair.createtime;
                res.Add(repair);
            }
            return res;
        }

        /// <summary>
        /// 报修页面 返回机器名称,产线层级和相应故障类型失效模式
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RepairIndex([FromBody]RequestListByMachineId req)
        {
            if (req.machineID.ToInt() == 0)
            {
                throw new ServerException(500213);
            }

            var machineType = _machineRepository.Get(t => t.id == req.machineID.ToInt() && t.status == (int)RowState.Valid && t.projectid == ProjectId);
            var locationHelper = new MachineLocationHelper(ProjectId, _planRepository);
            var location = locationHelper.GetPositionByMachineId(req.machineID.ToInt());
            if (machineType == null || !location.Any())
            {
                throw new ServerException(100236);
            }

            var res = new ResponseRepairIndex
            {
                FaultList = _repairRepository.GetFaultTypeList(machineType.typeid, ProjectId).ToList(),
                machinename = machineType.title,
                location = string.Join('-', location)
            };

            return new ObjectResult(res);
        }

        /// <summary>
        /// 工单详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RepairInfo([FromBody]RequestDataByRepairId req)
        {
            if (req.repairid == 0)
            {
                throw new ServerException(900027);
            }
            var res = new ResponseGetRepairDetail();
            var repair = _repairRepository.GetRepairInfoByID(req.repairid, ProjectId);
            if (repair != null)
            {
                var offlineTime = 0;
                //计算停线时间
                if (repair.status <(int)MachineRepairStatus.WaitingForFeedback)
                {
                    if (repair.offlinestatus == 1)
                    {
                        offlineTime = (int)Math.Ceiling((decimal)(UnixTimeHelper.GetNow() - repair.createtime) / 60);
                    }
                }
                repair.offlinetime = offlineTime;
                //工单是否与自己有关
                var addrepairuser = new List<string>();
                var userList = repair.usermids;
                if (!string.IsNullOrWhiteSpace(repair.add_repairmid))
                {
                    var addrepairmid = repair.add_repairmid.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    foreach (var midstr in addrepairmid)
                    {
                        userList.Add(midstr.ToInt());
                        var userInfo = _projectUserRepository.Get(t => t.mid == midstr.ToInt());
                        if (userInfo != null)
                        {
                            addrepairuser.Add(userInfo.name);
                        }
                    }
                }
                repair.markself = userList.Contains(UserId) ? 1 : 0;
                
                if (repair.faultid > 0)
                {
                    var machineFault = _repairRepository.GetMachineFaultByFaultId(repair.faultid, ProjectId).ToList();
                    if (machineFault.Any())
                    {
                        repair.faultlist = machineFault[0].title;
                        repair.answer = machineFault[0].answer;
                    }
                }

                if (repair.real_raultid > 0)
                {
                    repair.faultcontent = _faultTypeRepository.Get(f => f.id == repair.real_raultid)?.title ?? "";
                }
                var appmute = _appMuteRepository.Get(t =>
                    t.projectid == ProjectId && (t.repairid == req.repairid || t.repairid == 0) && t.status == 0 &&
                    t.mid == UserId);
                repair.mutestatus = appmute != null ? 0 : 1;

                res = Mapper<GetStatusRepairList, ResponseGetRepairDetail>.Map(repair);
                res.addrepairuser = string.Join(',', addrepairuser);
                if (!string.IsNullOrEmpty(repair.sparepartid))
                {
                    var sparepartHelper = new SparepartHelper(ProjectId, UserId, _sparepartRecordRepository, _sparepartRepository);
                    res.sparepartout = string.Join(',', sparepartHelper.GetSparepartNameNum(repair.sparepartid));
                    res.sparepartids = string.Join(',', sparepartHelper.GetSaprepartIdNum(repair.sparepartid));
                }
                else
                {
                    res.sparepartout = "";
                    res.sparepartids = "";
                }

                //返回工位下全部设备
                //var mach = _machineAttributionRepository.Get(q => q.machine == res.machineid 
                //            && q.projectid == ProjectId && q.status == (int)RowState.Valid);
                //if(mach != null)
                //{
                //    var attrs = _machineAttributionRepository.GetList(q => q.station == mach.station && q.projectid == ProjectId && q.status == (int)RowState.Valid).ToList();
                //    foreach (var attr in attrs)
                //    {
                //        var machine = _machineRepository.Get(q => q.id == attr.machine);
                //        if (machine != null)
                //        {
                //            res.machineids.Add(new ResponseIdName
                //            {
                //                id = attr.machine,
                //                name = machine.title
                //            });
                //        }
                //    }
                //}
                
                res.createtime = repair.createtimeformat;
                res.faultlist = res.faultlist ?? "";
                res.faultcontent = res.faultcontent ?? "";
                res.cost = repair.cost;
                res.work_order = repair.work_order;
                var locationHelper = new MachineLocationHelper(ProjectId, _planRepository);
                res.location = locationHelper.GetPositionByMachineId(repair.machineid);
            }
            else
            {
                throw new ServerException(900111);
            }

            var repairList = _repairListRepository.GetList(t => t.projectid == ProjectId && t.repairid == req.repairid)
                .OrderByDescending(x => x.creattime);
            var messageList = new List<MessageModel>();
            foreach (var p in repairList)
            {
                messageList.Add(new MessageModel
                {
                    id = p.id,
                    title = p.title,
                    content = p.content,
                    ctime = UnixTimeHelper.ConvertIntDateTime(p.creattime),
                    isrelate = p.relate_repairid > 0 ? 1 : 0,
                    relaterepairid = p.relate_repairid,
                });
            }
            res.message = messageList;
            return new ObjectResult(res);
        }

        /// <summary>
        /// 提交报修
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SubmitRepair([FromBody]RequestSubmitRepair req)
        {
            var condition = new AppRepairCondition
            {
                projectId = ProjectId,
                userId = UserId,
                planRepository = _planRepository,
                repairListRepository = _repairListRepository,
                repairRepository = _repairRepository,
                sigerUserRepository = _sigerUserRepository,
                unitOfWork = _unitOfWork,
                appMuteRepository = _appMuteRepository,
                calendarRepository = _calendarRepository,
                configRepository = _configRepository,
                machineRepository = _machineRepository,
                projectShiftRepository = _projectShiftRepository,
                projectUserRepository = _projectUserRepository,
                repairReportRepository = _repairReportRepository,
                sigerAppMessage = _sigerAppMessage,
                systemConfigRepository = _systemConfigRepository,
                //machineSetRepository = _machineSetRepository,
                workingRelationMachine=_workingRelationMachine,
                workingRelationUser=_workingRelationUser
            };
            var repairhelper = new AppRepairHelper(condition);
            if (await repairhelper.SubmitRepairAsync(req))
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 提交维修反馈
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SubmitRepairFeedback([FromBody]RequestSubmitRepairFeedback req)
        {
            var userId = UserId;
            var projectId = ProjectId;
            if (req.repairid == 0)
            {
                throw new ServerException(900027);
            }

            if (string.IsNullOrEmpty(req.fault_description) || string.IsNullOrEmpty(req.add_repairmid))
            {
                throw new ServerException(900037);
            }

            var userSectionType = _repairRepository.GetSectionByUserId(userId);
            if (userSectionType == null)
            {
                throw new ServerException(100283);
            }
            var repair = _repairRepository.Get(t => t.id == req.repairid && t.projectid == projectId);
            if (repair == null)
            {
                throw new ServerException(100282);
            }
            if (repair.status != 5 && req.edit_repair == 0)
            {
                throw new ServerException(900708);
            }

            //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.projectid == ProjectId && f.employ == UserId && f.status == (int)RowState.Valid);
            var machineIds = userRelation != null ? userRelation.machineSplit : new List<int>();

            //获取报修/接单/签到人
            var midList = new List<int>
            {
                repair.mid,
                repair.takemid,
                repair.signmid,
                repair.completemid,
                repair.checkmid
            };
            //获取合作维修人员
            var repairadd = _repairRepository.GetAddUserListByRepairId(req.repairid).ToList();
            if (repairadd.Any())
            {
                foreach (var addRepair in repairadd)
                {
                    midList.Add(addRepair.mid);
                }
                //合作维修 只能由合作人员操作
                var coopUser = repairadd.Select(t => t.mid).Distinct().ToList();
   
                coopUser.Add(repair.completemid);
                if (!coopUser.Contains(UserId))
                {
                    throw new ServerException(700074);
                }
            }
            midList = midList.Where(t => t > 0).Distinct().ToList();
            //信息记录
            var repairListInfo = new siger_project_repair_list
            {
                repairid = req.repairid,
                projectid = projectId,
                mid = userId,
                status = (int)MachineRepairStatus.WaitingForRenew
            };
            var isTranslate = _planRepository.GetProjectLanguage(projectId) == (int)LanguageType.EN;
            var translateHelper = new TranslateHelper(isTranslate);
            var userType = "";
            var userName = "";
            if (userSectionType.type == (int)SectionType.Maintenance)
            {
                userType = translateHelper.GetTranslateText(TranslateEnEnum.MaintenanceStaff);
            }
            else
            {
                userType = translateHelper.GetTranslateText(TranslateEnEnum.ProductionStaff);
            }

            var userType1 = translateHelper.GetTranslateText(TranslateEnEnum.ProductionStaff);
            var userName1 = "";
            var userInfo1 = _sigerUserRepository.Get(t => t.id == repair.mid);
            if (userInfo1 != null)
            {
                userName1 = userInfo1.nickname + "(" + userInfo1.mobile + ")";
            }

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

            if (userSectionType.type == (int)SectionType.Maintenance && (machineIds.Contains(repair.machineid) || midList.Contains(userId)))
            {
                //工单详情记录
                repairListInfo.title = ((int)RepairListStatus.MaintenanceFeedBack).ToString();
                repairListInfo.content = userType + userName +
                                         translateHelper.GetTranslateText(TranslateEnEnum
                                             .MaintenanceFeedbackSheetSubmittedMaintenanceCompleted);
                var locationHelper = new MachineLocationHelper(projectId, _planRepository);
                var location = string.Join('-', locationHelper.GetPositionByMachineId(repair.machineid));
                var content = "【" + location + "】" + userType + userName +
                              translateHelper.GetTranslateText(TranslateEnEnum
                                  .MaintenanceFeedbackSheetSubmittedPlease) + userType1 + userName1 +
                              translateHelper.GetTranslateText(TranslateEnEnum.ConfirmCompeletion);
                var oldrepair = repair;
                //消息推送
                await Task.Run(() =>
                {
                    //消息推送
                    if (oldrepair.status != (int)MachineRepairStatus.Completed)
                    {
                        var paras = new Dictionary<string, string>
                        {
                            { "location", location },
                            { "usertype1", userType },
                            { "username1", userName },
                            { "usertype2", userType1 },
                            { "username2", userName1 }
                        };
                        SendMessage(req.repairid, repair.machineid, (int)MachineRepairStatus.Completed,
                            translateHelper.GetTranslateText(TranslateEnEnum.Completed), content, 1, userId,
                            SMSTemplateConst.Completed, isTranslate, paras);
                    }
                });
                if (oldrepair.status > (int)MachineRepairStatus.WaitingForRepair)
                {
                    repairListInfo.content = userType + userName +
                                             translateHelper.GetTranslateText(TranslateEnEnum
                                                 .EditedMaintenanceFeedbackSheet);
                }

                repair.fault_description = req.fault_description ?? "";
                repair.fault_desc_img = req.fault_desc_img ?? "";
                repair.repair_process = req.repair_process ?? "";
                if(req.machineid != 0)
                {
                    repair.machineid = req.machineid;
                }
                repair.real_faultid_desc = "";
                repair.repairtime = UnixTimeHelper.GetNow();
                repair.repairmid = userId;
                repair.repair_remark = req.repair_remark ?? "";
                //repair.sparepartid = "";
                repair.status = (int)MachineRepairStatus.Completed;
                var addRepairmid = oldrepair.add_repairmid.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                addRepairmid.AddRange(req.add_repairmid.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList());
                addRepairmid = addRepairmid.Distinct().ToList();
                repair.add_repairmid = string.Join(',', addRepairmid);
                repair.cost_purpose = req.cost.ToInt();

                _repairRepository.Update(repair);

                repairListInfo.creattime = UnixTimeHelper.GetNow();
                _repairListRepository.Insert(repairListInfo);

                if (_unitOfWork.Commit() > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }

                throw new BadRequestException(CommonEnum.Fail);
            }
            else
            {
                throw new ServerException(900706);
            }
        }

        /// <summary>
        /// 人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetUserByType([FromBody]RequestMsgList req)
        {
            var res = new List<RepsonseGetUserByType>();

            var userSectionType = _repairRepository.GetUserBySectionType(ProjectId, req.type).ToList();
            if (userSectionType.Any())
            {
                foreach (var user in userSectionType)
                {
                    res.Add(new RepsonseGetUserByType
                    {
                        mid = user.mid,
                        name = user.name,
                        work_code = user.work_code
                    });
                }
            }
            return new ObjectResult(res);
        }

        /// <summary>
        /// 人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetUserListByType([FromBody]RequestMsgList req)
        {
            var res = new List<RepsonseGetUserListByType>();
            var userSectionType = _repairRepository.GetUserBySectionType(ProjectId, req.type).ToList();
            if (userSectionType.Any())
            {
                foreach (var user in userSectionType)
                {
                    res.Add(new RepsonseGetUserListByType
                    {
                        employee_id = user.mid,
                        name = user.name,
                        phonetic = PinYinHelper.ToPinYin(user.name),
                        position = user.work_code,
                        remark = "",
                        selected = false
                    });
                }
            }
            return new ObjectResult(res);
        }

        /// <summary>
        /// 扫码-应急维修工单页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MachineRepair([FromBody]RequestListByMachineId req)
        {
            if (req.machineID.ToInt() == 0)
            {
                throw new ServerException(900027);
            }
            //检查报修权限
            var cals = _calendarRepository.GetList(q => q.date.Date == DateTime.Now.Date && q.machine_id == req.machineID.ToInt() && 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;
            var time = UnixTimeHelper.GetNow();
            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 datalist = new List<StatusRepairModel>();
            var statusRepair = _repairRepository
                .GetRepairListByMachineArr(new List<int> { req.machineID.ToInt() }, 0, ProjectId, UserId)
                .Where(t => t.machineid == req.machineID.ToInt()).ToList();
            var repairList = ConvertRepairList(statusRepair).Where(t => t.status < (int)MachineRepairStatus.Completed && t.status > 0).ToList();
            var locationHelper = new MachineLocationHelper(ProjectId, _planRepository);
            foreach (var repair in repairList)
            {
                var model = new StatusRepairModel
                {
                    machineid = repair.machineid,
                    location = locationHelper.GetPositionByMachineId(repair.machineid),
                    //location = new List<string> { repair.levelLocation },
                    createtime = repair.createtimeformat,
                    faultlist = repair.faultlist ?? "",
                    faultcontent = repair.faultcontent ?? "",
                    repairremark = string.IsNullOrEmpty(repair.repairremark) ? repair.faultlist : repair.repairremark,
                    status = repair.status,
                    repairid = repair.repairid,
                    offlinetime = repair.offlinetime,
                    mutestatus = repair.mutestatus,
                    markself = repair.markself,
                    report_level = repair.report_level
                };
                datalist.Add(model);
            }

            return new ObjectResult(datalist);
        }

        /// <summary>
        /// 工单状态变更
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RepairExecute([FromBody]RequestRepairExecution req)
        {
            if (req.repairid == 0)
            {
                throw new ServerException(900027);
            }

            if (!string.IsNullOrEmpty(req.reason) && RegexHelper.InputRegex(req.reason))
            {
                throw new ServerException(800064);
            }
            var userSectionType = _repairRepository.GetSectionByUserId(UserId);
            if (userSectionType == null)
            {
                throw new ServerException(100283);
            }

            var repairInfo = _repairRepository.Get(t => t.projectid == ProjectId && t.id == req.repairid);
            if (repairInfo == null)
            {
                throw new ServerException(100282);
            }
            
            //获取合作维修人员
            var repairAddUser = _repairRepository.GetAddUserListByRepairId(req.repairid).ToList();

            var coopUser = new List<int> { 
                repairInfo.takemid,
                repairInfo.signmid,
                repairInfo.completemid
            };
            if (repairAddUser.Any())
            {
                //合作维修 只能由合作人员操作
                coopUser = repairAddUser.Select(t => t.mid).Distinct().ToList();
                
                if (repairInfo.status>=(int)MachineRepairStatus.WaitingForCheckIn && repairInfo.status<(int)MachineRepairStatus.WaitingForRenew)
                {
                    if (!coopUser.Contains(UserId))
                    {
                        throw new ServerException(700074);
                    }
                }
            }

            var time = UnixTimeHelper.GetNow();
            var userRelation = _workingRelationUser.Get(f => f.projectid == ProjectId && f.employ == UserId && 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 repairAddUser = _repairRepository.GetAddUserListByRepairId(req.repairid).ToList();
            if (coopUser.Any())
            {
                midList.AddRange(coopUser);
            }
            midList = midList.Where(t => t > 0).Distinct().ToList();
            var newRepairInfo = repairInfo;
            //根据工单状态不同执行不同状态变更
            if (repairInfo.status == req.repairstatus)
            {
                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 + ")";
                }
                //推送信息
                var content = "";
                var locationHelper = new MachineLocationHelper(ProjectId, _planRepository);
                var location = string.Join('-', locationHelper.GetPositionByMachineId(repairInfo.machineid));
                int templateId = 0;
                var pushTitle = "";
                var paras = new Dictionary<string, string>();
                switch (req.repairstatus)
                {
                    case 1://接单
                        if (userSectionType.type == (int)SectionType.Maintenance)
                        {
                            newRepairInfo.status = (int)MachineRepairStatus.WaitingForCheckIn;
                            pushTitle = translateHelper.GetTranslateText(TranslateEnEnum.TobeSignedIn);
                            newRepairInfo.taketime = time;
                            newRepairInfo.takemid = UserId;
                            newRepairInfo.report_level = 0;
                            //工单详情记录
                            repairListInfo.title = ((int)RepairListStatus.TobeSignedIn).ToString();
                            repairListInfo.content = userType + " " + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum.OrderReceivedRushingToTheScene);
                            //推送信息
                            content = "【" + location + "】" + "，" + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum.OrderReceived);
                            templateId = SMSTemplateConst.WaitingForCheckIn;
                            paras.Add("location", location);
                            paras.Add("usertype", userType);
                            paras.Add("username", userName);
                        }
                        else
                        {
                            throw new ServerException(900706);
                        }
                        break;
                    case 2://签到
                        if (userSectionType.type == (int)SectionType.Maintenance && midList.Contains(UserId))
                        {

                            newRepairInfo.status = (int)MachineRepairStatus.WaitingForRepair;
                            pushTitle = translateHelper.GetTranslateText(TranslateEnEnum.UnderRepair);
                            newRepairInfo.report_level = 0;
                            newRepairInfo.signtime = time;
                            newRepairInfo.signmid = UserId;
                            //工单详情记录
                            repairListInfo.title = ((int)RepairListStatus.UnderRepair).ToString();
                            repairListInfo.content = userType + " " + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum.AttendanceOnSite);
                            //推送信息
                            content = "【" + location + "】" + "，" + userName + " " + translateHelper.GetTranslateText(TranslateEnEnum.CheckedIn);
                            templateId = SMSTemplateConst.WaitingForRepair;
                            paras.Add("location", location);
                            paras.Add("userName", userName);
                        }
                        else
                        {
                            throw new ServerException(900706);
                        }
                        #region andon handle
                        if (!string.IsNullOrEmpty(repairInfo.work_order))
                        {
                            var andonid = _andonInfoRepository.Get(f => f.work_order == repairInfo.work_order && f.projectid == ProjectId && f.status < (int)AndonState.Approve && f.status > (int)AndonState.Abnormal);
                            if (andonid != null)
                            {
                                _andonInfoRepository.HandleAndon(new RequestHandleAndon { id = andonid.id, type = (int)AndonState.Handling, expection = andonid.expection_type }, ProjectId, CompanyId, UserId);
                            }
                        }
                        #endregion
                        break;
                    case 3:
                        //if (userSectionType.type == (int)SectionType.Maintenance && (machineIds.Contains(repairInfo.machineid) || midList.Contains(UserId)))
                        if (userSectionType.type == (int)SectionType.Maintenance && midList.Contains(UserId))
                        {
                            newRepairInfo.status = (int)MachineRepairStatus.WaitingForRenew;
                            pushTitle = translateHelper.GetTranslateText(TranslateEnEnum.TobeRecovered);
                            newRepairInfo.report_level = 0;
                            newRepairInfo.completemid = UserId;
                            newRepairInfo.repairmid = UserId;
                            newRepairInfo.completetime = time;
                            //工单详情记录
                            repairListInfo.title = ((int)RepairListStatus.TobeRecovered).ToString();
                            repairListInfo.content = userType + " " + userName + " " +
                                                     translateHelper.GetTranslateText(TranslateEnEnum
                                                         .MaintenanceCompletedPleaseConfirmProductionStaffRewire);
                            //推送信息
                            content = "【" + location + "】" + "，" + userName + " " +
                                      translateHelper.GetTranslateText(TranslateEnEnum
                                          .MaintenanceCompletedPleaseConfirmMultiline);
                            templateId = SMSTemplateConst.WaitingForRenew;
                            paras.Add("location", location);
                            paras.Add("userName", userName);
                        }
                        else
                        {
                            throw new ServerException(900706);
                        }
                        #region andon handle
                        if (!string.IsNullOrEmpty(repairInfo.work_order))
                        {
                            var andonid = _andonInfoRepository.Get(f => f.work_order == repairInfo.work_order && f.projectid == ProjectId && f.status < (int)AndonState.Approve && f.status > (int)AndonState.Abnormal);
                            if (andonid != null)
                            {
                                _andonInfoRepository.HandleAndon(new RequestHandleAndon { id = andonid.id, type = (int)AndonState.Complete, expection = andonid.expection_type }, ProjectId, CompanyId, UserId);
                            }
                        }
                        #endregion
                        break;
                    case 4://复线
                        //拦截安灯异常
                        if (!string.IsNullOrEmpty(repairInfo.work_order) && repairInfo.work_order.StartsWith('A'))
                        {
                            throw new BadRequestException(TpmEnum.MachinStatusCanNotHandle);
                        }
                        if (userSectionType.type == (int)SectionType.ProduceSection && (machineIds.Contains(repairInfo.machineid) || midList.Contains(UserId)))
                        {
                            if (req.checkstatus == 1)
                            {
                                newRepairInfo.status = (int)MachineRepairStatus.WaitingForFeedback;
                                pushTitle = translateHelper.GetTranslateText(TranslateEnEnum.TobeFeedBack);
                                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)//让步复线
                            {
                                //var section = _repairRepository.GetLevelMachineByMachineId(newRepairInfo.machineid);
                                //var sectionid = section != null ? section.section_id : 0;
                                newRepairInfo.status = (int)MachineRepairStatus.WaitingForFeedback;
                                pushTitle = translateHelper.GetTranslateText(TranslateEnEnum.ConcessionRecovered);
                                newRepairInfo.report_level = 0;
                                newRepairInfo.checktime = time;
                                newRepairInfo.checkmid = UserId;
                                //newRepairInfo.offlinestatus = 0;
                                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 expection = _andonInfoRepository.Get(f => f.work_order == repairInfo.work_order && f.status != (int)RowState.Invalid)?.expection_type ?? 0;
                                var expectionName = _andonExpectionTypeRepository.Get(f => f.id == expection)?.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
                                };
                                _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 new ObjectResult(CommonEnum.Succefull);
                                }
                                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);
                            }
                        }
                        else
                        {
                            throw new ServerException(900706);
                        }
                        break;
                    default:
                        throw new ServerException(900707);
                }
                _repairRepository.Update(newRepairInfo);
                //工单记录
                repairListInfo.creattime = time;
                _repairListRepository.Insert(repairListInfo);
                if (_unitOfWork.Commit() > 0 && templateId > 0)
                {
                    //消息推送
                    SendMessage(req.repairid, repairInfo.machineid, newRepairInfo.status, pushTitle, content, 1, UserId, templateId, isTranslate, paras);
                    return new ObjectResult(CommonEnum.Succefull);
                }
                else
                {
                    throw new ServerException(900651);
                }
            }
            else
            {
                throw new ServerException(900705);
            }
        }

        /// <summary>
        /// 关闭工单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CloseRepair([FromBody]RequestDataByRepairId req)
        {
            var condition = new AppRepairCondition
            {
                projectId = ProjectId,
                userId = UserId,
                planRepository = _planRepository,
                repairListRepository = _repairListRepository,
                repairRepository = _repairRepository,
                sigerUserRepository = _sigerUserRepository,
                unitOfWork = _unitOfWork,
                appMuteRepository = _appMuteRepository,
                calendarRepository = _calendarRepository,
                configRepository = _configRepository,
                machineRepository = _machineRepository,
                projectShiftRepository = _projectShiftRepository,
                projectUserRepository = _projectUserRepository,
                repairReportRepository = _repairReportRepository,
                sigerAppMessage = _sigerAppMessage,
                systemConfigRepository = _systemConfigRepository,
                //machineSetRepository = _machineSetRepository,
                workingRelationUser=_workingRelationUser,
                workingRelationMachine=_workingRelationMachine
            };
            var repairhelper = new AppRepairHelper(condition);
            if (repairhelper.CloseRepair(req))
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 合作维修
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CooperateRepair([FromBody]RequestCooperateRepair req)
        {
            if (req.midarr == null || !req.midarr.Any() || req.repairid == 0)
            {
                throw new ServerException(900027);
            }

            if (!string.IsNullOrEmpty(req.reason) && RegexHelper.InputRegex(req.reason))
            {
                throw new ServerException(800064);
            }
            var repairInfo = _repairRepository.Get(t => t.projectid == ProjectId && t.id == req.repairid);
            if (repairInfo == null)
            {
                throw new ServerException(100282);
            }
            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.projectid == ProjectId && f.employ == UserId && 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 user = new List<int>();
            var addUser = new List<string>();
            var locationHelper = new MachineLocationHelper(ProjectId, _planRepository);
            var isTranslate = _planRepository.GetProjectLanguage(ProjectId) == (int)LanguageType.EN;
            var translateHelper = new TranslateHelper(isTranslate);
            if (midList.Contains(UserId) || machineIds.Contains(repairInfo.machineid))
            {
                foreach (var midstr in req.midarr)
                {
                    var mid = midstr.ToInt();
                    if (mid == 0)
                    {
                        continue;
                    }

                    //获取岗位信息
                    var userSectionType1 = _repairRepository.GetSectionByUserId(mid);
                    if (userSectionType1 == null || userSectionType.type != userSectionType1.type)
                    {
                        continue;
                    }
                    var res = _addUserRepository.GetList(t => t.status == (int)RowState.Valid && t.repairid == req.repairid
                        && t.creatmid == UserId && t.mid == mid && t.reason == req.reason && t.type == userSectionType1.type);
                    if (!res.Any())
                    {
                        var newAdduser = new siger_project_repair_add_user
                        {
                            repairid = req.repairid,
                            creatmid = UserId,
                            mid = mid,
                            reason = req.reason,
                            type = userSectionType1.type,
                            status = (int)RowState.Valid,
                            creattime = time
                        };
                        _addUserRepository.Insert(newAdduser);
                        if (_unitOfWork.Commit() > 0)
                        {
                            user.Add(mid);
                            var midUser = _sigerUserRepository.Get(t => t.id == mid && t.status == (int)RowState.Valid);
                            if (midUser != null)
                            {
                                addUser.Add(midUser.nickname + "(" + midUser.mobile + ")");
                            }
                        }
                    }
                }

                string addUserStr = "";
                if (addUser.Any())
                {
                    var location = string.Join('-', locationHelper.GetPositionByMachineId(repairInfo.machineid));
                    var repairListInfo = new siger_project_repair_list
                    {
                        repairid = req.repairid,
                        projectid = ProjectId,
                        mid = UserId,
                        status = repairInfo.status,
                        title = ((int)RepairListStatus.CooperativeMaintenance).ToString()
                    };
                    addUserStr = string.Join(',', addUser);
                    repairListInfo.content = addUserStr + " " +
                                             translateHelper.GetTranslateText(TranslateEnEnum.Participated) +
                                             "【" + location + "】，" +
                                             translateHelper.GetTranslateText(TranslateEnEnum.CooperativeMaintenance);
                    repairListInfo.creattime = time;
                    _repairListRepository.Insert(repairListInfo);
                    if (_unitOfWork.Commit() > 0)
                    {
                        var paras = new Dictionary<string, string>
                        {
                            {"addUserStr", addUserStr},
                            {"location", location}
                        };
                        SendMessage(req.repairid, repairInfo.machineid, repairInfo.status,
                            translateHelper.GetTranslateText(TranslateEnEnum.CooperativeMaintenance),
                            repairListInfo.content, 1, UserId, SMSTemplateConst.CooperateRepair, isTranslate, paras);
                    }
                }

                return new ObjectResult(addUserStr);
            }
            else
            {
                throw new ServerException(900706);
            }
        }

        /// <summary>
        /// 提交备件
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SubmitSpareparts([FromBody]RequestSubmitSpareparts request)
        {
            var spareparts = request.spareparts;
            if (spareparts == null || !spareparts.Any())
            {
                spareparts = new List<SubmitSparepartInfo>();
            }

            if (spareparts.Any())
            {
                //是否有审核件
                var needApproval = _sparepartRepository.Get(q => request.spareparts.Select(m => m.sparepart_id).Contains(q.id)
                                                                 && q.approvaluser_mid > 0 && q.status == (int)RowState.Valid);

                var result = _auditRepository.AddPrepareSpareparts(request, ProjectId, UserId, needApproval != null);
                if (result < 0)
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }
            }

            var isTranslate = _planRepository.GetProjectLanguage(ProjectId) == (int)LanguageType.EN;
            var translateHelper = new TranslateHelper(isTranslate);
            var time = UnixTimeHelper.GetNow();

            //add repair list
            var addRepairList = new siger_project_repair_list
            {
                repairid = request.repair_id,
                projectid = ProjectId,
                mid = UserId,
                title = ((int)RepairListStatus.SparepartPreparing).ToString(),
                status = (int)MachineRepairStatus.WaitingForRepair,
                content = translateHelper.GetTranslateText(TranslateEnEnum.SparepartPrepare),
                creattime = time
            };
            _repairListRepository.Insert(addRepairList);

            //发送消息
            var messagepush = new PushHelper(ProjectId, _sigerAppMessage, _projectUserRepository, _configRepository);
            var config = _systemConfigRepository.Get(q =>
                q.key == SystemConfigKey.SkfSparepartWarehouseMid && q.status == (int)RowState.Valid);
            if (config != null)
            {
                var messageInfo = new siger_app_project_message
                {
                    tomid = config.value.ToInt(),
                    projectid = ProjectId,
                    repairid = request.repair_id,
                    create_time = time,
                    type = (int)RepairOrPlanStatus.Repair,
                    title = translateHelper.GetTranslateText(TranslateEnEnum.SparepartPreparing), //备料中
                    content = translateHelper.GetTranslateText(TranslateEnEnum.SparepartPrepare),
                    read_sign = 0,
                    status = (int)RepairListStatus.SparepartPreparing,
                };
                var templateId = 0;
                if (isTranslate)
                {
                    templateId = TemplateHelper.GetSmsEnTemplateId(templateId);
                }
                var mute = _appMuteRepository.Get(t =>
                    t.projectid == ProjectId && t.status == 0 && (t.repairid == request.repair_id || t.repairid == 0) &&
                    t.mid == config.value.ToInt());
                var isPush = mute == null;
                if (templateId > 0 && isPush)
                {
                    messagepush.Push(messageInfo, isPush, templateId, null);
                    SendWeXinMessage(messageInfo.title, messageInfo.content, time, messageInfo.tomid,
                        TemplateHelper.GetWxTempleteId(isTranslate));
                }
            }

            if (_unitOfWork.Commit() < 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        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)
            {
                if (mid == mymid || mid <= 0)
                {
                    continue;
                }
                try
                {
                    if (reportMidList.Contains(mid))
                    {
                        var mute = _appMuteRepository.Get(t =>
                            t.projectid == ProjectId && t.status == 0 && (t.repairid == repairid || t.repairid == 0) &&
                            t.mid == mid);
                        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,
                        };
                        if (isTranslate)
                        {
                            templateId = TemplateHelper.GetSmsEnTemplateId(templateId);
                        }
                        var isPush = reportMidList.Contains(mid) && mute == null;
                        if (templateId > 0 && isPush)
                        {
                            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);
        }

        /// <summary>
        /// 获取合作维修交接原因列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCooperateReasons()
        {
            var res = new List<IdText>();
            var languageType = _planRepository.GetProjectLanguage(ProjectId);
            var reasons = _repairRepository.GetCooperateReasonList(ProjectId, languageType).OrderBy(x => x.sort).ToList();

            foreach (var reason in reasons)
            {
                res.Add(new IdText
                {
                    id = reason.id,
                    text = reason.reason
                });
            }

            return new ObjectResult(res);
        }

        /// <summary>
        /// skf-app
        /// </summary>
        /// <param name="machineid"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetRepairHistory(string machineid, int page, int pagesize)
        {
            var machineId = machineid.ToInt();
            Expression<Func<siger_project_repair, bool>> funMachine = t =>
                    t.projectid == ProjectId && t.machineid == machineId && t.status > 0 && t.status < (int)MachineRepairStatus.Deleted;
            var repairs = _repairRepository.GetPagedList(page, pagesize, funMachine, "status", false);
            var res = new List<ResponseGetRepairHistory>();
            foreach (var repair in repairs.Data)
            {
                res.Add(new ResponseGetRepairHistory
                {
                    repairid = repair.id,
                    workcode = repair.id.ToString(),
                    status = repair.status
                });
            }

            return new PagedObjectResult(res, repairs.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult AddFeedBack([FromBody]RequestAddFeedBack req)
        {
            if (req.repairid == 0)
            {
                throw new ServerException(900027);
            }

            if (req.mode.ToInt() == 0)
            {
                throw new ServerException(900037);
            }

            var repair = _repairRepository.Get(t => t.id == req.repairid && t.projectid == ProjectId);
            if (repair == null)
            {
                throw new ServerException(100282);
            }
            if (repair.status != 5)
            {
                throw new ServerException(900708);
            }
            //信息记录
            var repairListInfo = new siger_project_repair_list
            {
                repairid = req.repairid,
                projectid = ProjectId,
                mid = UserId,
                status = (int)MachineRepairStatus.WaitingForRenew
            };
            var isTranslate = _planRepository.GetProjectLanguage(ProjectId) == (int)LanguageType.EN;
            var translateHelper = new TranslateHelper(isTranslate);
            var userType = "";
            var userName = "";
            var userSectionType = _repairRepository.GetSectionByUserId(UserId);
            if (userSectionType != null && userSectionType.type == (int)SectionType.Maintenance)
            {
                userType = translateHelper.GetTranslateText(TranslateEnEnum.MaintenanceStaff);
            }
            else
            {
                userType = translateHelper.GetTranslateText(TranslateEnEnum.ProductionStaff);
            }

            var userType1 = translateHelper.GetTranslateText(TranslateEnEnum.ProductionStaff);
            var userName1 = "";
            var userInfo1 = _sigerUserRepository.Get(t => t.id == repair.mid);
            if (userInfo1 != null)
            {
                userName1 = userInfo1.nickname + "(" + userInfo1.mobile + ")";
            }

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

            var oldrepair = repair;
            if (oldrepair.status > (int)MachineRepairStatus.WaitingForRepair)
            {
                repairListInfo.content = userType + userName +
                                            translateHelper.GetTranslateText(TranslateEnEnum
                                                .EditedMaintenanceFeedbackSheet);
            }

            repair.fault_description = req.reason.ToStr() ?? "";
            repair.repair_process = req.action.ToStr() ?? "";
            repair.real_faultid = req.mode.ToInt();
            repair.repairtime = UnixTimeHelper.GetNow();
            repair.repairmid = UserId;
            repair.repair_remark = req.remark ?? "";
            repair.status = (int)MachineRepairStatus.Completed;
            repair.add_repairmid = string.Join(',', req.midarr.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList());
            repair.cost_purpose = req.cost.ToInt();

            _repairRepository.Update(repair);

            repairListInfo.creattime = UnixTimeHelper.GetNow();
            repairListInfo.title = ((int)RepairListStatus.MaintenanceFeedBack).ToString();
            repairListInfo.content = userType + userName +
                                     translateHelper.GetTranslateText(TranslateEnEnum
                                         .MaintenanceFeedbackSheetSubmittedMaintenanceCompleted);
            _repairListRepository.Insert(repairListInfo);

            AddEditRecord(repair.id, repair.repair_remark);
            if (_unitOfWork.Commit() > 0)
            {
                Task.Run(() =>
                {
                    //工单详情记录
                    var locationHelper = new MachineLocationHelper(ProjectId, _planRepository);
                    var location = string.Join('-', locationHelper.GetPositionByMachineId(repair.machineid));
                    var content = "【" + location + "】" + userType + userName +
                                  translateHelper.GetTranslateText(TranslateEnEnum
                                      .MaintenanceFeedbackSheetSubmittedPlease) + userType1 + userName1 +
                                  translateHelper.GetTranslateText(TranslateEnEnum.ConfirmCompeletion);
                    //消息推送
                    if (oldrepair.status != (int)MachineRepairStatus.Completed)
                    {
                        var paras = new Dictionary<string, string>
                        {
                            {"location", location},
                            {"usertype1", userType},
                            {"username1", userName},
                            {"usertype2", userType1},
                            {"username2", userName1}
                        };
                        SendMessage(req.repairid, repair.machineid, (int)MachineRepairStatus.Completed,
                            translateHelper.GetTranslateText(TranslateEnEnum.Completed), content, 1, UserId,
                            SMSTemplateConst.Completed, isTranslate, paras);
                    }
                });
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult EditFeedBack([FromBody]RequestAddFeedBack req)
        {
            var repair = _repairRepository.Get(t => t.id == req.repairid && t.projectid == ProjectId);
            if (repair == null)
            {
                throw new ServerException(100282);
            }
            if (repair.status < 5)
            {
                throw new ServerException(900708);
            }
            repair.fault_description = req.reason.ToStr() ?? "";
            repair.repair_process = req.action.ToStr() ?? "";
            repair.real_faultid = req.mode.ToInt();
            repair.repair_remark = req.remark ?? "";
            repair.add_repairmid = string.Join(',', req.midarr.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList());
            repair.cost_purpose = req.cost.ToInt();

            _repairRepository.Update(repair);

            AddEditRecord(repair.id, repair.repair_remark);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        private void AddEditRecord(int repairId, string remark)
        {
            var entity = new siger_project_repair_edit_record
            {
                repair_id = repairId,
                content = remark,
                create_time = DateTime.Now,
                creator_mid = UserId,
                project_id = ProjectId
            };
            _editRecordRepository.Insert(entity);
        }

        [HttpGet]
        public IActionResult GetEditRecord(int page = PageIndex, int pagesize = PageSize)
        {
            var data = _editRecordRepository.GetRepairEditRecords(page, pagesize, ProjectId);
            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }
    }
}