using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiDashboard.Result;
using Siger.Middlelayer.CncRepository.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.DashboardRepository.Entities;
using Siger.Middlelayer.DashboardRepository.Repositories.Interface;
using Siger.Middlelayer.DashboardRepository.Request;
using Siger.Middlelayer.EsopRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.Repository.Entities;
using static Siger.Middlelayer.DashboardRepository.Response.ResponseDashboardRotation;

namespace Siger.ApiDashboard.Controllers
{
    public class DashboardConfigController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly IDashboardCombRepository _dashboardCombRepository;
        private readonly IDashboardPageRepository _dashboardPageRepository;
        private readonly IDashboardCombPageRepository _dashboardCombPageRepository;
        private readonly IDashboardCombPageConditionRepository _combPageConditionRepository;
        private readonly IProductionConfigRepository _productionConfigRepository;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly ISigerProjectLevelRepository _levelRepository;
        private readonly ISigerProjectRepository _projectRepository;
        private readonly IQmsSensorParameterRepository _sensorParameter;
        private readonly IPlanTimeRepository _planTimeRepository;
        private readonly IRepairRepository _repairRepository;
        private readonly IPlanSignRepository _planSignRepository;
        private readonly IEsopDocumentHistoryRepository _esopDocumentHistoryRepository;
        private readonly ISigerProjectMachineTypeRepository _machineTypeRepository;
        private readonly ISigerProjectMachineExtendRepository _machineExtendRepository;
        private readonly ISigerProjectDashboardFixpathRepository _dashboardFixpathRepository;

        /// <inheritdoc />
        public DashboardConfigController(IUnitOfWork unitOfWork, ISigerProjectMachineRepository machineRepository, IDashboardCombRepository dashboardCombRepository, IDashboardPageRepository dashboardPageRepository,
            IDashboardCombPageRepository dashboardCombPageRepository, IDashboardCombPageConditionRepository combPageConditionRepository, ISigerProjectDashboardFixpathRepository dashboardFixpathRepository,
            IProductionConfigRepository productionConfigRepository, ISigerProjectLevelSectionRepository levelSectionRepository, ISigerProjectRepository projectRepository,
            ISigerProjectLevelRepository levelRepository, IQmsSensorParameterRepository sensorParameter, IPlanTimeRepository planTimeRepository, IRepairRepository repairRepository,
            IPlanSignRepository planSignRepository, IEsopDocumentHistoryRepository esopDocumentHistoryRepository, ISigerProjectMachineTypeRepository machineTypeRepository,
            ISigerProjectMachineExtendRepository machineExtendRepository)
        {
            _unitOfWork = unitOfWork;
            _machineRepository = machineRepository;
            _dashboardCombRepository = dashboardCombRepository;
            _dashboardPageRepository = dashboardPageRepository;
            _dashboardCombPageRepository = dashboardCombPageRepository;
            _combPageConditionRepository = combPageConditionRepository;
            _productionConfigRepository = productionConfigRepository;
            _levelSectionRepository = levelSectionRepository;
            _projectRepository = projectRepository;
            _levelRepository = levelRepository;
            _sensorParameter = sensorParameter;
            _planTimeRepository = planTimeRepository;
            _repairRepository = repairRepository;
            _planSignRepository = planSignRepository;
            _esopDocumentHistoryRepository = esopDocumentHistoryRepository;
            _machineTypeRepository = machineTypeRepository;
            _machineExtendRepository = machineExtendRepository;
            _dashboardFixpathRepository = dashboardFixpathRepository;
        }

        [HttpGet]
        public IActionResult GetCombList()
        {
            var data = _dashboardCombRepository.GetDashboardCombs(ProjectId);

            var dataComs = _dashboardCombRepository
                .GetList(q => q.project_id == ProjectId && q.status == (int)RowState.Valid)
                .Select(m => new DataComb
                {
                    cycle = m.cycle,
                    id = m.id,
                    title = m.title
                }).ToList();

            foreach (var com in dataComs)
            {
                com.combList = data.Where(t => t.comb_id == com.id).ToList();
            }

            return new GetCombListResult(data, dataComs);
        }

