using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Common;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common.AppSettings;
using System.IO;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Request;
using Siger.Middlelayer.AccRepository.Response;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;
using Siger.Middlelayer.Common.Helpers;

namespace Siger.ApiACC.Controllers
{
    public class RoutingInStationController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerRoutingInStation _sigerRoutingIn;
        private readonly ISigerDict _sigerDict;
        private readonly ISigerRoutingOutStation _sigerRoutingOut;
        private readonly ISigerProjectProductRepository _sigerProduct;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSection;

        public RoutingInStationController(IUnitOfWork unitOfWork, ISigerRoutingInStation sigerRoutingIn, ISigerProjectLevelSectionRepository sigerProjectLevelSection
            , ISigerDict sigerDict, ISigerRoutingOutStation sigerRoutingOut, ISigerProjectProductRepository sigerProduct)
        {
            _unitOfWork = unitOfWork;
            _sigerRoutingIn = sigerRoutingIn;
            _sigerProjectLevelSection = sigerProjectLevelSection;
            _sigerDict = sigerDict;
            _sigerRoutingOut = sigerRoutingOut;
            _sigerProduct = sigerProduct;
        }
        [HttpGet]
        public IActionResult Getlist(string productId, int line, int station, int page = 1, int pagesize = 10)
        {
            var data = _sigerRoutingIn.GetRoutingInStationPage(ProjectId, line, station, productId, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }
        [HttpPost]
        public IActionResult Add([FromBody]RequestRoutingInStation inStation)
        {
            if (inStation.outstation == inStation.station)
            {
                throw new BadRequestException(RequestEnum.LastStationNotEqualCurrentStation);
            }
            if (string.IsNullOrEmpty(inStation.productid))
                throw new BadRequestException(RequestEnum.ParameterMiss);

            if (_sigerRoutingIn.IsExist(f=>f.projectId==ProjectId && f.Station==inStation.station && f.ProductId==inStation.productid && f.status==(int)RowState.Valid))
                throw new BadRequestException(CommonEnum.RecordExits);

            var outStation = _sigerRoutingOut.Get(t => t.projectId == ProjectId && t.status == (int)RowState.Valid && t.EventNo == inStation.status && t.Station == inStation.station);
            if (outStation == null)
                throw new BadRequestException(AccEnum.Busi_EventNo_Null);

            _sigerRoutingIn.Insert(new SigerTrRoutingInStation
            {
                projectId = ProjectId,
                Line = inStation.line,
                Station = inStation.station,
                ProductId = inStation.productid,
                ResultStatus = outStation.ResultStatus
            });
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpPost]
        public IActionResult Modify([FromBody]RequestUpdateRoutingInStation inStation)
        {
            if (inStation.outstation == inStation.station)
                throw new BadRequestException(RequestEnum.LastStationNotEqualCurrentStation);
            var NewObj = _sigerRoutingIn.Get(inStation.id);
            if (NewObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var routOut = _sigerRoutingOut.Get(f => f.projectId == ProjectId && f.Station==inStation.outstation && f.EventNo == inStation.status);
            if (routOut==null)
                throw new BadRequestException(AccEnum.Busi_EventNo_Null);
            NewObj.Line = inStation.line;
            NewObj.Station = inStation.station;
            NewObj.ProductId = inStation.productid;
            NewObj.ResultStatus = routOut.ResultStatus;
            _sigerRoutingIn.Update(NewObj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpGet]
        public IActionResult Delete(int id)
        {
            var NewObj = _sigerRoutingIn.Get(id);
            if (NewObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            NewObj.status = (int)RowState.Invalid;
            _sigerRoutingIn.Update(NewObj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult duplicate([FromBody]RequestDuplicate model)
        {
            var lists = _sigerRoutingIn.GetDataList(model.fromline, model.toline, ProjectId);
            var insertedList = new List<SigerTrRoutingInStation>();
            foreach (var item in lists)
            {
                var InStation = _sigerRoutingIn.Get(t => t.Line == item.Line && t.Station == item.Station && t.ResultStatus == item.ResultStatus
                     && t.ProductId == item.ProductId && t.status == (int)RowState.Valid && t.projectId == ProjectId);
                var OutStation = _sigerRoutingOut.Get(t => t.projectId == ProjectId && t.status == (int)RowState.Valid && t.ResultStatus == item.ResultStatus
                    && t.Station == item.Station);
                if (InStation == null && OutStation == null)
                {
                    _sigerRoutingIn.Insert(item);
                    insertedList.Add(item);
                }
            }

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

        [HttpGet]
        public IActionResult ExportAll(string productid, int line, int station)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            var query = _sigerRoutingIn.GetRoutingInList(productid, line, station, ProjectId).ToList();
            if (!query.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var dataList = new List<RoutingInStationTemplate>();
            foreach (var item in query)
            {
                dataList.Add(new RoutingInStationTemplate
                {
                    line = item.line_value,
                    station = item.station_value,
                    productid = item.productid_value,
                    status = item.status_value
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<RoutingInStationTemplate> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<RoutingInStationTemplate>();
                    var temporaryFileName = $"进站维护信息_RoutingInStationInfo_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(dataList, Path.Combine(rootDir, temporaryFileName));
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("ExportEquipmentPosition failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 获取路由可视化数据
        /// </summary>
        /// <param name="line"></param>
        /// <param name="product_id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetJson(int line, string product_id)
        {
            if (!(line > 0) || string.IsNullOrEmpty(product_id))
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var lists = _sigerRoutingIn.GetRoutingStations(line, product_id, ProjectId).ToList();
            if (lists.Any())
            {
                var response = new ResponseRouteStaionJson();
                response.productid = product_id;
                response.productid_value = lists[0].productid_value;
                response.line = line;
                var nodearr = new List<nodeDataArrayModel>();
                var nodearr2 = new List<nodeDataArrayModel>();
                var linkdata = new List<linkDataArrayModel>();
                var firstlists = lists.Where((x, i) => lists.FindIndex(z => z.station == x.station) == i);
                int k = 1;
                foreach (var item in firstlists)
                {
                    int nodetype = 1;
                    var staions = lists.FindAll(t => t.station == item.station);
                    var nodetypeto = _sigerRoutingOut.GetList(t => t.Station == item.station && t.status == (int)RowState.Valid && t.projectId == ProjectId);
                    if (nodetypeto.Any())
                    {
                        nodetype = nodetypeto.FirstOrDefault(t => t.EventNo == (int)EventNo_Status.Fail) != null ? (int)EventNo_Status.Fail : (int)EventNo_Status.Success;
                    }
                    nodearr.Add(new nodeDataArrayModel
                    {
                        station = item.station,
                        text = item.station_value,
                        key = "N" + item.station,
                        nodeHeight = nodetype == 2 ? "80px" : "60px",
                        nodeType = nodetype == 2 ? "gateWay" : "comm",
                        nodeWidth = nodetype == 2 ? "80px" : "100px",
                        locLeft = item.locleft > 0 ? item.locleft : 520,
                        locTop = item.loctop > 0 ? item.loctop : 270,
                        bgColor = string.IsNullOrEmpty(item.bgcolor) ? "#6babdc" : item.bgcolor
                    });
                    foreach (var model in staions)
                    {
                        int nodetypefrom = 1;
                        var nodetypefromlist = _sigerRoutingOut.GetList(t => t.Station == model.fromstation && t.status == (int)RowState.Valid && t.projectId == ProjectId).ToList();
                        if (nodetypefromlist.Any())
                        {
                            nodetypefrom = nodetypefromlist.FirstOrDefault(t => t.EventNo == (int)EventNo_Status.Fail) != null ? (int)EventNo_Status.Fail : (int)EventNo_Status.Success;
                        }
                        var stationmodel = _sigerProjectLevelSection.Get(t => t.id == model.fromstation && t.projectid == ProjectId && t.status == (int)RowState.Valid);
                        if (stationmodel != null)
                        {
                            nodearr2.Add(new nodeDataArrayModel
                            {
                                station = model.fromstation,
                                text = stationmodel.title,
                                key = "N" + stationmodel.id,
                                nodeHeight = nodetype == 2 ? "80px" : "60px",
                                nodeType = nodetype == 2 ? "gateWay" : "comm",
                                nodeWidth = nodetype == 2 ? "80px" : "100px",
                                locLeft = model.fromlocleft > 0 ? model.fromlocleft : 520,
                                locTop = model.fromloctop > 0 ? model.fromloctop : 270,
                                bgColor = string.IsNullOrEmpty(model.frombgcolor) ? "#6babdc" : model.frombgcolor
                            });
                        }
                        var routers = lists.Where(t => t.fromstation == model.fromstation && t.station == model.station || t.fromstation == model.station && t.station == model.fromstation);
                        var linkMode = linkdata.FirstOrDefault(t => t.from == "N" + model.station.ToStr() && t.to == "N" + model.fromstation.ToString());
                        var anchors = new string[] { };
                        if (routers.Any())
                        {
                            var routerGrouBy = routers.GroupBy(t => t.fromstation);
                            if (routerGrouBy.Any() && routerGrouBy.Count() > 1)
                            {
                                anchors = linkMode != null ? (linkMode.sourceAnchors[0] == "Left" ? new string[] { "Right" } : new string[] { "Left" }) : new string[] { "Left" };
                            }
                        }
                        else
                        {
                            anchors = new string[] { "Bottom", "Right", "Top", "Left" };
                        }
                        linkdata.Add(new linkDataArrayModel
                        {
                            from = "N" + model.fromstation,
                            to = "N" + model.station,
                            routerId = "R" + k.ToString("00000"),
                            label = model.result_value,
                            status = model.status_value,
                            status_value = model.status_value,
                            fromid = model.fromid,
                            toid = model.id,
                            sourceAnchors = anchors,
                            targetAnchors = anchors,
                            result = model.result
                        });
                        k++;
                    }
                }
                var stations = _sigerRoutingOut.GetList(t => firstlists.FirstOrDefault(p => p.station == t.Station) == null && t.status == (int)RowState.Valid
                                        && t.projectId == ProjectId && t.Line == line &&
                                        lists.FirstOrDefault(q => q.resultstatus == t.ResultStatus.ToString()) != null).ToList();

                if (stations.Any())
                {
                    var stationList = stations.OrderBy(t => t.Line).OrderBy(t => t.Station).ToList();
                    var fireststations = stationList.Where((x, i) => stationList.FindIndex(z => z.Station == x.Station) == i);
                    int nodetype = 1;
                    foreach (var item in fireststations)
                    {
                        var station = _sigerProjectLevelSection.Get(t => t.id == item.Station && t.projectid == ProjectId && t.status == (int)RowState.Valid);
                        if (station != null)
                        {
                            var nodetypelist = _sigerRoutingOut.GetList(t => t.Station == item.Station && t.status == (int)RowState.Valid && t.projectId == ProjectId);
                            if (nodetypelist.Any())
                            {
                                nodetype = nodetypelist.FirstOrDefault(t => t.EventNo == (int)EventNo_Status.Fail) != null ? (int)EventNo_Status.Fail : (int)EventNo_Status.Success;
                            }
                            decimal locleft = 520; decimal loctop = 270; var bgcolor = "#6babdc";
                            var lastnode = lists.FirstOrDefault(t => t.resultstatus == item.ResultStatus && t.fromstation == item.Station);
                            if (lastnode != null)
                            {
                                locleft = lastnode.fromlocleft > 0 ? lastnode.fromlocleft : locleft;
                                loctop = lastnode.fromloctop > 0 ? lastnode.fromloctop : loctop;
                                bgcolor = !string.IsNullOrEmpty(lastnode.frombgcolor) ? lastnode.frombgcolor : bgcolor;
                            }
                            nodearr.Add(new nodeDataArrayModel
                            {
                                station = item.Station,
                                text = station.title,
                                key = "N" + station.id,
                                nodeHeight = nodetype == 2 ? "80px" : "60px",
                                nodeType = nodetype == 2 ? "gateWay" : "comm",
                                nodeWidth = nodetype == 2 ? "80px" : "100px",
                                locLeft = locleft,//item.locleft > 0 ? item.locleft : 520,
                                locTop = loctop,//item.loctop > 0 ? item.loctop : 270,
                                bgColor = bgcolor//string.IsNullOrEmpty(item.bgcolor) ? "#6babdc" : item.bgcolor
                            });
                        }
                    }
                }

                if (nodearr.Any() && linkdata.Any())
                {
                    int j = 1;
                    int g = 1;
                    foreach (var node in nodearr)
                    {
                        var nodekey = node.key;
                        var newkey = node.nodeType == "gateWay" ? "G" + g.ToString("00000") : "T" + j.ToString("00000");
                        var nodeModel = nodearr.Find(t => t.key == nodekey).key = newkey;
                        var links = linkdata.Where(t => t.from == nodekey);
                        foreach (var link in links)
                        {
                            linkdata.Find(t => t.routerId == link.routerId).from = newkey;
                        }
                        links = linkdata.Where(t => t.to == nodekey);
                        foreach (var link in links)
                        {
                            linkdata.Find(t => t.routerId == link.routerId).to = newkey;
                        }
                        if (node.nodeType == "gateWay")
                            g++;
                        else
                            j++;
                    }
                }
                response.nodeDataArray = nodearr;
                response.linkDataArray = linkdata;

                return new ObjectResult(response);
            }
            else
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
        }

        [HttpPost]
        public IActionResult SaveJson([FromBody]ResquestRouteStaionJson res)
        {
            var nodearr = res.obj.nodeDataArray;
            var linkdata = res.obj.linkDataArray;

            var routOuts = new List<SigerTrRoutingOutStation>();
            var routInOuts = new List<ResponseRoutingInStation>();

            var statusKeyList = new List<string>();
            //判断是否有节点没有设置工站
            foreach (var arr in nodearr)
            {
                if (!(arr.station > 0))
                {
                    throw new BadRequestException(RequestEnum.HaveNodeNotSetStation);
                }
            }
            //判断字典中是否存在失败,成功的结果
            var faildict = _sigerDict.Get(t => t.cat == AccDictCostNoProjectId.eventno && t.status == (int)RowState.Valid && t.dkey == ((int)EventNo_Status.Fail).ToStr());
            //结果字典值-失败或成功 未配置
            if (faildict == null)
            {
                throw new BadRequestException(RequestEnum.ResultDictNotSet);
            }
            //工站数据重复
            if (nodearr.Any() && nodearr.Select(t => t.station).Distinct().Count() < nodearr.Count())
            {
                throw new BadRequestException(RequestEnum.StationRepeat);
            }
            //判断数据是否有误，并把传入的json数据整理成出站列表和入站列表
            foreach (var p in nodearr)
            {
                //获取所有出战和入站的线
                var links = linkdata.Where(t => t.from == p.key || t.to == p.key).ToList();
                if (!links.Any())
                {
                    throw new BadRequestException(RequestEnum.NodeNoLink);//有的节点没有出入站(连接线)
                }
                if (string.IsNullOrEmpty(p.nodeType))
                {
                    throw new BadRequestException(RequestEnum.NodeTypeError);//节点类型值错误
                }
                var linksFrom = links.Where(t => t.from == p.key);
                if (!string.IsNullOrEmpty(p.nodeType) && p.nodeType.ToLower() == "gateway")
                {
                    if (linksFrom.FirstOrDefault(t => t.label == faildict.dval) == null)
                    {
                        links.Add(new linkDataArray
                        {
                            from = p.key,
                            to = "DeFaultFailStation",
                            label = faildict.dval
                        });
                    }
                }
                else
                {
                    if (linksFrom.FirstOrDefault(t => t.label == faildict.dval) != null)
                    {
                        throw new BadRequestException(RequestEnum.RectangleNodeOnlySuccess);//comm类型的长方形只能有成功的结果
                    }
                }
                foreach (var link in links)
                {
                    var dict = _sigerDict.Get(t => t.status == (int)RowState.Valid && t.cat == AccDictCostNoProjectId.eventno && t.dval == link.label);
                    if (dict == null)
                    {
                        throw new BadRequestException(RequestEnum.LinkNoResult);//没有选择结果的线
                    }
                    var status = "";
                    var stationModel = _sigerRoutingOut.Get(t => t.Line == res.line && t.Station == p.station && t.status == (int)RowState.Valid
                        && t.projectId == ProjectId && t.EventNo == dict.dkey.ToInt());//查找出站数据是否已经存在
                    if (stationModel != null)
                    {
                        //stationModel.status = (int)RowState.Invalid;
                        //_sigerRoutingOut.Update(stationModel);
                        status = stationModel.ResultStatus;
                    }
                    if (!string.IsNullOrEmpty(status))
                    {
                        statusKeyList.Add(status);
                    }
                    //如果已经添加的出站数据不用重复添加
                    if (link.from == p.key && routOuts.FirstOrDefault(t => t.Line == res.line && t.Station == p.station && t.EventNo == dict.dkey.ToInt()) == null)
                    {
                        routOuts.Add(new SigerTrRoutingOutStation
                        {
                            Line = res.line,
                            Station = p.station,
                            EventNo = dict.dkey.ToInt(),
                            locleft = p.locLeft,
                            loctop = p.locTop,
                            nodeheight = p.nodeHeight,
                            nodewidth = p.nodeWidth,
                            bgcolor = p.bgColor,
                            ResultStatus = status,//这里如果已有数据是有值的，如果没有数据就是空字符串，在后面用于判断是新增的出站还是原有的出站数据
                            projectId = ProjectId
                        });
                    }
                    else
                    {
                        var fromNode = nodearr.FirstOrDefault(t => t.key == link.from);
                        if (fromNode == null)
                        {
                            throw new BadRequestException(RequestEnum.LinkNoBindNode);//这条线没有绑定节点
                        }
                        if (routInOuts.FirstOrDefault(t => t.line == res.line && t.productid == res.product_id && t.station == p.station && t.eventno == dict.dkey.ToInt() && t.outstation == fromNode.station) == null)
                        {
                            routInOuts.Add(new ResponseRoutingInStation
                            {
                                line = res.line,
                                productid = res.product_id,
                                station = p.station,
                                eventno = dict.dkey.ToInt(),
                                outstation = fromNode.station
                            });
                        }
                    }
                }
            }

            #region 获取所有当前产线-工站-产品编号下的入站数据，然后删除
            var routInList = _sigerRoutingIn.GetList(t => t.Line == res.line && t.ProductId == res.product_id && t.projectId == ProjectId
                && t.status == (int)RowState.Valid);
            foreach (var p in routInList)
            {
                p.status = (int)RowState.Invalid;
                _sigerRoutingIn.Update(p);
            }
            #endregion

            #region 获取新增数据需要使用的状态值列表
            var dkeyList = new List<string>();
            var allMyRoutOut = _sigerRoutingOut.GetList(t => t.projectId == ProjectId && t.status == (int)RowState.Valid
                && !(statusKeyList.Contains(t.ResultStatus)));//根据状态值列表获取到不在当前产线-工站-产品编号下的出站数据
            statusKeyList.AddRange(allMyRoutOut.Select(t => t.ResultStatus));//把非当前的出站数据的状态值存入statusKeyList
            var dicts = _sigerDict.GetList(t => t.projectId == ProjectId && t.cat == AccDictCost.status && t.status == (int)RowState.Valid
                && (!statusKeyList.Contains(t.dkey)));//获取还未使用的状态值字典列表
            if (dicts.Any())
            {
                dkeyList = dicts.Select(t => t.dkey).ToList();//获取状态值列表（未使用）
            }
            else
            {
                throw new BadRequestException(RequestEnum.StationStatusUseDone);//没有多余的staus可供选择
            }
            #endregion
            #region 插入新增的出站数据
            var insertOuts = routOuts.Where(t => string.IsNullOrEmpty(t.ResultStatus));//获取新增的出站数据，状态值为空的就是新增的
            foreach (var p in insertOuts)
            {
                p.ResultStatus = dkeyList[0];
                dkeyList.Remove(p.ResultStatus);
                var notUniqOne = _sigerRoutingOut.GetList(t => (t.Line == p.Line && t.Station == p.Station && t.EventNo == p.EventNo || t.ResultStatus == p.ResultStatus)
                    && t.projectId == ProjectId && t.status == (int)RowState.Valid).ToList();
                //var notUniqTwo = _sigerRoutingOut.GetList(t => t.ResultStatus == p.ResultStatus);
                if (notUniqOne.Any())
                {
                    throw new BadRequestException(RequestEnum.RoutingOutRepeat);//违背出站唯一性
                }

                _sigerRoutingOut.Insert(p);
            }
            #endregion
            #region 填充节点样式数据,从出站列表获取状态值
            var routingInOuts = new List<ResponseRoutingInStation>();
            var useOuts = new List<SigerTrRoutingOutStation>();//所有需要使用的出站数据
            foreach (var p in routInOuts)
            {
                var routOut = routOuts.FirstOrDefault(t => t.Line == p.line && t.Station == p.outstation && t.EventNo == p.eventno);
                if (routOut == null)
                {
                    throw new BadRequestException(RequestEnum.LastNodeIsEmpty);//没有找到上一站信息，获取不到status
                }
                useOuts.Add(routOut);
                p.resultstatus = routOut.ResultStatus;
                p.fromlocleft = routOut.locleft;
                p.fromloctop = routOut.loctop;
                p.fromnodeheight = routOut.nodeheight;
                p.fromnodewidth = routOut.nodewidth;
                p.frombgcolor = routOut.bgcolor;
                routingInOuts.Add(p);
            }
            #endregion
            //插入入站数据
            foreach (var p in routingInOuts)
            {
                if (routingInOuts.Count(t => t.station == p.station && t.outstation == p.outstation) > 1)
                {
                    throw new BadRequestException(RequestEnum.TwoLinkBindSameNode);//同一个商品，不能同时有两个出站状态到同一个入站
                }
                //if (routingInOuts.Count(t => t.station == p.station && t.line == p.line && t.productid == p.productid) > 1)
                //{
                //    throw new BadRequestException(CommonEnum.Fail);//违背唯一性
                //}
                if (routingInOuts.Count(t => (t.station == p.station && t.outstation == p.outstation || t.station == p.outstation && t.outstation == p.station)
                     && t.eventno != faildict.dkey.ToInt()) > 1)
                {
                    throw new BadRequestException(RequestEnum.OnlyFailResultToLastNode);//只有失败的结果才能回到上一工站循环
                }
                if (p.eventno == faildict.dkey.ToInt() && routingInOuts.Count(t => (t.station == p.station && t.outstation == p.outstation
                      || t.station == p.outstation && t.outstation == p.station)) == 1)
                {
                    throw new BadRequestException(RequestEnum.OnlyBackLastNodeCanbeFailStatus);//只有回到上一工站才能是失败的状态
                }
                var node = nodearr.FirstOrDefault(t => t.station == p.station);
                if (node == null)
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }
                if (p.station != p.outstation)
                {
                    _sigerRoutingIn.Insert(new SigerTrRoutingInStation
                    {
                        Line = p.line,
                        Station = p.station,
                        ProductId = p.productid,
                        projectId = ProjectId,
                        ResultStatus = p.resultstatus,
                        locleft = node.locLeft,
                        loctop = node.locTop,
                        nodeheight = node.nodeHeight,
                        nodewidth = node.nodeWidth,
                        bgcolor = node.bgColor,
                        lastlocleft = p.fromlocleft,
                        lastloctop = p.fromloctop,
                        lastnodeheight = p.fromnodeheight,
                        lastnodewidth = p.fromnodewidth,
                        lastbgcolor = p.fromnodewidth,
                    });
                }
            }
           
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetEventNos(int line, int station)
        {
            var eventno = _sigerRoutingOut.GetList(t => t.Line == line && t.Station == station && t.projectId == ProjectId && t.status == (int)RowState.Valid).ToList();
            var eventlist = eventno.Any() ? _sigerDict.GetList(t => (eventno.FirstOrDefault(p => p.EventNo.ToStr() == t.dkey) == null) && t.status == (int)RowState.Valid
                    && t.cat == AccDictCostNoProjectId.eventno) : _sigerDict.GetList(t => t.status == (int)RowState.Valid && t.cat == AccDictCostNoProjectId.eventno);
            var response = new List<ResponseIdText>();
            if (eventlist.Any())
            {
                foreach (var item in eventlist)
                {
                    response.Add(new ResponseIdText
                    {
                        id = item.dkey,
                        Text = item.dval
                    });
                }
            }
            return new ObjectResult(response);
        }
    }
}