using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Response;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Common.Extensions;
using System;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.AccRepository.Request;

namespace Siger.ApiACC.Controllers
{
    [NoTokenValidateFilter]
    public class PowerController : BaseController
    {
        private readonly ISigerUserPowerRepository _userPower;
        private readonly ISigerUserRolePowerRepository _userRolePower;
        private readonly ISigerTrPowerSectionRepository _powerSection;
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectLevelSectionRepository _section;
        public PowerController(ISigerUserPowerRepository userPower, ISigerUserRolePowerRepository userRolePower, ISigerTrPowerSectionRepository powerSection, IUnitOfWork unitOfWork
            , ISigerProjectLevelSectionRepository section)
        {
            _userPower = userPower;
            _userRolePower = userRolePower;
            _powerSection = powerSection;
            _unitOfWork = unitOfWork;
            _section = section;
        }

        /// <summary>
        /// 获取菜单信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenusByRoleId(int roleId, int type)
        {
            var powerId = _userRolePower.GetList(q => q.roleid.Equals(roleId) && q.status.Equals((int)RowState.Valid)).Select(s => s.powerid);
            if (!powerId.Any())
            {
                throw new BadRequestException(AccEnum.Data_Null);
            }
            var menus = _userPower.GetList(q => powerId.Contains(q.id) && q.status.Equals((int)RowState.Valid) && q.type.Equals((int)PowerType.Client));
            if (!menus.Any())
            {
                throw new BadRequestException(AccEnum.Data_Null);
            }
            return new ObjectResult(menus);
        }

        [HttpGet]
        public IActionResult GetSectionsByMenu(int menuId, int? projectId)
        {
            var pid = projectId == 0 || projectId == null ? ProjectId : projectId;
            var sectionId = _powerSection.GetList(f => f.projectId.Equals(pid) &&
                 f.status.Equals((int)RowState.Valid) && f.MenuId.Equals(menuId)).ToList();
            var response = new ResponsePowerSection
            {
                Id = 0,
                Title = "",
                PowerSections = new List<ResponsePowerSection>()
            };
            if (!sectionId.Any())
            {
                return new ObjectResult(response);
            }
            var lines = sectionId.Select(s =>
              new
              {
                  s.Line,
                  s.LineId
              }).Distinct();
            foreach (var item in lines)
            {
                var tempLine = new ResponsePowerSection
                {
                    Id = item.LineId,
                    Title = item.Line,
                    PowerSections = new List<ResponsePowerSection>()
                };
                foreach (var stationData in sectionId.Where(f => f.LineId.Equals(item.LineId)))
                {
                    tempLine.PowerSections.Add(new ResponsePowerSection
                    {
                        Id = stationData.StationId,
                        Title = stationData.Station
                    });
                }
                response.PowerSections.Add(tempLine);
            }
            return new ObjectResult(response);
        }
        /// <summary>
        /// 获取Acc菜单结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAccMenu()
        {
            var userpowerData = _userPower.GetList(f => f.status != (int)RowState.Invalid);
            var resp = new List<ResponseMenus>();
            var clientType = Enum.GetNames(typeof(PowerType));
            //菜单类型
            foreach (var item in clientType)
            {
                var clientData = new ResponseMenus
                {
                    description = item,
                    type = (int)Enum.Parse(typeof(PowerType), item),
                    disabled = true,
                    title = item,
                    id = userpowerData.Where(f => f.value.Contains("mts")).FirstOrDefault().id
                };
                resp.Add(clientData);
            }
            foreach (var item in resp)
            {
                item.children = GetPowerData(item.id, item.type);
            }
            return new ObjectResult(resp);
        }

        private List<ResponseMenus> GetPowerData(int parent, int type)
        {
            var menus = new List<ResponseMenus>();
            var powerData = _userPower.GetList(f => f.parent.ToInt() == parent && f.status != (int)RowState.Invalid && f.type == type);
            if (powerData == null)
            {
                return null;
            }
            foreach (var item in powerData)
            {
                var data = Mapper<siger_user_power, ResponseMenus>.Map(item);
                data.title = data.description;
                menus.Add(data);
                data.children = GetPowerData(item.id, item.type);
            }
            return menus;
        }
        /// <summary>
        ///  根据工位获取产线的菜单
        /// </summary>
        /// <param name="section"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenusBySectionId(int section)
        {
            var data = _powerSection.GetList(f => f.projectId.Equals(ProjectId) && f.status != (int)RowState.Invalid && f.StationId.Equals(section));
            return new ObjectResult(data);
        }
        /// <summary>
        /// 保存菜单与工位关系
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SavePowerSectionData([FromBody] RequestMenus request)
        {
            var entities = _powerSection.GetList(f => f.StationId == request.section && f.projectId == ProjectId && f.status != 0).ToList();
            foreach (var entity in entities)
            {
                
                _powerSection.Delete(entity);
            }
            if (string.IsNullOrEmpty(request.power))
            {
                if (_unitOfWork.Commit() > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
                throw new BadRequestException(CommonEnum.Fail);
            }

            var powers = request.power.Split(',', StringSplitOptions.RemoveEmptyEntries);
            var station = _section.Get(f => f.projectid==ProjectId && f.status != (int)RowState.Invalid && f.id == request.section);
            var line = _section.Get(f => f.projectid==ProjectId && f.status != (int)RowState.Invalid && f.id == station.parentid);
            foreach (var strPowers in powers)
            {
                var data = new SigerTrPowerSection
                {
                    StationId = request.section,
                    MenuId = strPowers.ToInt(),
                    LineId = line.id,
                    Line = line.title,
                    Station = station.title,
                    projectId = ProjectId
                };
                _powerSection.Insert(data);
                //如果power为父级 自动带入子集
                var sons = _userPower.GetList(f => f.parent == strPowers).Select(s => s.id).ToList();
                foreach (var item in sons)
                {
                    var model = new SigerTrPowerSection
                    {
                        StationId = request.section,
                        MenuId = item,
                        LineId = line.id,
                        Line = line.title,
                        Station = station.title,
                        projectId = ProjectId,
                    };
                    _powerSection.Insert(model);
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 删除菜单与工位关系
        /// </summary>
        /// <param name="power"></param>
        /// <param name="section"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DeletePowerSectionData(int power, int section)
        {
            var data = _powerSection.Get(f => f.StationId == section && f.MenuId == power);
            if (data == null)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            _powerSection.Delete(data);
            //如果power为父级 自动带入子集
            var sons = _userPower.GetList(f => f.parent.Equals(power.ToStr())).Select(s => s.id);
            foreach (var son in sons)
            {
                var model = _powerSection.Get(f => f.StationId == section && f.MenuId.Equals(son));
                if (model != null)
                {
                    _powerSection.Delete(model);
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}