        [HttpPost]
        public IActionResult AddEditComb([FromBody] RequestAddEditComb request)
        {
            var entity = _dashboardCombRepository.Get(q =>
                q.project_id == ProjectId && q.title == request.comb_title && q.status == (int)RowState.Valid);
            if (entity != null)
            {
                throw new BadRequestException(RequestEnum.NameHasExist);
            }

            var comb = new siger_project_dashboard_comb
            {
                project_id = ProjectId,
                cycle = request.cycle.ToInt(),
                title = request.comb_title
            };
            _dashboardCombRepository.Insert(comb);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(comb.id);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult EditCombChk([FromBody] RequestEditCombChk request)
        {
            var entity = _dashboardCombRepository.Get(q =>
                q.project_id == ProjectId && q.id == request.comb_id && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.title = request.edit_comb_title;
            entity.cycle = request.edit_cycle;
            _dashboardCombRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult EditComb(int id)
        {
            var comb = _dashboardCombRepository.Get(id);
            if (comb == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return new ObjectResult(comb);
        }

        [HttpPost]
        public IActionResult DelCombPage([FromBody] RequestDelCombPage request)
        {
            switch (request.del_type)
            {
                case 1: //remove comb
                    var comb = _dashboardCombRepository.Get(q => q.id == request.comb_id && q.project_id == ProjectId);
                    if (comb == null)
                    {
                        throw new BadRequestException(CommonEnum.RecordNotFound);
                    }
                    var pages = _dashboardCombPageRepository.GetList(q => q.comb_id == request.comb_id && q.status == (int)RowState.Valid);
                    if (pages.Any())
                    {
                        throw new ServerException(500184);
                    }

                    comb.status = (int)RowState.Invalid;
                    _dashboardCombRepository.Update(comb);
                    if (_unitOfWork.Commit() > 0)
                    {
                        return new ObjectResult(CommonEnum.Succefull);
                    }
                    throw new BadRequestException(CommonEnum.Fail);
                case 2: //remove page
                    var page = _dashboardCombPageRepository.Get(q => q.comb_id == request.comb_id && q.id == request.comb_page_id && q.status == (int)RowState.Valid);
                    if (page != null)
                    {
                        _dashboardCombPageRepository.Delete(page);
                        if (_unitOfWork.Commit() > 0)
                        {
                            var conditions = _combPageConditionRepository.GetList(q => q.comb_page_id == request.comb_page_id.ToString() && q.status == (int)RowState.Valid);
                            foreach (var condition in conditions.ToList())
                            {
                                _combPageConditionRepository.Delete(condition);
                            }
                            _unitOfWork.Commit();
                        }
                    }
                    return new ObjectResult(CommonEnum.Succefull);
                default:
                    throw new BadRequestException(CommonEnum.RecordNotFound);
            }
        }

        [HttpGet]
        public IActionResult PostDashboardPageCodeList(string page_code)
        {
            var entities = _dashboardPageRepository.GetList(q => q.page_code == page_code && q.status == (int)RowState.Valid);
            return new ObjectResult(entities);
        }

        /// <summary>
        /// 取产线层级
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSectionTreeForDashboardOld(string patial_code)
        {
            var list = _levelSectionRepository.GetLevelSectionTree(ProjectId).ToList();
            var lastLevel = list.Max(m => m.levelId);
            var machineDatas = _machineRepository.GetLevelSectionMachines(0, ProjectId);

            var responses = new List<LevelSectionTree>();
            //最后一层改为machineid
            foreach (var sectionTree in list)
            {
                var section = Mapper<LevelSectionTree, LevelSectionTree>.Map(sectionTree);
                if (section.levelId == lastLevel)
                {
                    var sectionData = machineDatas.FirstOrDefault(q => q.section_id == sectionTree.id);
                    if (sectionData != null)
                    {
                        if (patial_code == "e_maintenance_status_1")
                        {
                            section.machineid = sectionData.machine_id;
                        }
                        else
                        {
                            section.id = sectionData.machine_id;
                            section.machineid = sectionData.machine_id;
                        }

                        section.disabled = false;
                        responses.Add(section);
                    }
                    else
                    {

                        section.disabled = true;
                        responses.Add(section);
                    }
                }
                else
                {
                    var sonSection = _levelSectionRepository.Get(q => q.parentid == sectionTree.id && q.projectid == ProjectId && q.status == (int)RowState.Valid);
                    sectionTree.disabled = sonSection == null;
                    responses.Add(sectionTree);
                }
            }

            var response = new ResponseLevelSectionChildren(GetTreeNode(responses, 0, lastLevel));

            return new ObjectResult(response);
        }

        /// <summary>
        /// 取产线层级
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSectionTreeForDashboard(string page_id, string patial_code)
        {
            if (!string.IsNullOrWhiteSpace(page_id))
            {
                var list = _levelSectionRepository.GetLevelSectionTree(ProjectId).ToList();
                var lastLevel = list.Max(m => m.levelId);
                var machineDatas = _machineRepository.GetLevelSectionMachines(0, ProjectId);

                var responses = new List<LevelSectionTree>();
                //查询是否有记录
                var combCondition = _combPageConditionRepository.GetList(f => f.comb_page_id == page_id && f.page_patial_code == patial_code);
                Dictionary<string, string> myDic = new Dictionary<string, string>();
                var groupTimeRang = new List<groupTimeRang>();
                foreach (var item in combCondition)
                {
                    if (!string.IsNullOrWhiteSpace(page_id) && !string.IsNullOrWhiteSpace(patial_code))
                    {
                        //判断condition是否有班次时间
                        if (combCondition != null && item.condition.Contains('_'))
                        {
                            //得到tree得id
                            var cfgMachines = item.condition.Split('_').ToList()[0].Split('-').ToList();
                            foreach (var itemTwo in cfgMachines)
                            {
                                if (!myDic.Keys.Contains(itemTwo))
                                {
                                    myDic.Add(itemTwo, item.page_patial_code);
                                }
                            }
                            //先得到所有班次
                            var frequency = item.condition.Split('_').ToList()[1].Split(';').ToList();
                            foreach (var itemTwo in frequency)
                            {
                                //在得到每次班次的名称和时间
                                var cfgMachinetimes = itemTwo.Split('|').ToList();
                                groupTimeRang.Add(new Result.groupTimeRang() { groupname = cfgMachinetimes[0].ToStr(), timerang = cfgMachinetimes[1].ToStr() });

                            }
                        }
                        else
                        {
                            if (combCondition != null && item.condition.Contains('-'))
                            {
                                var cfgMachines = item.condition.Split('-').ToList();
                                foreach (var itemTwo in cfgMachines)
                                {
                                    if (!myDic.Keys.Contains(itemTwo))
                                    {
                                        myDic.Add(itemTwo, item.page_patial_code);
                                    }
                                }
                            }
                            else
                            {
                                if (!myDic.Keys.Contains(item.condition))
                                {
                                    myDic.Add(item.condition, item.page_patial_code);
                                }                                
                            }
                        }
                    }

                    //最后一层改为machineid
                    foreach (var sectionTree in list)
                    {
                        var sectionA = Mapper<LevelSectionTree, LevelSectionTree>.Map(sectionTree);
                        if (sectionA.levelId == lastLevel)
                        {
                            //位置放到下面，判断是否有设备，没有设备的工位不添加到树
                            //responses.Add(sectionTree);

                            //var sectionData = machineDatas.FirstOrDefault(q => q.section_id == sectionTree.id);
                            //                                                                           只要nc得
                            var sectionDatas = machineDatas.Where(q => q.section_id == sectionTree.id && q.category == 1).OrderBy(q => q.machine_id); ;
                            if (sectionDatas.Count() > 0)
                            {
                                responses.Add(sectionTree);
                                foreach (var sectionData in sectionDatas)
                                {
                                    var section = Mapper<LevelSectionTree, LevelSectionTree>.Map(sectionTree);
                                    //responses.Add(new LevelSectionTree {
                                    //   id= sectionData.machine_id,
                                    //   name= sectionData.machine_name,
                                    //   pid= sectionTree.id,
                                    //   levelId= lastLevel+1

                                    //});
                                    if (sectionData != null)
                                    {
                                        if (patial_code == "e_maintenance_status_1")
                                        {
                                            section.machineid = sectionData.machine_id;
                                        }
                                        else
                                        {
                                            section.name = sectionData.machine_name;
                                            section.title = sectionData.machine_name;
                                            //设备id加大，避免设备和工位id相同，出现设备下挂设备情况--改为负数
                                            //section.id = (sectionData.machine_id + "0000").ToInt();
                                            section.id = -sectionData.machine_id;
                                            section.pid = sectionTree.id;
                                            section.machineid = sectionData.machine_id;

                                        }
                                        //判断字典是否存在键
                                        if (!string.IsNullOrWhiteSpace(page_id) && myDic.Values.Contains(patial_code))
                                        {
                                            List<string> keyList = (from q in myDic
                                                                    where q.Value == item.page_patial_code
                                                                    select q.Key).ToList<string>(); //get all keys
                                            if (keyList.Count() > 0)
                                            {
                                                foreach (var itemValue in keyList)
                                                {
                                                    if (itemValue.ToString() == (section.machineid.ToStr()))
                                                    {
                                                        section.@checked = true;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (keyList[0].ToString() == (section.machineid.ToStr()))
                                                {
                                                    section.@checked = true;
                                                }
                                            }

                                        }

                                        section.disabled = false;
                                        responses.Add(section);
                                    }
                                    else
                                    {
                                        section.disabled = true;
                                        responses.Add(section);
                                    }
                                }
                            }
                        }
                        else
                        {
                            var sonSection = _levelSectionRepository.Get(q => q.parentid == sectionTree.id && q.projectid == ProjectId && q.status == (int)RowState.Valid);
                            sectionTree.disabled = sonSection == null;
                            responses.Add(sectionTree);
                        }
                    }

                }
                var response = new ResponseLevelSectionChildren(GetTreeNode(responses, 0, lastLevel, true));
                if (groupTimeRang.Count() > 0)
                {
                    return new GetDashboardtreeResult(response, groupTimeRang);
                }
                else
                {
                    return new ObjectResult(response);
                }
            }
            else
            {
                var list = _levelSectionRepository.GetLevelSectionTree(ProjectId).ToList();
                var lastLevel = list.Max(m => m.levelId);
                var machineDatas = _machineRepository.GetLevelSectionMachines(0, ProjectId);

                var responses = new List<LevelSectionTree>();

                //最后一层改为machineid
                foreach (var sectionTree in list)
                {
                    var sectionA = Mapper<LevelSectionTree, LevelSectionTree>.Map(sectionTree);
                    if (sectionA.levelId == lastLevel)
                    {
                        //位置放到下面，判断是否有设备，没有设备的工位不添加到树
                        //responses.Add(sectionTree);

                        //var sectionData = machineDatas.FirstOrDefault(q => q.section_id == sectionTree.id);
                        //                                                                           只要nc得
                        var sectionDatas = machineDatas.Where(q => q.section_id == sectionTree.id && q.category == 1).OrderBy(q => q.machine_id);
                        if (sectionDatas.Count() > 0)
                        {
                            responses.Add(sectionTree);
                            foreach (var sectionData in sectionDatas)
                            {
                                var section = Mapper<LevelSectionTree, LevelSectionTree>.Map(sectionTree);
                                if (sectionData != null)
                                {
                                    if (patial_code == "e_maintenance_status_1")
                                    {
                                        section.machineid = sectionData.machine_id;
                                    }
                                    else
                                    {
                                        //section.id = sectionData.machine_id;
                                        //section.machineid = sectionData.machine_id;
                                        section.name = sectionData.machine_name;
                                        section.title = sectionData.machine_name;
                                        //设备id加大，避免设备和工位id相同，出现设备下挂设备情况--改为负数
                                        //section.id = (sectionData.machine_id + "0000").ToInt();
                                        section.id = -sectionData.machine_id;
                                        section.pid = sectionTree.id;
                                        section.machineid = sectionData.machine_id;
                                    }
                                    section.disabled = false;
                                    responses.Add(section);
                                }
                                else
                                {
                                    section.disabled = true;
                                    responses.Add(section);
                                }
                            }
                        }

                    }
                    else
                    {
                        var sonSection = _levelSectionRepository.Get(q => q.parentid == sectionTree.id && q.projectid == ProjectId && q.status == (int)RowState.Valid);
                        sectionTree.disabled = sonSection == null;
                        responses.Add(sectionTree);
                    }
                }

                var response = new ResponseLevelSectionChildren(GetTreeNode(responses, 0, lastLevel, true));

                return new ObjectResult(response);
            }


        }

        [HttpGet]
        public ActionResult GetCurrentUserProjectLevel(string page_id, string patial_code)
        {
            var combCondition = _combPageConditionRepository.GetList(f => f.comb_page_id == page_id && f.page_patial_code == patial_code);
            var result = _levelRepository
                .GetList(f => f.status == (int)RowState.Valid && f.projectid == ProjectId)
                .Select(f => new { f.id, f.title, f.levelid }).ToList();
            var resultTwo = new List<siger_project_levelEntity>();
            if (!string.IsNullOrWhiteSpace(page_id))
            {
                foreach (var item in combCondition)
                {
                    if (item != null)
                    {
                        foreach (var itemTwo in result)
                        {
                            siger_project_levelEntity entity = new siger_project_levelEntity();
                            if (itemTwo.id.ToString() == item.condition)
                            {
                                entity.id = itemTwo.id;
                                entity.title = itemTwo.title;
                                entity.levelid = itemTwo.levelid;
                                entity.@checked = true;
                                resultTwo.Add(entity);
                            }
                            else
                            {
                                entity.id = itemTwo.id;
                                entity.title = itemTwo.title;
                                entity.levelid = itemTwo.levelid;
                                entity.@checked = false;
                                resultTwo.Add(entity);
                            }
                        }
                    }
                }
                return new ObjectResult(resultTwo);
            }
            else
            {
                foreach (var itemTwo in result)
                {
                    siger_project_levelEntity entity = new siger_project_levelEntity();
                    entity.id = itemTwo.id;
                    entity.title = itemTwo.title;
                    entity.levelid = itemTwo.levelid;
                    entity.@checked = false;
                    resultTwo.Add(entity);
                }

                return new ObjectResult(resultTwo);
            }
        }

        /// <summary>
        /// Vue产线结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSectionTree(string page_id, string patial_code)
        {
            //根据page_id判断走新逻辑还是旧逻辑
            if (!string.IsNullOrWhiteSpace(page_id))
            {
                var combCondition = _combPageConditionRepository.Get(f => f.comb_page_id == page_id && f.page_patial_code == patial_code);
                var maxLevel = _levelRepository.GetList(f => f.status == (int)RowState.Valid && f.projectid == ProjectId)
                    .OrderByDescending(q => q.id).FirstOrDefault();
                var resp = _levelSectionRepository.GetSectionChildrenFromRotation(combCondition.condition, combCondition.acc_text_value,
                   combCondition.right_article_num, combCondition.right_foot_online, combCondition.right_foot_offline, 0, ProjectId, maxLevel?.levelid ?? 0);
                return new ObjectResult(resp);
            }
            else
            {
                var maxLevel = _levelRepository.GetList(f => f.status == (int)RowState.Valid && f.projectid == ProjectId)
                    .OrderByDescending(q => q.id).FirstOrDefault();
                var alltreedata = _levelSectionRepository.getAllTreeData(ProjectId);
                var resp = _levelSectionRepository.GetSectionChildren(alltreedata, 0, ProjectId, maxLevel?.levelid ?? 0);
                return new ObjectResult(resp);
            }

        }

        /// <summary>
        /// Vue产线结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSectionTreeTwo(string page_id, string patial_code)
        {
            //根据page_id判断走新逻辑还是旧逻辑
            if (!string.IsNullOrWhiteSpace(page_id))
            {
                var combCondition = _combPageConditionRepository.Get(f => f.comb_page_id == page_id && f.page_patial_code == patial_code);
                var maxLevel = _levelRepository.GetList(f => f.status == (int)RowState.Valid && f.projectid == ProjectId)
                    .OrderByDescending(q => q.id).FirstOrDefault();
                var data = new ResponseGetData();
                var fixList = new List<RequestFixs>();
                var result = _dashboardFixpathRepository.GetList(q => q.guid == combCondition.guid && q.status == (int)RowState.Valid).ToList();
                foreach (var item in result)
                {
                    var fix = new RequestFixs
                    {
                        id = item.id,
                        title = item.title,
                        section_id=item.stationid,
                        x = item.x,
                        y = item.y
                    };
                    fixList.Add(fix);
                }
                var resp = _levelSectionRepository.GetSectionChildrenFromRotation(combCondition.condition, combCondition.acc_text_value,
                   combCondition.right_article_num, combCondition.right_foot_online, combCondition.right_foot_offline, 0, ProjectId, maxLevel?.levelid ?? 0);
                data.fixPath = fixList;
                data.data = resp;
                data.lampStatus = combCondition.lampStatus;
                data.layout = combCondition.layout;
                return new ObjectResult(data);
            }
            else
            {
                var maxLevel = _levelRepository.GetList(f => f.status == (int)RowState.Valid && f.projectid == ProjectId)
                    .OrderByDescending(q => q.id).FirstOrDefault();
                var alltreedata = _levelSectionRepository.getAllTreeData(ProjectId);
                var resp = _levelSectionRepository.GetSectionChildren(alltreedata, 0, ProjectId, maxLevel?.levelid ?? 0);
                return new ObjectResult(resp);
            }

        }

        private IList<LevelSectionTree> GetTreeNode(List<LevelSectionTree> source, int parentId, int lastLevel, bool addMachine = false)
        {
            var parents = source.FindAll(p => p.pid == parentId);
            foreach (var item in parents)
            {
                item.children = ConvertToChild(source, item.id, item.levelId, lastLevel, addMachine);
            }

            return parents;
        }

        private List<LevelSectionTree> ConvertToChild(List<LevelSectionTree> source, int parentId, int levelId, int lastLevel, bool addMachine = false)
        {
            var parents = source.FindAll(p => p.pid == parentId);
            foreach (var item in parents)
            {
                if (addMachine)
                {
                    item.children = ConvertToChild(source, item.id, item.levelId, lastLevel, true);
                }
                else
                {
                    if (levelId < item.levelId && item.levelId != lastLevel)
                    {
                        item.children = ConvertToChild(source, item.id, item.levelId, lastLevel);
                    }
                }

            }
            return parents;
        }

        private IList<LevelSectionTree> ConvertToTree(IEnumerable<LevelSectionTree> models)
        {
            var section = new Dictionary<int, LevelSectionTree>();
            foreach (var item in models)
            {
                if (section.ContainsKey(item.id))
                {
                    continue;
                }
                section.Add(item.id, item);
            }
            var result = new List<LevelSectionTree>();
            foreach (var item in section.Values)
            {
                if (item.pid == 0)
                {
                    result.Add(item);
                }
                else
                {
                    if (section.ContainsKey(item.pid))
                    {
                        section[item.pid].AddChilrden(item);
                    }
                }
            }
            return result;
        }

        [HttpPost]
        public IActionResult EditConditionChk([FromBody] RequestEditConditionChk request)
        {
            if (request.comb_page_id == 0)
            {
                throw new BadRequestException(RequestEnum.PageNotFound);
            }

            var page = _dashboardCombPageRepository.Get(q =>
                q.id == request.comb_page_id && q.status == (int)RowState.Valid);
            if (page == null)
            {
                throw new BadRequestException(RequestEnum.PageNotFound);
            }

            page.title = request.pageTitle;
            _dashboardCombPageRepository.Update(page);

            foreach (var condition in request.condition_dg_data)
            {
                var conditions = condition.Split(',');
                var entity = _combPageConditionRepository.Get(q => q.id == conditions[0].ToInt() && q.status == (int)RowState.Valid);
                if (entity != null)
                {
                    entity.condition = conditions[1];
                    if (conditions.Length == 6)
                    {
                        entity.acc_text_value = conditions[2];
                        entity.right_article_num = conditions[3].ToInt();
                        entity.right_foot_online = conditions[4].ToDouble();
                        entity.right_foot_offline = conditions[5].ToDouble();
                    }
                    _combPageConditionRepository.Update(entity);
                }
            }

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

        [HttpGet]
        public IActionResult EditConditionList(int comb_id, int comb_page_id, int nc = 0)
        {
            var areas = _dashboardCombPageRepository.GetEditConditionForEdit(comb_page_id, ProjectId);
            if (!areas.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var firstArea = areas.First();
            var result = new EditConditionListResult
            {
                page_title = firstArea.title,
            };
            var machines = _machineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid);

            var pageCode = new Dictionary<string, Dictionary<string, object>>();
            foreach (var area in areas)
            {
                var pagePatialCode = new Dictionary<string, object>();
                var typeId = new Dictionary<int, object>();
                if (area.type == 2)
                {
                    var conditions = area.condition.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                    var types = new List<string>();

                    foreach (var con in conditions)
                    {
                        types.Add(con);
                    }

                    foreach (var machineId in machines.Select(m => m.id))
                    {
                        if (!types.Contains(machineId.ToString()))
                        {
                            types.Add("0");
                        }
                    }
                    typeId[area.type] = types;
                }
                else if (area.type == 9 || area.type == 10) //acc 移动极值
                {
                    var conditions = area.condition.Split('-');
                    var response = new ResponseCondition();
                    response.Ids = conditions.ToList();
                    var keyValues = new List<ResponseKeyValue> {
                          new ResponseKeyValue("acc_text_value",area.acc_text_value),
                          new ResponseKeyValue("right_article_num",area.right_article_num.ToStr()),
                          new ResponseKeyValue("right_foot_online",area.right_foot_online.ToStr()),
                          new ResponseKeyValue("right_foot_offline",area.right_foot_offline.ToStr())
                        };

                    response.KeyValues = keyValues;
                    typeId[area.type] = response;

                }
                else if (area.type == 13)//277-278-279-280_早班|00:00:00 - 02:00:00;午班|02:00:00 - 04:00:00
                {
                    var conditions = area.condition.Split('_');
                    if (conditions.Length == 2)
                    {
                        var response = new ResponseCondition();
                        var ids = conditions[0].Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                        response.Ids = ids.ToList();

                        var shifts = conditions[1].Split(';');
                        var keyValues = new List<ResponseKeyValue>();
                        foreach (var shift in shifts)
                        {
                            var value = shift.Split('|');
                            if (value.Length == 2)
                            {
                                keyValues.Add(new ResponseKeyValue(value[0], value[1]));
                            }
                        }

                        response.KeyValues = keyValues;
                        typeId[area.type] = response;
                    }
                }
                else
                {
                    typeId[area.type] = new List<string> { area.condition };
                }

                pagePatialCode[area.condition_id.ToString()] = typeId;
                pageCode[area.page_patial_code] = pagePatialCode;
            }
            result.data[firstArea.page_code] = pageCode;

            foreach (var machine in machines)
            {
                result.project.Add(new StrIdTitle
                {
                    id = machine.id.ToString(),
                    title = machine.title
                });
            }
            return result;
        }
        /// <summary>
        /// [EditConditionList]vue框架方法
        /// </summary>
        /// <param name="comb_id"></param>
        /// <param name="comb_page_id"></param>
        /// <param name="nc"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEditConditionList(int comb_id, int comb_page_id, int nc = 0)
        {
            var areas = _dashboardCombPageRepository.GetEditConditionForEdit(comb_page_id, ProjectId);
            if (!areas.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var firstArea = areas.First();
            var result = new GetEditConditionListResult
            {
                page_title = firstArea.title,
            };
            var machines = _machineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid);

            var pageCode = new Dictionary<string, Dictionary<string, object>>();
            foreach (var area in areas)
            {
                var conditionList = new ConditionList();
                if (area.type == 2)
                {
                    var conditions = area.condition.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                    var types = new List<string>();

                    foreach (var con in conditions)
                    {
                        types.Add(con);
                    }

                    foreach (var machineId in machines.Select(m => m.id))
                    {
                        if (!types.Contains(machineId.ToString()))
                        {
                            types.Add("0");
                        }
                    }
                    conditionList.typeId = area.type;
                    conditionList.condition = types.Select(t => t.ToInt()).ToList();
                }
                else if (area.type == 9 || area.type == 10) //acc 移动极值
                {
                    var conditions = area.condition.Split('-');
                    var keyValues = new List<ResponseKeyValue> {
                          new ResponseKeyValue("acc_text_value",area.acc_text_value),
                          new ResponseKeyValue("right_article_num",area.right_article_num.ToStr()),
                          new ResponseKeyValue("right_foot_online",area.right_foot_online.ToStr()),
                          new ResponseKeyValue("right_foot_offline",area.right_foot_offline.ToStr())
                        };

                    conditionList.typeId = area.type;
                    conditionList.condition = conditions.Select(t => t.ToInt()).ToList();
                    conditionList.keyValues = keyValues;
                }
                else if (area.type == 13)//277-278-279-280_早班|00:00:00 - 02:00:00;午班|02:00:00 - 04:00:00
                {
                    var conditions = area.condition.Split('_');
                    if (conditions.Length == 2)
                    {
                        var ids = conditions[0].Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

                        var shifts = conditions[1].Split(';');
                        var keyValues = new List<ResponseKeyValue>();
                        foreach (var shift in shifts)
                        {
                            var value = shift.Split('|');
                            if (value.Length == 2)
                            {
                                keyValues.Add(new ResponseKeyValue(value[0], value[1]));
                            }
                        }

                        conditionList.typeId = area.type;
                        conditionList.condition = ids.Select(t => t.ToInt()).ToList();
                        conditionList.keyValues = keyValues;
                    }
                }
                else
                {
                    conditionList.typeId = area.type;
                    conditionList.conditionStr = area.condition;
                }

                conditionList.condition_id = area.condition_id;
                conditionList.page_patial_code = area.page_patial_code;

                result.data.Add(conditionList);
            }
            result.page_code = firstArea.page_code;

            foreach (var machine in machines)
            {
                result.project.Add(new StrIdTitle
                {
                    id = machine.id.ToString(),
                    title = machine.title
                });
            }
            return result;
        }

        [HttpGet]
        public IActionResult PagePatialCondtion(string page_code)
        {
            var result = new PagePatialCondtionResult();
            var machines =
                _machineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.category == (int)MachineCategory.NC);
            foreach (var machine in machines)
            {
                result.project.Add(new Result.IdTitle { id = machine.id, title = machine.title });
            }

            var pages = _dashboardCombPageRepository.GetCombInfo(page_code);
            var pageCode = new Dictionary<string, object>();
            foreach (var pageInfo in pages)
            {
                var pagePatialCode = new Dictionary<string, object>();
                if (!string.IsNullOrWhiteSpace(pageInfo.page_code) &&
                    !string.IsNullOrWhiteSpace(pageInfo.page_patial_code) &&
                    !string.IsNullOrWhiteSpace(pageInfo.page_patial_condition_code))
                {
                    var type = new PagePatialConditionCode
                    {
                        des = pageInfo.des,
                        type = pageInfo.type
                    };

                    pagePatialCode[pageInfo.page_patial_condition_code] = type;

                    pageCode[pageInfo.page_patial_code] = pagePatialCode;
                }
            }

            result.data_page_patial_condition[page_code] = pageCode;
            return result;
        }
        /// <summary>
        /// [PagePatialCondtion]vue方法
        /// </summary>
        /// <param name="page_code"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPagePatialCondtion(string page_code)
        {
            var result = new GetPagePatialCondtionResult();
            var machines =
                _machineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.category == (int)MachineCategory.NC);
            foreach (var machine in machines)
            {
                result.project.Add(new Result.IdTitle { id = machine.id, title = machine.title });
            }

            var pages = _dashboardCombPageRepository.GetCombInfo(page_code).OrderBy(q => q.page_patial_code);
            foreach (var pageInfo in pages)
            {
                if (!string.IsNullOrWhiteSpace(pageInfo.page_code) &&
                    !string.IsNullOrWhiteSpace(pageInfo.page_patial_code) &&
                    !string.IsNullOrWhiteSpace(pageInfo.page_patial_condition_code))
                {
                    var type = new PagePatialConditionCode
                    {
                        des = pageInfo.des ?? "",
                        type = pageInfo.type,
                        page_code = pageInfo.page_code,
                        page_patial_code = pageInfo.page_patial_code,
                        page_patial_condition_code = pageInfo.page_patial_condition_code
                    };

                    result.data_page_patial_condition.Add(type);
                }
            }

            return result;
        }

        [HttpPost]
        public IActionResult AddPage([FromBody] RequestAddPage request)
        {
            if (!string.IsNullOrWhiteSpace(request.page_id))
            {
                _dashboardCombPageRepository.UpdateCombPage(request.comb_id.ToInt(), request.page_code, request.pageTitle,request.page_id.ToInt());
                if (request.dashboard_comb_page_condition.Any())
                {
                    foreach (var condition in request.dashboard_comb_page_condition)
                    {
                        var conditions = condition.Split(',');
                        var combCondition = _combPageConditionRepository.Get(f => f.comb_page_id == request.page_id && f.page_patial_code == conditions[0]);
                        if (combCondition != null && request.fixPath != null && request.fixPath.Count > 0)
                        {
                            var fix = _dashboardFixpathRepository.GetList(q => q.guid == combCondition.guid && q.projectid == ProjectId && q.status == (int)RowState.Valid).ToList();
                            foreach (var item in fix)
                            {
                                _dashboardFixpathRepository.Delete(item);
                            }
                            
                            foreach (var item in request.fixPath)
                            {
                                var query = new siger_project_dashboard_fixpath
                                {
                                    guid = combCondition.guid,
                                    x = item.x,
                                    y = item.y,
                                    stationid = item.section_id,
                                    title = item.title,
                                    projectid = ProjectId,
                                };
                                _dashboardFixpathRepository.Insert(query);
                            }
                        }
                        combCondition.condition = conditions[2];
                        if (conditions.Length == 7)
                        {
                            combCondition.acc_text_value = conditions[3] ?? "0";
                            combCondition.right_article_num = conditions[4].ToInt();
                            combCondition.right_foot_online = conditions[5].ToDouble();
                            combCondition.right_foot_offline = conditions[6].ToDouble();

                        }
                        combCondition.layout = (request.layout != null && request.layout != "") ? request.layout : "";
                        combCondition.lampStatus = request.lampStatus > 0 ? request.lampStatus : 0;
                        combCondition.acc_text_value = combCondition.acc_text_value ?? "0";
                        _combPageConditionRepository.Update(combCondition);
                    }
                    _unitOfWork.Commit();
                }
            }
            else
            {
                var combPageId =
                    _dashboardCombPageRepository.AddCombPage(request.comb_id.ToInt(), request.page_code, request.pageTitle);

                if (request.dashboard_comb_page_condition.Any())
                {
                    foreach (var condition in request.dashboard_comb_page_condition)
                    {
                        var conditions = condition.Split(',');
                        var guid = Guid.NewGuid().ToString();
                        var entity = new siger_project_dashboard_comb_page_condition
                        {
                            comb_page_id = combPageId.ToString(),
                            page_patial_code = conditions[0],
                            page_patial_condition_code = conditions[1],
                            condition = conditions[2],
                            lampStatus = request.lampStatus,
                            layout = request.layout != null ? request.layout : "",
                            guid = guid
                        };

                        if (conditions.Length == 7)
                        {
                            entity.acc_text_value = conditions[3] ?? "0";
                            entity.right_article_num = conditions[4].ToInt();
                            entity.right_foot_online = conditions[5].ToDouble();
                            entity.right_foot_offline = conditions[6].ToDouble();
                        }
                        entity.acc_text_value = entity.acc_text_value ?? "0";
                        _combPageConditionRepository.Insert(entity);

                        if (request.layout != "" && request.layout != null && request.fixPath != null && request.fixPath.Count > 0)
                        {
                            foreach (var item in request.fixPath)
                            {
                                var query = new siger_project_dashboard_fixpath
                                {
                                    guid = guid,
                                    x = item.x,
                                    y = item.y,
                                    stationid = item.section_id,
                                    title = item.title,
                                    projectid = ProjectId,
                                };
                                _dashboardFixpathRepository.Insert(query);
                            }
                        }
                    }
                    _unitOfWork.Commit();
                }
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        [HttpGet]
        public IActionResult DProductionConfig(int page_id = 0)
        {
            var result = new ProductionConfigResult();

            var stations = _machineRepository.GetNCMachinStationInfos(ProjectId);
            var configs = _productionConfigRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.page_id == page_id).ToList();
            if (configs.Any())
            {
                var stationIds = stations.Select(m => m.station_Id).Distinct();
                foreach (var stationId in stationIds)
                {
                    var machines = new Dictionary<string, object>();
                    var machineInfos = new List<ProductionConfigInfo>();
                    var ms = stations.Where(m => m.station_Id == stationId);
                    foreach (var m in ms)
                    {
                        var machineInConfig = configs.FirstOrDefault(q => q.machine_id == m.machineId);
                        if (machineInConfig == null)
                        {
                            var machineInfo = new ProductionConfigInfo
                            {
                                machine_id = m.machineId.ToString(),
                                machine_section_id = m.sectionId.ToString(),
                                machine_section_title = m.section_name,
                            };
                            machineInfos.Add(machineInfo);
                            machines[m.station_name] = machineInfos;
                        }
                        else
                        {
                            var machineInfo = new ProductionConfigInfo
                            {
                                machine_id = machineInConfig.machine_id.ToString(),
                                machine_section_id = machineInConfig.machine_section_id.ToString(),
                                machine_section_title = machineInConfig.machine_section_title,
                                x = machineInConfig.x.ToString(),
                                y = machineInConfig.y.ToString(),
                                w = machineInConfig.w.ToString(),
                                h = machineInConfig.h.ToString(),
                                v = machineInConfig.v.ToString()
                            };
                            machineInfos.Add(machineInfo);
                            machines[m.station_name] = machineInfos;
                        }
                    }

                    result.data[stationId] = machines;
                }
            }
            else
            {
                var stationIds = stations.Select(m => m.station_Id).Distinct();
                foreach (var stationId in stationIds)
                {
                    var machines = new Dictionary<string, object>();
                    var machineInfos = new List<ProductionConfigInfo>();
                    var ms = stations.Where(m => m.station_Id == stationId);
                    foreach (var m in ms)
                    {
                        var machineInfo = new ProductionConfigInfo
                        {
                            machine_id = m.machineId.ToString(),
                            machine_section_id = m.sectionId.ToString(),
                            machine_section_title = m.section_name
                        };
                        machineInfos.Add(machineInfo);
                        machines[m.station_name] = machineInfos;
                    }
                    result.data[stationId] = machines;
                }
            }
            return result;
        }

        [HttpPost]
        public IActionResult DProductionConfig_add([FromBody] RequestDProductionConfig request)
        {
            if (request.datas == null)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            try
            {
                var stations = _machineRepository.GetNCMachinStationInfos(ProjectId);
                foreach (var config in request.datas)
                {
                    var machineId = config.mid.ToInt();
                    if (machineId == 0)
                    {
                        throw new BadRequestException(RequestEnum.MachineNotFound);
                    }

                    var dbConfig = _productionConfigRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid
                                                 && q.machine_id == machineId).FirstOrDefault();
                    if (dbConfig == null)
                    {
                        var stationInfo = stations.FirstOrDefault(q => q.machineId == machineId);
                        if (stationInfo == null)
                        {
                            continue;
                        }
                        var productConfig = new siger_project_production_configuration
                        {
                            machine_id = machineId,
                            machine_section_id = stationInfo.sectionId,
                            machine_section_title = stationInfo.section_name,
                            production_section_id = stationInfo.station_Id,
                            production_section_title = stationInfo.station_name,
                            add_time = UnixTimeHelper.GetNow(),
                            h = config.h_val.ToInt(),
                            w = config.w_val.ToInt(),
                            x = config.x_val.ToInt(),
                            y = config.y_val.ToInt(),
                            v = config.v_val.ToInt(),
                            projectid = ProjectId,
                            page_id = request.page_id
                        };
                        _productionConfigRepository.Insert(productConfig);
                        _unitOfWork.Commit();
                    }
                    else // 修改
                    {
                        dbConfig.h = config.h_val.ToInt();
                        dbConfig.w = config.w_val.ToInt();
                        dbConfig.x = config.x_val.ToInt();
                        dbConfig.y = config.y_val.ToInt();
                        dbConfig.v = config.v_val.ToInt();
                        dbConfig.page_id = request.page_id;
                        _productionConfigRepository.Update(dbConfig);
                        _unitOfWork.Commit();
                    }
                }
                return new ObjectResult(CommonEnum.Succefull);
            }
            catch
            {
                return new ObjectResult(CommonEnum.Fail);
            }

        }

        [HttpGet]
        public IActionResult GetProductionLine(string page_id, string patial_code)
        {
            var machineIds = _machineRepository
                .GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.category == (int)MachineCategory.NC).Select(m => m.id).ToList();

            var lines = _machineRepository.GetNCMachinSectionInfos(machineIds, ProjectId);

            var response = new List<RotationResponseIdTitle>();

            var combCondition = _combPageConditionRepository.Get(f => f.comb_page_id == page_id && f.page_patial_code == patial_code);
            Dictionary<string, string> myDic = new Dictionary<string, string>();
            if (!string.IsNullOrWhiteSpace(page_id) && !string.IsNullOrWhiteSpace(patial_code))
            {
                if (combCondition != null && combCondition.condition.Contains('-'))
                {
                    var cfgMachines = combCondition.condition.Split('-').ToList();
                    foreach (var itemTwo in cfgMachines)
                    {
                        if (!myDic.Keys.Contains(itemTwo))
                        {
                            myDic.Add(itemTwo, combCondition.page_patial_code);
                        }
                    }
                }
                else
                {
                    if (!myDic.Keys.Contains(combCondition.condition))
                    {
                        myDic.Add(combCondition.condition, combCondition.page_patial_code);
                    }
                }

            }

            foreach (var line in lines)
            {
                if (response.Any(m => m.id == line.id))
                {
                    continue;
                }

                //判断字典是否存在键
                if (!string.IsNullOrWhiteSpace(page_id) && myDic.Values.Contains(patial_code))
                {
                    List<string> keyList = (from q in myDic
                                            where q.Value == patial_code
                                            select q.Key).ToList<string>(); //get all keys
                    if (keyList.Count() > 0)
                    {
                        foreach (var itemValue in keyList)
                        {
                            if (itemValue.Split(',')[0].ToString() == (line.id.ToStr()))
                            {
                                line.@checked = true;
                            }
                        }
                    }
                    else if (keyList.Count() == 1)
                    {
                        if (keyList[0].Split(',')[0].ToString() == (line.id.ToStr()))
                        {
                            line.@checked = true;
                        }
                    }
                    else
                    {
                        line.@checked = false;
                    }

                }


                response.Add(new RotationResponseIdTitle
                {
                    id = line.id,
                    title = line.section_name,
                    @checked = line.@checked
                });
            }

            return new ObjectResult(response);
        }
        [HttpPost]
        public IActionResult SelectEquipment([FromBody] RequestSelectEquipment request)
        {
            var response = new SelectEquipmentResult();

            var machineIds = _machineRepository.GetNCMachinIdsBySectionId(request.sid.ToInt(), 0, ProjectId);

            var machines = _machineRepository.GetList(q =>
                machineIds.Contains(q.id) && q.projectid == ProjectId && q.status == (int)RowState.Valid && q.category == (int)MachineCategory.NC);

            response.page_patial_code = request.page_patial_code;
            response.page_patial_condition_code = request.page_patial_condition_code;
            foreach (var machine in machines)
            {
                response.data.Add(new ResponseIdTitle
                {
                    id = machine.id,
                    title = machine.title
                });
            }
            return response;
        }

        [HttpGet]
        public IActionResult GetProductionWorkShop()
        {
            var response = new List<ResponseIdTitle>();
            //var levelsection = _machineRepository.GetSecondLevelSection(ProjectId).Distinct();
            var levelsection = _machineRepository.GetNCLevelSections(0, ProjectId);
            var levels = _levelRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).OrderBy(t => t.id).ToList();
            if (levels.Count < 2)
            {
                return new ObjectResult(response);
            }
            levelsection = levelsection.Where(t => t.levelid == levels[1].levelid).ToList();
            foreach (var section in levelsection)
            {
                if (response.All(m => m.id != section.id))
                {
                    response.Add(new ResponseIdTitle
                    {
                        id = section.id,
                        title = section.title
                    });
                }
            }

            return new ObjectResult(response);
        }
        [HttpGet]
        public IActionResult GetMachineTypes()
        {
            var ret = new List<ResponseSectionsByMachineType>();
            var pid = ProjectId;
            var rowstate = (int)RowState.Valid;
            var types = _machineTypeRepository.GetList(f => f.projectid == pid && f.status == rowstate && f.parentid == 0).ToList();
            foreach (var typedata in types)
            {
                var sons = _machineTypeRepository.GetSonMachineTypes(typedata.id, pid).Select(s => s.id).ToList();
                var count = _machineRepository.GetList(f => f.status == rowstate && f.projectid == pid && sons.Contains(f.typeid)).Count();
                ret.Add(new ResponseSectionsByMachineType { title = typedata.title, typeid = typedata.id, count = count });
            }
            return new ObjectResult(ret);
        }

        /// <summary>
        /// APP-SKF 设备状态一览
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetMachineStateView([FromBody] RequestMachineLineState req)
        {
            var res = new ResponseMachineState();
            var MachineList = new List<MachineLine>();
            var machines = _machineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid).ToList();
            if (req.typeid != 0)
            {
                var sons = _machineTypeRepository.GetSonMachineTypes(req.typeid, ProjectId).Select(s => s.id).ToList();
                machines = machines.Where(f => sons.Contains(f.typeid)).ToList();
            }
            if (!machines.Any())
            {
                return new ObjectResult(res);
            }

            var levels = _levelRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).OrderBy(t => t.id).ToList();
            if (levels.Count < 2)
            {
                return new ObjectResult(res);
            }

            foreach (var machine in machines)
            {
                var location = _machineRepository.GetLevelSectionTitles(machine.id, machine.projectid, levels, out var sectionId);
                MachineList.Add(new MachineLine
                {
                    Name = machine.title,
                    MachineId = machine.id,
                    IsEnabled = (int)RowState.Valid,
                    Location = location,
                    SectionId = sectionId
                });
            }

            var rep = new CNCEquipmentStateRepository(CompanyId, ProjectId);
            var cncStates = rep.GetCNCEquipmentStates();
            var machineStates = new List<MachineIdLineState>();
            foreach (var cncState in cncStates)
            {
                machineStates.Add(new MachineIdLineState
                {
                    MachineId = cncState.MachineId,
                    State = cncState.Status
                });
            }

            var sectionIds = MachineList.Select(t => t.SectionId).Distinct().ToList();
            var lastSections = _levelSectionRepository.GetList(t =>
                    sectionIds.Contains(t.parentid) && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            var selectMachines = _machineRepository.GetMachineIdsBySectionIds(lastSections.Select(t => t.id).ToList(), ProjectId).ToList();
            if (req.sections != null && req.sections.Any())
            {
                sectionIds = sectionIds.Where(t => req.sections.Contains(t)).ToList();
                MachineList = MachineList.Where(t => req.sections.Contains(t.SectionId)).ToList();
                machineStates = machineStates.Where(t => selectMachines.Contains(t.MachineId)).ToList();
            }
            machineStates = machineStates.Where(t => MachineList.Select(q => q.MachineId).Contains(t.MachineId)).ToList();

            var mIds = MachineList.Select(t => t.MachineId).ToList();
            var repairs = _repairRepository.GetList(t => mIds.Contains(t.machineid) && t.projectid == ProjectId && t.status > 0 &&
                    t.status < (int)MachineRepairStatus.WaitingForFeedback).ToList();
            var endTime = UnixTimeHelper.GetTodayUnix() + 86399;

            var planSigns = _planSignRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                    mIds.Contains(t.machine_id) && t.create_time >= UnixTimeHelper.GetTodayUnix()).ToList();
            var signMachineIds = planSigns.Select(t => t.machine_id).ToList();
            var planModels = _planTimeRepository.GetPlanInformationByMachineIds(0, mIds, 0, endTime, ProjectId).ToList();

            var sensorStates = _sensorParameter.GetList(f => mIds.Contains(f.mid) &&
                    f.status > 0 && f.status != (int)SensorStatus.NoSet).ToList();

            var machineTypes = _machineTypeRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            foreach (var sectionId in sectionIds)
            {
                var machineStatus = new List<MachineLineState>();
                var machineList = MachineList.Where(t => t.SectionId == sectionId).ToList();
                var machineIds = machineList.Select(t => t.MachineId).ToList();
                if (!machineIds.Any() || !machineList.Any())
                {
                    continue;
                }

                var machineExtends = _machineExtendRepository.GetList(t => machineIds.Contains(t.machine_id)).ToList();
                foreach (var machineId in machineIds)
                {
                    var machine = machines.FirstOrDefault(t => t.id == machineId);
                    if (machine == null)
                    {
                        continue;
                    }
                    var state = machineStates.FirstOrDefault(t => t.MachineId == machineId);
                    var runState = state?.State ?? (int)SkfMachineRunningStatus.Shutdown;
                    var sensorState = (int)SensorStatus.Normal;
                    var sensorStatess = sensorStates.Where(f => f.mid == machineId);
                    if (sensorStatess.Count(t => t.status == (int)SensorStatus.OverDue) > 0)
                    {
                        sensorState = (int)SensorStatus.OverDue;
                    }
                    else if (sensorStatess.Count(t => t.status == (int)SensorStatus.WaitMark) > 0)
                    {
                        sensorState = (int)SensorStatus.WaitMark;
                    }
                    //设备保养状态填写
                    var MaintenanceState = (int)PlanStatus.Normal;
                    var planModel = planModels.Where(t => t.machineid == machineId).ToList();
                    if (planModel.Any())
                    {
                        if (planModel.Count(t => t.information == (int)PlanStatus.Overdue) > 0)
                        {
                            MaintenanceState = (int)PlanStatus.Overdue;
                        }
                        else if (planModel.Count(t => t.information == (int)PlanStatus.UnExecuted) > 0)
                        {
                            MaintenanceState = (int)PlanStatus.UnExecuted;
                        }
                        else
                        {
                            MaintenanceState = (int)PlanStatus.Normal;
                        }
                    }

                    if (signMachineIds.Contains(machineId) || sensorStatess.Count(t => t.status == (int)SensorStatus.Marking) > 0)
                    {
                        runState = (int)SkfMachineRunningStatus.MaintainSensor;
                    }

                    var repair = repairs.Where(t => t.machineid == machineId).ToList();
                    if (repair.Any())
                    {
                        runState = (int)SkfMachineRunningStatus.Repairing;
                    }
                    var machinetype = machineTypes.FirstOrDefault(t => t.id == machine.typeid);
                    var parentmachinetype = "";
                    if (machinetype != null)
                    {
                        parentmachinetype = machineTypes.FirstOrDefault(t => t.id == machinetype.parentid)?.title ?? "";
                    }
                    runState = (runState != (int)SkfMachineRunningStatus.Running && runState != (int)SkfMachineRunningStatus.Repairing &&
                        runState != (int)SkfMachineRunningStatus.MaintainSensor) ? (int)SkfMachineRunningStatus.Shutdown : runState;
                    var machineExtend = machineExtends.FirstOrDefault(t => t.machine_id == machine.id);
                    var machineicontype = (machinetype?.title ?? "").ToUpper();
                    machineStatus.Add(new MachineLineState
                    {
                        machineid = machine.id,
                        name = machine.title,
                        shortname = machineExtend?.machine_shortname ?? "",
                        status = runState,
                        sensorstate = sensorState,
                        maintenancestate = MaintenanceState,
                        machinetype = machineicontype == "A-THU" ? "THU" : (machineicontype == "A-SEAL" ? "SEAL" : machineicontype),
                        parent_machinetype = parentmachinetype
                    });
                }

                res.machinelocations.Add(new MachineLineLocation
                {
                    location = machineList.First().Location,
                    machinestates = machineStatus
                });
            }

            var statuss = EnumHelper.EnumToList<MachineRunningStatus>();
            foreach (var status in statuss)
            {
                var count = machineStates.Count(t => t.State == status.EnumValue);
                switch (status.EnumValue)
                {
                    case (int)MachineRunningStatus.Running:
                        res.run = count;
                        break;
                    case (int)MachineRunningStatus.Debugging:
                        res.debug = count;
                        break;
                    case (int)MachineRunningStatus.Fault:
                        res.fault = count;
                        break;
                    case (int)MachineRunningStatus.Free:
                        res.free = count;
                        break;
                    case (int)MachineRunningStatus.Shutdown:
                        res.shutdown = count;
                        break;
                }
            }

            return new ObjectResult(res);
        }

        /// <summary>
        /// APP-skf 获取设备状态详情
        /// </summary>
        /// <param name="machineid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMachineStateDetail(string machineid)
        {
            var machineId = machineid.ToInt();

            var machine = _machineRepository.Get(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.id == machineId);
            if (machine == null)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            var rep = new CNCEquipmentStateRepository(CompanyId, ProjectId);
            var cncStates = rep.GetCNCEquipmentState(machineId);
            var runState = cncStates?.Status ?? (int)SkfMachineRunningStatus.Shutdown;
            var MaintenanceState = (int)PlanStatus.Normal;
            var planSign = _planSignRepository.Get(t =>
                t.projectid == ProjectId && t.status == (int)RowState.Valid && t.machine_id == machineId);
            var planModel = _planTimeRepository.GetPlanInformationByMachineIds(0, new List<int> { machineId }, 0,
                UnixTimeHelper.GetNow() + 86399, ProjectId).ToList();
            if (planModel.Any() && planSign != null)
            {
                if (planModel.Count(t => t.information == (int)PlanStatus.Overdue) > 0)
                {
                    MaintenanceState = (int)PlanStatus.Overdue;
                }
                else if (planModel.Count(t => t.information == (int)PlanStatus.UnExecuted) > 0)
                {
                    MaintenanceState = (int)PlanStatus.UnExecuted;
                }
                else
                {
                    MaintenanceState = (int)PlanStatus.Normal;
                }
            }

            var sensorState = _sensorParameter.Get(f => f.status == (int)RowState.Valid && f.mid == machineId &&
                        f.status > 0 && f.status != (int)SensorStatus.NoSet && f.status != (int)SensorStatus.OverDue);

            if (MaintenanceState > (int)PlanStatus.Normal || sensorState != null)
            {
                runState = (int)SkfMachineRunningStatus.MaintainSensor;
            }

            var repairs = _repairRepository.GetList(q => q.status > 0 && q.status < (int)MachineRepairStatus.WaitingForFeedback && q.projectid == ProjectId
                                                         && q.machineid == machineId).OrderBy(q => q.status).ToList();
            var repairState = repairs.Any() ? repairs.First().status : (int)MachineRepairStatus.Completed;
            runState = repairs.Any() ? (int)SkfMachineRunningStatus.Repairing : runState;

            var levels = _levelRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).OrderBy(t => t.id).ToList();
            var location = _machineRepository.GetLevelSectionTitles(machineId, ProjectId, levels, out var _);

            var machineExtend = _machineRepository.GetExtendMachines(machineId, ProjectId);
            var res = new ResponseMachineStateDetail
            {
                location = location,
                machineid = machineId,
                machinename = machine.title,
                maintainstate = MaintenanceState,
                repairstate = repairState,
                sensorstate = sensorState?.status ?? (int)SensorStatus.Normal,
                status = runState,
                typetitle = machineExtend.typetitle,
                description = machineExtend.description,
                brand = machineExtend.brand,
                code = machineExtend.code,
                current_status = machineExtend.current_status,
                factory = machineExtend.factory,
                factory_code = machineExtend.factory_code,
                image = machineExtend.image,
                ip = machineExtend.ip,
                model = machineExtend.model,
                savedaycomment = machineExtend.savedaycomment,
                savedays = machineExtend.savedays,
                sorting = machineExtend.sorting,
                time = machineExtend.time,
                typeid = machineExtend.typeid,
                made_date = machineExtend.made_date,

                machine_name = machineExtend.machine_name ?? "",
                typical_application = machineExtend.typical_application ?? "",
                inside_diameter = machineExtend.inside_diameter,
                outside_diameter = machineExtend.outside_diameter ?? "",
                radial_load = machineExtend.radial_load ?? "",
                axial_load = machineExtend.axial_load ?? "",
                pressure = machineExtend.pressure ?? "",
                speed = machineExtend.speed ?? "",
                temperature = machineExtend.temperature ?? "",
                rotation = machineExtend.rotation ?? "",
                sample_lubrication = machineExtend.sample_lubrication ?? "",
                oil_hydraulic = machineExtend.oil_hydraulic ?? "",
                oil_lubrication = machineExtend.oil_lubrication ?? "",
                signal_monitor = machineExtend.signal_monitor ?? "",
                position = machineExtend.position ?? "",
                machine_size = machineExtend.machine_size ?? "",
                machine_shortname = machineExtend.machine_shortname ?? "",
                responsor = machineExtend.responsor ?? "",
                current = GetMachineStatus(machineExtend.current_status)
            };
            var machineFiles = _esopDocumentHistoryRepository.GetDocumentHistoryFileList(machineId, ProjectId);
            var machineDocs = new List<MachineFile>();
            foreach (var doc in machineFiles)
            {
                machineDocs.Add(new MachineFile
                {
                    id = doc.document_id,
                    filename = doc.file_name,
                    fileurl = doc.file_url,
                    uploadtime = doc.createtime
                });
            }
            res.machinefiles = machineDocs;

            return new ObjectResult(res);
        }

        private string GetMachineStatus(int current_status)
        {
            try
            {
                var status = (MachineStatus)current_status;

                return status.ToDescription();
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}