using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;
using Siger.Middlelayer.Repository.Response;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class SigerProjectLevelSectionRepository : ApiConfigRepositoryBase<siger_project_level_section>, ISigerProjectLevelSectionRepository
    {
        private readonly ApiConfigDbContext _context;
        public SigerProjectLevelSectionRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }

        public IEnumerable<LevelSectionTree> GetLevelSectionTree(int projectid, int canselected = 0)
        {
            var list = new List<LevelSectionTree>();
            var query = GetSonLevelSections(0, projectid);

            foreach (var section in query.ToList())
            {
                list.Add(new LevelSectionTree
                {
                    id = section.id,
                    name = section.title,
                    title = section.title,
                    pid = section.parentid,
                    levelId = section.levelid,
                    open = true,
                    disabled = canselected == 0
                });
            }

            return list;
        }

        public bool AddLevelSections(List<AddProjectLevelSection> sections, int projectId)
        {
            try
            {
                foreach (var level in sections)
                {
                    if (level.isNewParent == "0")
                    {
                        var pid = AddLevelSectionEntity(level.levelid, level.name, projectId, level.pid);

                        AddSection(pid, level.id, sections, projectId);
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void AddSection(int parentId, int levelId, List<AddProjectLevelSection> sections, int projectId)
        {
            var entities = sections.Where(q => q.pid == levelId).ToList();
            if (entities.Any())
            {
                foreach (var addSection in entities)
                {
                    var pid = AddLevelSectionEntity(addSection.levelid, addSection.name, projectId, parentId);

                    AddSection(pid, addSection.id, sections, projectId);
                }
            }
        }

        private int AddLevelSectionEntity(int levelid, string name, int projectId, int parentid)
        {
            var levelsection = new siger_project_level_section
            {
                levelid = levelid,
                title = name,
                projectid = projectId,
                parentid = parentid,
            };
            _context.siger_project_level_section.Add(levelsection);
            _context.SaveChanges();
            return levelsection.id;
        }

        public IEnumerable<ResponseIdName> GetSectionIdNamesByLevel(int levelId, int parentId, int projectId)
        {
            var query = _context.siger_project_level_section.Where(t => t.levelid == levelId && t.status == (int)RowState.Valid
                && t.projectid == projectId).ToList();
            if (parentId > 0)
            {
                query = query.Where(t => t.parentid == parentId).ToList();
            }
            var queryList = from q in query
                            select new ResponseIdName
                            {
                                id = q.id,
                                name = q.title
                            };
            return queryList;
        }

        public IEnumerable<ResponseIdName> GetAllLines(int projectId)
        {
            var querylist = from q in _context.siger_project_machine_attribution
                            join se in _context.siger_project_level_section on q.station equals se.id
                            join se2 in _context.siger_project_level_section on se.parentid equals se2.id
                            where q.status == (int)RowState.Valid && se.status == (int)RowState.Valid
                                  && se.projectid == projectId
                            select new ResponseIdName
                            {
                                id = se2.id,
                                name = se2.title
                            };

            return querylist.Distinct().ToList();
        }
        /// <summary>
        /// MTS 产线信息 （产线层级倒数第二级别）
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public IEnumerable<siger_project_level_section> GetAccLines(int projectId)
        {
            var linelevel = _context.siger_project_level.Where(f => f.projectid == projectId && f.status == (int)RowState.Valid).OrderByDescending(o => o.id).ToList();
            if (!linelevel.Any() || linelevel.Count < 2)
                return new List<siger_project_level_section>();
            var lineSetion = _context.siger_project_level_section.Where(f => f.projectid == projectId && f.levelid == linelevel[1].id && f.status == (int)RowState.Valid);
            return lineSetion;
        }
        /// <summary>
        /// MTS 工站信息 （产线层级倒数第一级别）
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public IEnumerable<siger_project_level_section> GetAccStation(int projectId)
        {
            var linelevel = _context.siger_project_level.Where(f => f.projectid == projectId && f.status == (int)RowState.Valid).OrderByDescending(o => o.id).ToList();
            if (!linelevel.Any() || linelevel.Count < 2)
                return new List<siger_project_level_section>();
            var stationSetion = _context.siger_project_level_section.Where(f => f.projectid == projectId && f.levelid == linelevel[0].id && f.status == (int)RowState.Valid);
            return stationSetion;
        }
        /// <summary>
        /// MTS 工站信息 
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="line">产线section</param>
        /// <returns></returns>
        public IEnumerable<siger_project_level_section> GetAccStationByline(int projectId, int line)
        {
            
            var linelevel = _context.siger_project_level.Where(f => f.projectid == projectId && f.status == (int)RowState.Valid).OrderByDescending(o => o.id).ToList();
            if (!linelevel.Any() || linelevel.Count < 2)
                return new List<siger_project_level_section>();
            var stationSetion = _context.siger_project_level_section.Where(f => f.projectid == projectId && f.levelid == linelevel[0].id && f.parentid == line && f.status == (int)RowState.Valid);
            return stationSetion;
        }

        /// <summary>
        /// 获取工站
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="line">产线section</param>
        /// <returns></returns>
        public IEnumerable<siger_project_level_section> Getline(int projectId, int line)
        {
            var lines = GetLevelSections(line, projectId);
            return lines;
        }
        /// <summary>
        /// 根据工站获取产线ID
        /// </summary>
        /// <param name="station"></param>
        /// <param name="projectId"></param>
        /// <returns>0 ：无对于产线ID</returns>
        public int GetlineId(int station, int projectId)
        {
            var linelevel = _context.siger_project_level.Where(f => f.projectid == projectId && f.status == (int)RowState.Valid).OrderByDescending(o => o.id).ToList();
            if (!linelevel.Any() || linelevel.Count < 2)
                return 0;
            var stationSetion = _context.siger_project_level_section.Where(f => f.projectid == projectId && f.levelid == linelevel[0].id && f.id == station && f.status == (int)RowState.Valid).FirstOrDefault();
            if (stationSetion == null)
                return 0;
            return stationSetion.parentid;
        }
        /// <summary>
        /// 获取产线信息
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        public List<LevelSectionTree> GetSectionData(int pid, int parentid)
        {
            //获取所有产线信息
            var sectionData = _context.siger_project_level_section.Where(f => f.status == (int)RowState.Valid && f.projectid.Equals(pid)).ToList();
            return GetChildren(parentid, sectionData);
        }
        private List<LevelSectionTree> GetChildren(int parentid, List<siger_project_level_section> sectionDatas)
        {
            var resp = new List<LevelSectionTree>();
            var query = sectionDatas.Where(f => f.parentid.Equals(parentid));
            if (!query.Any())
            {
                return null;
            }
            foreach (var section in query)
            {
                var data = new LevelSectionTree();
                data = Mapper<siger_project_level_section, LevelSectionTree>.Map(section);
                data.children = GetChildren(section.id, sectionDatas);
                resp.Add(data);
            }
            return resp;
        }
        /// <summary>
        /// 获取产线结构详细字符串
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="sectionid"></param>
        /// <returns></returns>
        public string GetSectionString(int pid, int sectionid)
        {
            var sectionModel = _context.siger_project_level_section.FirstOrDefault(f => f.projectid.Equals(pid) && f.status == (int)RowState.Valid && f.id.Equals(sectionid));
            if (sectionModel == null)
            {
                return null;
            }
            return GetSectionString(pid, sectionModel.parentid) + "->" + sectionModel.title;
        }

        public string GetSectionStringByMid(int pid, int machineid)
        {
            var sectionModel = _context.siger_project_machine_attribution.FirstOrDefault(f => f.status == (int)RowState.Valid && f.machine.Equals(machineid));
            if (sectionModel == null)
            {
                return null;
            }
            var machinename = _context.siger_project_machine.Where(f => f.projectid.Equals(pid) && f.status == (int)RowState.Valid && f.id.Equals(machineid)).Select(s => s.title).FirstOrDefault() ?? "";
            return GetSectionString(pid, sectionModel.station) + "->" + machinename;
        }

        public int AddLevelSection(siger_project_level_section levelSection)
        {
            var level = new siger_project_level_section
            {
                parentid = levelSection.parentid,
                dutymid = 0,
                levelid = levelSection.levelid,
                projectid = levelSection.projectid,
                status = (int)RowState.Valid,
                title = levelSection.title
            };
            _context.siger_project_level_section.Add(level);
            if (_context.SaveChanges() > 0)
            {
                return level.id;
            }

            return 0;
        }
        /// <summary>
        /// 获取项目所有树数据
        /// </summary>
        /// <param name="pid">项目id</param>
        /// <returns></returns>
        public List<siger_project_level_section> getAllTreeData(int pid) 
        {            
            var response = _context.siger_project_level_section.Where(f => f.status == (int)RowState.Valid && f.projectid == pid).ToList();
            return response;
        }

        public  List<ResponseGetSectionTree> GetSectionChildren(List<siger_project_level_section> alltreedata, int parentid, int pid, int maxlevelId)
        {
            var response = new List<ResponseGetSectionTree>();
            //var model = _context.siger_project_level_section.Where(f => f.parentid==parentid && f.status == (int)RowState.Valid && f.projectid==pid);
            var model = alltreedata.Where(f => f.parentid == parentid);
            if (!model.Any())
            {
                return response;
            }
            foreach (var item in model)
            {               
                    response.Add(new ResponseGetSectionTree
                    {
                        @checked = false,
                        label = item.title,
                        value = item.id,
                        levelid = item.levelid == maxlevelId ? maxlevelId : 0,
                        children = GetSectionChildren(alltreedata, item.id, pid, maxlevelId)
                    });             
            }
            return response;
        }

        public List<ResponseGetSectionTree> GetSectionChildrenFromRotation(string condition,string acc_text_value, int right_article_num,
            double right_foot_online, double right_foot_offline, int parentid, int pid, int maxlevelId)
        {
            var response = new List<ResponseGetSectionTree>();
            var model = _context.siger_project_level_section.Where(f => f.parentid.Equals(parentid) && f.status == (int)RowState.Valid && f.projectid.Equals(pid));
            if (!model.Any())
            {
                return response;
            }
            foreach (var item in model)
            {
                if (condition == item.id.ToString())
                {
                    response.Add(new ResponseGetSectionTree
                    {
                        @checked = true,
                        label = item.title,
                        value = item.id,
                        levelid = item.levelid == maxlevelId ? maxlevelId : 0,
                        acc_text_value= acc_text_value,
                        right_article_num= right_article_num,
                        right_foot_online= right_foot_online,
                        right_foot_offline= right_foot_offline,
                        children = GetSectionChildrenFromRotation(condition, acc_text_value, right_article_num, right_foot_online,
                        right_foot_offline, item.id, pid, maxlevelId)
                    });
                }
                else
                {
                    response.Add(new ResponseGetSectionTree
                    {
                        @checked = false,
                        label = item.title,
                        value = item.id,
                        levelid = item.levelid == maxlevelId ? maxlevelId : 0,
                        children = GetSectionChildrenFromRotation(condition, acc_text_value, right_article_num, right_foot_online,
                        right_foot_offline, item.id, pid, maxlevelId)
                    }); ;
                }
            }
            return response;
        }

        public List<siger_project_level_section> GetSectionFamilyList(int id, int pid)
        {
            var response = new List<siger_project_level_section>();
            var model = _context.siger_project_level_section.Where(f => f.parentid.Equals(id) && f.status == (int)RowState.Valid && f.projectid.Equals(pid)).ToList();
            if (!model.Any())
            {
                return response;
            }
            foreach (var item in model)
            {
                response.Add(item);
                response.AddRange(GetSectionFamilyList(item.id, pid));
            }
            return response;
        }

        public int ConvetTitle(string strTile)
        {

                for (int i = 0; i < strTile.Length; i++)
                {
                    var charTitle = strTile[i].ToString();
                    if (int.TryParse(charTitle, out int reust))
                    {
                        return i;
                    }
                };
                return 0;
            
        }

    }
}
