using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.ApiTPM.Result;
using Siger.ApiTPM.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Data.Tpm;
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;

namespace Siger.ApiTPM.Controllers
{
    public class AppPlanController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IPlanTimeRepository _planTime;
        private readonly IPlanRepository _plan;
        private readonly IPlanItemRepository _planItem;
        private readonly ISparepartRecordRepository _sparepartRecord;
        private readonly ISparepartRepository _sparepartRepository;
        private readonly IPlanRecordRepository _planRecord;
        private readonly ISigerProjectUserRepository _userRepository;
        private readonly IWorkingCalendarRepository _calendarRepository;
        private readonly IWorkingRelationUserRepository _workingRelationUser;
        private readonly ISigerProjectUserRepository _projectUserRepository;
        private readonly ISparepartAuditRepository _auditRepository;
        private readonly ISigerProjectMachineAttributionRepository _machineAttributionRepository;

        public AppPlanController(IUnitOfWork unitOfWork, IPlanTimeRepository planTime, IPlanRepository plan,
            IPlanItemRepository planItem, ISparepartRecordRepository sparepartRecord, ISigerProjectMachineRepository machineRepository,
            IPlanRecordRepository planRecord, ISparepartRepository sparepartRepository, ISigerProjectUserRepository userRepository,
            IWorkingCalendarRepository calendarRepository,IWorkingRelationUserRepository workingRelationUser,
            ISigerProjectUserRepository projectUserRepository, ISparepartAuditRepository auditRepository,ISigerProjectMachineAttributionRepository machineAttributionRepository)
        {
            _unitOfWork = unitOfWork;
            _planTime = planTime;
            _plan = plan;
            _planItem = planItem;
            _sparepartRecord = sparepartRecord;
            _planRecord = planRecord;
            _sparepartRepository = sparepartRepository;
            _userRepository = userRepository;
            _calendarRepository = calendarRepository;
            _workingRelationUser = workingRelationUser;
            _projectUserRepository = projectUserRepository;
            _auditRepository = auditRepository;
            _machineAttributionRepository = machineAttributionRepository;
        }

        /// <summary>
        /// 计划维护首页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PlanList()
        {
            var pid = ProjectId;
            var mid = UserId;
            var start = UnixTimeHelper.GetTodayUnix();
            var result = new List<ResponseGetPlanList>();
           // var machineIds = _calendarRepository.GetList(q => q.user_mid == mid && q.project_id == pid && q.status == (int)RowState.Valid).Select(q => q.machine_id).Distinct().ToList();
            var workingCalendar = _calendarRepository.Get(f => f.project_id == pid && f.user_mid == mid && f.status == (int)RowState.Valid);
            if (workingCalendar==null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var userRelation = _workingRelationUser.Get(f => f.employ == mid && f.projectid==pid);
            if (userRelation==null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var machineIds = userRelation.machineSplit;
            var user = _projectUserRepository.Get(q => q.mid == mid);
            
            //待执行实体
            var waitHandleModel = new ResponseGetPlanList { count = 0, status = 1, state = 0, plans = new List<PlanModel>() };
            //已完成实体
            var completeModel = new ResponseGetPlanList { count = 0, status = 1, state = 1, plans = new List<PlanModel>() };
            if (!machineIds.Any())
            {
                result.Add(waitHandleModel);
                result.Add(completeModel);
                return new ObjectResult(result);
            }
            //计划维护未完成
            var unhandlePlans = _planItem.GetMachinePlans(start, machineIds, pid, mid)
                .ToList();
            var completePlans = _planItem.GetPlanHistoryListEx(start, machineIds, pid, mid)
                .ToList();
            var locationHelper = new MachineLocationHelper(pid, _plan);
            //待执行
            foreach (var item in unhandlePlans.Select(s => new { s.machine_name, s.machineid }).Distinct())
            {
                var data = new PlanModel
                {
                    machineID = item.machineid,
                    machine_name = item.machine_name,
                    markself = unhandlePlans.Any(f => f.instruction_mid == mid && f.machineid == item.machineid) ? 1 : 0,
                    standard_time = unhandlePlans.Where(f => f.machineid == item.machineid).Sum(s => s.standard_time),
                    count = unhandlePlans.Count(f => f.machineid == item.machineid),
                };
                var location = locationHelper.GetPositionByMachineId(item.machineid);
                if (location.Any())
                {
                    data.Location = locationHelper.GetLocations(location);
                }
                waitHandleModel.plans.Add(data);
            }
            //已完成
            foreach (var item in completePlans.Select(s => new { s.machine_name, s.machineid }).Distinct())
            {
                var data = new PlanModel
                {
                    machineID = item.machineid,
                    machine_name = item.machine_name,
                    markself = completePlans.Any(f => f.instruction_mid == mid && f.machineid == item.machineid) ? 1 : 0,
                    standard_time = completePlans.Where(f => f.machineid == item.machineid).Sum(s => s.standard_time),
                    count = completePlans.Count(f => f.machineid == item.machineid),
                };
                var location = locationHelper.GetPositionByMachineId(item.machineid);
                if (location.Any())
                {
                    data.Location = locationHelper.GetLocations(location);
                }
                completeModel.plans.Add(data);
            }
            waitHandleModel.count = waitHandleModel.plans.Count;
            completeModel.count = completeModel.plans.Count;
            result.Add(waitHandleModel);
            result.Add(completeModel);
            return new ObjectResult(result);
        }
        /// <summary>
        /// 当月计划维护 正常
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MouthPlanList()
        {
            var startTime =
                (int)UnixTimeHelper.ConvertDataTimeLong(DateTime.Now.ToString(ParameterConstant.YearMonthFormat)
                    .ToDateTime());
            var planlist = new List<PlanModel>();

            var machineIds = _calendarRepository.GetList(q =>
                    q.user_mid == UserId && q.project_id == ProjectId && q.status == (int)RowState.Valid && q.date == DateTime.Now.Date).Select(q => q.machine_id)
                .Distinct().ToList();

            if (machineIds.Any())
            {
                //计划维护历史（已完成）
                var res1 = _planItem.GetPlanHistoryListByMid(startTime, machineIds, ProjectId, UserId).ToList();
                if (res1.Any())
                {
                    var machineList1 = res1.Select(t => t.machineid).Distinct().ToList();
                    var locationHelper = new MachineLocationHelper(ProjectId, _plan);
                    foreach (var p in machineList1)
                    {
                        var model = new PlanModel();
                        var location = locationHelper.GetPositionByMachineId(p);
                        if (location.Any())
                        {
                            model.Location = locationHelper.GetLocations(location);
                        }

                        model.machineID = p;
                        model.markself = 0;
                        int count = 0;
                        int standardTime = 0;
                        foreach (var q in res1)
                        {
                            if (q.machineid == p)
                            {
                                if (q.actual_mid == UserId || q.create_mid == UserId)
                                {
                                    model.markself = 1;
                                }

                                standardTime += q.standard_time;
                                count++;
                            }
                        }
                        model.standard_time = standardTime;
                        model.count = count;
                        if (model.markself == 1)
                        {
                            planlist.Add(model);
                        }
                    }
                }
            }

            return new ObjectResult(planlist);
        }

        /// <summary>
        /// 当日计划维护 未执行-逾期 不用筛选人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UnExecutePlanList()
        {
            var planlist = new List<PlanModel>();
            var time = UnixTimeHelper.GetTodayUnix();
            var endTodayUnix = time + 86400;

            //var sectionIdList = new List<int>();
            //var sectionIdInfoArr = _plan.GetStationID(UserId, UnixTimeHelper.GetNow()).ToList();
            var machineIds = _calendarRepository.GetList(q =>
                    q.user_mid == UserId && q.project_id == ProjectId && q.status == (int)RowState.Valid && q.date == DateTime.Now.Date).Select(q => q.machine_id)
                .Distinct().ToList();

            if (machineIds.Any())
            {
                var res = _planItem.GetPlanListByMid(endTodayUnix, machineIds, ProjectId, 0).ToList();
                if (res.Any())
                {
                    var machineList = res.Select(t => t.machineid).Distinct().ToList();
                    var locationHelper = new MachineLocationHelper(ProjectId, _plan);
                    foreach (var p in machineList)
                    {
                        var model = new PlanModel();
                        var location = locationHelper.GetPositionByMachineId(p);
                        if (location.Any())
                        {
                            model.Location = locationHelper.GetLocations(location);
                        }

                        model.machineID = p;
                        model.markself = 0;
                        int count = 0;
                        int standardTime = 0;

                        var overdue = new List<int>();
                        foreach (var q in res)
                        {
                            if (q.machineid == p)
                            {
                                if (q.instruction_mid > 0 && q.instruction_mid == UserId)
                                {
                                    model.markself = 1;
                                }
                                if (q.instruction_time < time)
                                {
                                    overdue.Add((int)Math.Ceiling((decimal)(time - q.instruction_time) / 86400));
                                }
                                standardTime += q.standard_time;
                                count++;
                            }
                            model.overdue = overdue.Any() ? overdue.Max() : 0;
                            model.standard_time = standardTime;
                            model.count = count;
                        }
                        planlist.Add(model);
                    }
                }
            }

            return new ObjectResult(planlist);
        }

        /// <summary>
        /// 计划维护项点
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PlanListByMachine([FromBody]RequestListByMachineId req)
        {
            var time = UnixTimeHelper.GetTodayUnix();
            if (req.machineID.ToInt() == 0)
            {
                throw new ServerException(900027);
            }

            var user = _projectUserRepository.Get(q => q.mid == UserId);
            
            List<GetAppPlan> planList;
            if (req.state == 1)//已完成数据
            {
                planList = _planItem.GetPlanHistoryListEx(time, new List<int> { req.machineID.ToInt() }, ProjectId, UserId)
                .OrderBy(t => t.instruction_time).ToList();
            }
            else //未完成
            {
                planList = _planItem.GetMachinePlans(time, new List<int> { req.machineID.ToInt() }, ProjectId, UserId)
                .OrderBy(t => t.instruction_time).ToList();
            }

            if (!planList.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var standardTime = 0;
            var dataList = new List<PlanListModel>();
            foreach (var plan in planList)
            {
                ////如果逾期到下一个执行日期之后，则不显示(补充容差)
                //var nextTime = _planTime.GetList(pl =>
                //        pl.planid == plan.planid && pl.projectid == ProjectId && pl.status == (int)RowState.Valid
                //        && pl.instruction_time > plan.instruction_time)
                //    .OrderBy(pl => pl.instruction_time).FirstOrDefault();
                //if (nextTime != null && nextTime.instruction_time - plan.space_time * 86400 < (int)UnixTimeHelper.ConvertDataTimeLong(DateTime.Now.Date))
                //{
                //    continue;
                //}

                var model = Mapper<GetAppPlan, PlanListModel>.Map(plan);
                model.overdue = (int)Math.Ceiling((decimal)(time - plan.instruction_time) / 86400);
                model.create_time = UnixTimeHelper.ConvertIntDate(plan.create_time);
                model.yeartime = UnixTimeHelper.ConvertIntDate(plan.instruction_time);
                model.itemid = plan.id;
                model.keep_remark = plan.remark.ToStr();

                model.makeself = 2;
                if (plan.instruction_mid > 0)
                {
                    if (plan.instruction_mid == UserId)
                    {
                        model.makeself = 1;
                    }
                    else
                    {
                        model.makeself = 0;
                    }
                }
                dataList.Add(model);
                standardTime += plan.standard_time;
            }

            //根据设备id获取所有与之相关的人的mid数组                        
            var sectionIdArr = new List<int>();
            var section = _machineAttributionRepository.Get(q => q.machine == req.machineID.ToInt() && q.projectid == ProjectId && q.status == (int)RowState.Valid
                                                                 && q.attribution == 1);
            if (section != null)
            {
                sectionIdArr.Add(section.station);
            }
            var sectionMidArr = new List<int>();
            if (sectionIdArr.Any())
            {
                sectionMidArr = _plan.ListAllMidArrBySectionIDArr(sectionIdArr, UnixTimeHelper.GetNow()).ToList();
            }
            var userNames = _userRepository.GetList(t => sectionMidArr.Contains(t.mid) && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid).Select(t => t.name).ToList();

            var locationHelper = new MachineLocationHelper(ProjectId, _plan);
            var res = new PlanListList
            {
                standard_time = standardTime,
                planlist = dataList,
                location = string.Join('-', locationHelper.GetPositionByMachineId(req.machineID.ToInt())),
                count = dataList.Count,
                machine_person = string.Join(',', userNames)
            };

            return new AppPlanResultResult
            {
                data = res
            };
        }

        /// <summary>
        /// 计划准时率分析
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PlanPunctual()
        {
            var time = UnixTimeHelper.GetTodayUnix() + 86400;
            var result = new List<PlanPuntualModel>();

            var machineIds = _calendarRepository.GetList(q => q.user_mid == UserId && q.date == DateTime.Now.Date).Select(m => m.machine_id).Distinct().ToList();
            if (machineIds.Any())
            {
                var startTime = time - 86400 * 7;
                var endTime = time - 1;

                var res2 = _planTime.SearchPlanDay(0, startTime, endTime, machineIds, ProjectId).ToList();

                var a = startTime + 3600 * 24;
                var a1 = (int)UnixTimeHelper.ConvertDataTimeLong(UnixTimeHelper.ConvertIntDate(a).ToDateTime());//第二天0时0分0秒
                var a2 = (int)UnixTimeHelper.ConvertDataTimeLong(UnixTimeHelper.ConvertIntDate(endTime).ToDateTime());//最后一天0时0分0秒

                var xData = new List<string>();
                var y1Data = new List<int>();
                var y2Data = new List<int>();

                for (var i = startTime; i <= a2; i += 3600 * 24)
                {
                    var date = UnixTimeHelper.ConvertIntDate(i).ToDateTime();
                    xData.Add(date.Month + "." + date.Day);
                }

                if (!res2.Any())
                {//如果所选日期内没有维修信息
                    for (var i = 0; i < xData.Count(); i++)
                    {
                        result.Add(new PlanPuntualModel
                        {
                            w = xData[i],
                            plannum = 0,
                            executenum = 0
                        });
                    }

                    return new ObjectResult(new ResponsePlanPunctual
                    {
                        dimensions = new List<string>() { "w", "800203", "800202" },
                        source = result
                    });
                }
                var execute2 = 0; var plan2 = 0;
                foreach (var p in res2)
                {
                    if (startTime <= p.instruction_time && p.instruction_time < a1)
                    {
                        plan2++;
                        if (p.information == (int)PlanStatus.Normal)
                        {
                            execute2++;
                        }
                    }
                }
                y1Data.Add(plan2);
                y2Data.Add(execute2);
                for (var i = a1; i < a2; i += 3600 * 24)
                {
                    var execute3 = 0; var plan3 = 0;
                    foreach (var p in res2)
                    {
                        if (i <= p.instruction_time && p.instruction_time < i + 3600 * 24)
                        {
                            plan3++;
                            if (p.information == (int)PlanStatus.Normal)
                            {
                                execute3++;
                            }
                        }
                    }
                    y1Data.Add(plan3);
                    y2Data.Add(execute3);
                }
                var execute4 = 0; var plan4 = 0;
                foreach (var p in res2)
                {
                    if (a2 <= p.instruction_time && p.instruction_time < endTime)
                    {
                        plan4++;
                        if (p.information == (int)PlanStatus.Normal)
                        {
                            execute4++;
                        }
                    }
                }
                y1Data.Add(plan4);
                y2Data.Add(execute4);

                for (var i = 0; i < xData.Count; i++)
                {
                    result.Add(new PlanPuntualModel
                    {
                        w = xData[i],
                        plannum = y1Data[i],
                        executenum = y2Data[i]
                    });
                }

                var results = new ResponsePlanPunctual
                {
                    dimensions = new List<string>() { "w", "800203", "800202" },
                    source = result
                };

                return new ObjectResult(results);
            }
            else
            {
                throw new ServerException(900680);
            }
        }

        /// <summary>
        /// 计划维护历史查看
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PlanHistoryInfo([FromBody]RequestListByMachineIdDateType req)
        {
            if (req.machineID.ToInt() == 0)
            {
                throw new ServerException(900027);
            }
            var time = UnixTimeHelper.GetTodayUnix();
            if (req.DateType == 1)
            {
                time = UnixTimeHelper.GetMouthUnix();
            }
            var user = _projectUserRepository.Get(q => q.mid == UserId);
            
            var res = _planItem.GetPlanHistory(time, req.machineID.ToInt(), ProjectId, UserId)
                .ToList();
            if (!res.Any())
            {
                throw new ServerException(900111);
            }
            var result = new List<PlanHistoryInfoModel>();
            var standardTime = 0;
            foreach (var v in res)
            {
                var model = Mapper<GetAppPlans, PlanHistoryInfoModel>.Map(v);
                if (v.actual_mid == UserId || v.create_mid == UserId)
                {
                    model.makeself = 1;
                }
                standardTime += v.standard_time;

                model.yeartime = UnixTimeHelper.ConvertIntDate(v.instruction_time);
                model.actual_time = UnixTimeHelper.ConvertIntDate(v.create_time);

                if (!string.IsNullOrEmpty(v.sparepartouts))
                {
                    var sparepartHelper = new SparepartHelper(ProjectId, UserId, _sparepartRecord, _sparepartRepository);
                    model.sparepartout = string.Join(',', sparepartHelper.GetSparepartNameNum(v.sparepartouts));
                    model.sparepartids = string.Join(',', sparepartHelper.GetSaprepartIdNum(v.sparepartouts));
                }
                else
                {
                    model.sparepartout = "";
                    model.sparepartids = "";
                }

                if (!string.IsNullOrWhiteSpace(model.corepairer))
                {
                    model.corepairer_names = _calendarRepository.GetUserNamesByMids(model.corepairer, ProjectId);
                }

                result.Add(model);
            }
            var locationHelper = new MachineLocationHelper(ProjectId, _plan);
            var location = locationHelper.GetPositionByMachineId(req.machineID.ToInt());

            //根据设备id获取所有与之相关的人的mid数组                        
            var sectionIdArr = new List<int>();
            var section = _machineAttributionRepository.Get(q => q.machine == req.machineID.ToInt() && q.projectid == ProjectId && q.status == (int)RowState.Valid
                                                                 && q.attribution == 1);
            if (section != null)
            {
                sectionIdArr.Add(section.station);
            }
            var sectionMidArr = new List<int>();
            if (sectionIdArr.Any())
            {
                sectionMidArr = _plan.ListAllMidArrBySectionIDArr(sectionIdArr, UnixTimeHelper.GetNow()).ToList();
            }
            var userNames = _userRepository.GetList(t => sectionMidArr.Contains(t.mid) && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid).Select(t => t.name).ToList();

            var planlist = new PlanHistoryInfoList
            {
                Location = string.Join('-', location),
                standard_time = standardTime,
                count = result.Count,
                machine_person = string.Join(',', userNames),
                planlist = result
            };
            return new AppPlanHistoryResult
            {
                data = planlist
            };
        }

        /// <summary>
        /// 执行计划维护(支持逐条执行)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ExecutionPlan([FromBody]RequestExecutionPlan req)
        {
            if (req.planlist == null || !req.planlist.Any())
            {
                throw new ServerException(900027);
            }

            foreach (var item in req.planlist)
            {
                if (!string.IsNullOrEmpty(item.value) && RegexHelper.InputRegex(item.value))
                {
                    throw new ServerException(800064);
                }
            }
            foreach (var plan in req.planlist)
            {
                if (plan.itemid > 0 && !string.IsNullOrEmpty(plan.value) && plan.value_type > 0 && plan.planid > 0)
                {
                    var currentPlanTime = _planTime.Get(t =>
                        t.projectid == ProjectId && t.status == (int)RowState.Valid && t.id == plan.timeid);
                    if (currentPlanTime == null)
                    {
                        continue;
                    }

                    var result1 = _planRecord.GetList(t =>
                        t.projectid == ProjectId && t.planid == plan.planid && t.itemid == plan.itemid &&
                        t.plan_time_id == plan.timeid && t.status == (int)RowState.Valid);
                    if (result1.Any())
                    {
                        foreach (var record in result1)
                        {
                            record.status = (int)RowState.Invalid;
                            _planRecord.Update(record);
                        }
                    }

                    var planRecord = new siger_project_plan_record
                    {
                        projectid = ProjectId,
                        status = (int)RowState.Valid,
                        planid = plan.planid,
                        itemid = plan.itemid,
                        plan_time_id = plan.timeid,
                        create_mid = UserId,
                        actual_mid = req.actual_mid,
                        value = plan.value,
                        imgurl = plan.images,
                        sparepartout = plan.sparepartoutid,
                        create_time = UnixTimeHelper.GetNow(),
                        actual_standard_time = plan.standard_time,
                        corepairer = plan.corepairer
                    };
                    //var sparepartHelper = new SparepartHelper(ProjectId, UserId, _sparepartRecord, _sparepartRepository);
                    if (plan.value_type == 1)
                    {
                        if (!string.IsNullOrEmpty(plan.value) && plan.value.Trim() == "true")
                        {
                            var ptime = _planTime.Get(t =>
                                t.status == (int)RowState.Valid && t.projectid == ProjectId && t.id == plan.timeid);
                            if (ptime != null)
                            {
                                ptime.information = (int)PlanStatus.Normal;
                                ptime.keep_remark = plan.keep_remark ?? "";
                                ptime.hit_type = plan.hit_type.ToInt();
                                _planTime.Update(ptime);

                                _planRecord.Insert(planRecord);

                                //var resultPlanTable = _plan.Get(t => t.id == plan.planid);
                                //if (resultPlanTable != null)
                                //{
                                //    var sparepartOuts = sparepartHelper.CheckSparepart(plan.sparepartoutid, "");//没有旧的备件绑定数据
                                //    sparepartHelper.SparepartOutIn(new Dictionary<int, int>(), sparepartOuts["new"],
                                //        plan.timeid.ToString(), resultPlanTable.machineid,
                                //        (int) OutStockCategory.PlanRepair);
                                //}

                                SubmitSpareparts(plan.sparepartoutid, plan.itemid);
                            }
                        }
                    }
                    else if (plan.value_type > 1)
                    {
                        if (!string.IsNullOrEmpty(plan.value))
                        {
                            var ptime = _planTime.Get(t =>
                                t.status == (int)RowState.Valid && t.projectid == ProjectId && t.id == plan.timeid);
                            if (ptime != null)
                            {
                                ptime.information = (int)PlanStatus.Normal;
                                ptime.hit_type = plan.hit_type.ToInt();
                                ptime.keep_remark = plan.keep_remark ?? "";
                                _planTime.Update(ptime);

                                _planRecord.Insert(planRecord);

                                //var resultPlanTable = _plan.Get(t => t.id == plan.planid);
                                //if (resultPlanTable != null)
                                //{
                                //    var sparepartOuts = sparepartHelper.CheckSparepart(plan.sparepartoutid, "");//没有旧的备件绑定数据
                                //    sparepartHelper.SparepartOutIn(new Dictionary<int, int>(), sparepartOuts["new"],
                                //        plan.timeid.ToString(), resultPlanTable.machineid,
                                //        (int)OutStockCategory.PlanRepair);
                                //}

                                SubmitSpareparts(plan.sparepartoutid, plan.itemid);
                            }
                        }
                    }
                }
            }

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

        private void SubmitSpareparts(string sparepartids, int planitemId)
        {
            if (string.IsNullOrWhiteSpace(sparepartids))
            {
                return;
            }
            var newSparepartArr = new Dictionary<int, int>();

            var newspareparts = sparepartids.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
            foreach (var spa in newspareparts)
            {
                var idcount = spa.Split('*', StringSplitOptions.RemoveEmptyEntries);
                if (idcount.Any() && idcount.Length > 1 && idcount[0].ToInt() > 0 && idcount[1].ToInt() > 0)
                {
                    if (newSparepartArr.ContainsKey(idcount[0].ToInt()))
                    {
                        continue;
                    }
                    newSparepartArr.Add(idcount[0].ToInt(), idcount[1].ToInt());
                }
            }

            var spids = newSparepartArr.Keys.ToList();
            //是否有审核件
            var needApproval = _sparepartRepository.Get(q =>
                spids.Contains(q.id) && q.approvaluser_mid > 0 && q.status == (int)RowState.Valid);

            _auditRepository.AddPlanPrepareSpareparts(newSparepartArr, planitemId, ProjectId, UserId, needApproval != null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetLocationByMachineId([FromBody]RequestListByMachineId req)
        {
            var locationHelper = new MachineLocationHelper(ProjectId, _plan);
            var location = locationHelper.GetPositionByMachineId(req.machineID.ToInt());
            return new ObjectResult(location);
        }

        [HttpPost]
        public IActionResult PlanSign([FromBody]RequestListByMachineId req)
        {
            if (req.machineID.ToInt() == 0)
            {
                throw new ServerException(900027);
            }
            var signs = _plan.GetTodayPlanSigns(req.machineID.ToInt(), UserId, ProjectId);
            if (signs.Any())
            {
                return new ObjectResult(CommonEnum.Succefull); //throw new ServerException(200122);
            }
            var model = new siger_project_plan_sign
            {
                projectid = ProjectId,
                status = (int)RowState.Valid,
                machine_id = req.machineID.ToInt(),
                create_mid = UserId,
                create_time = UnixTimeHelper.GetNow()
            };
            if (_plan.InsertPlanSign(model))
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// skf-app
        /// </summary>
        /// <param name="machineid"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaintainPlan(string machineid, int page, int pagesize)
        {
            var machineId = machineid.ToInt();
            Expression<Func<siger_project_plan, bool>> funMachine = t =>
                t.projectid == ProjectId && t.status == (int)RowState.Valid && t.machineid == machineId && t.starttime <= UnixTimeHelper.GetTodayUnix();
            var plans = _plan.GetPagedList(page, pagesize, funMachine, "starttime", true);
            var res = new List<ResponseGetMaintainPlan>();
            var planIds = plans.Data.Select(t => t.id).ToList();
            var itemIds = plans.Data.Select(t => t.itemid).ToList();
            var items = _planItem.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid && itemIds.Contains(t.id)).ToList();
            var times = _planTime.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                    planIds.Contains(t.planid) && (t.information == (int)PlanStatus.UnExecuted || t.information == (int)PlanStatus.Overdue)).ToList();
            foreach (var plan in plans.Data)
            {
                var item = items.FirstOrDefault(t => t.id == plan.itemid);
                if (item == null)
                {
                    continue;
                }

                var time = times.Where(t => t.planid == plan.id).OrderBy(t => t.information).ToList();
                if (!time.Any())
                {
                    continue;
                }

                res.Add(new ResponseGetMaintainPlan
                {
                    planid = plan.id,
                    name = item.content,
                    status = time.First().information
                });
            }

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

    }
}