using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.DashboardRepository.Entities;
using Siger.Middlelayer.DashboardRepository.Repositories.Interface;
using Siger.Middlelayer.DashboardRepository.Request;
using Siger.Middlelayer.DashboardRepository.Response;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;


namespace Siger.ApiDashboard.Controllers
{
    public class DashboardGroupController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly IDashboardMachineGroupRepository _machineGroupRepository;
        private readonly ISigerProjectUserRepository _userRepository;

        public DashboardGroupController(IUnitOfWork unitOfWork, ISigerProjectMachineRepository machineRepository,
        IDashboardMachineGroupRepository machineGroupRepository, ISigerProjectUserRepository userRepository)
        {
            _unitOfWork = unitOfWork;
            _machineRepository = machineRepository;
            _machineGroupRepository = machineGroupRepository;
            _userRepository = userRepository;
        }

        [HttpGet]
        public IActionResult GetList(int page, int pagesize)
        {
            Expression<Func<siger_project_dashboard_machine_group, bool>> Funkey = f => f.projectid == ProjectId && f.status == (int)RowState.Valid;
            var data = _machineGroupRepository.GetPagedList(page, pagesize, Funkey, "createtime", true);
            var machines = _machineRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            var res = new List<ResponseGetMachineGroup>();
            foreach (var item in data.Data)
            {
                var machineNames = "";
                if (!string.IsNullOrEmpty(item.machineid))
                {
                    var machineIdArr = item.machineid.Split(',').Select(t => t.ToInt()).ToList();
                    var groupMachines = machines.Where(t => machineIdArr.Contains(t.id)).ToList();
                    machineNames = string.Join(',', groupMachines.Select(t => t.title).ToList());
                }
                res.Add(new ResponseGetMachineGroup
                {
                    machineid = item.machineid,
                    machinename = machineNames,
                    username = item.userid,
                    createtime = item.createtime.ToString(ParameterConstant.DateTimeFormat),
                    id = item.id,
                    group = item.group
                });
            }
            return new PagedObjectResult(res, data.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult Add([FromBody]RequestAddMachineGroup req)
        {
            if (string.IsNullOrEmpty(req.group))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var exist = _machineGroupRepository.Get(t => t.group == req.group &&
                t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if (exist != null)
            {
                throw new BadRequestException(RequestEnum.DataExist);
            }
            #region//设备重复绑定组别校验
            //if (!string.IsNullOrEmpty(req.machineid))
            //{
            //    var machineIds = req.machineid.Split(',').ToList();
            //    foreach(var machineIdStr in machineIds)
            //    {
            //        var group = _machineGroupRepository.Get(t => (t.machineid.Contains("," + machineIdStr + ",") ||
            //            t.machineid.Contains(machineIdStr + ",") || t.machineid.Contains("," + machineIdStr) ||
            //            t.machineid == machineIdStr) && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            //        if(group != null)
            //        {
            //            throw new BadRequestException(RequestEnum.MachineHasBindGroup);
            //        }
            //    }
            //}
            #endregion
            var entity = new siger_project_dashboard_machine_group
            {
                machineid = req.machineid,
                userid = req.userid,
                group = req.group,
                createtime = DateTime.Now,
                projectid = ProjectId
            };
            _machineGroupRepository.Insert(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Edit([FromBody]RequestEditMachineGroup req)
        {
            if (string.IsNullOrEmpty(req.group))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var entity = _machineGroupRepository.Get(t => t.id == req.id && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var exist = _machineGroupRepository.Get(t => t.id != req.id && t.group == req.group &&
                t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if (exist != null)
            {
                throw new BadRequestException(RequestEnum.DataExist);
            }
            #region//设备重复绑定组别校验
            //if (!string.IsNullOrEmpty(req.machineid))
            //{
            //    var machineIds = req.machineid.Split(',').ToList();
            //    foreach (var machineIdStr in machineIds)
            //    {
            //        var group = _machineGroupRepository.Get(t => t.id != req.id && (t.machineid.Contains("," + machineIdStr + ",") ||
            //            t.machineid.Contains(machineIdStr + ",") || t.machineid.Contains("," + machineIdStr) ||
            //            t.machineid == machineIdStr) && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            //        if (group != null)
            //        {
            //            throw new BadRequestException(RequestEnum.MachineHasBindGroup);
            //        }
            //    }
            //}
            #endregion
            entity.machineid = req.machineid;
            entity.userid = req.userid;
            entity.group = req.group;
            _machineGroupRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult Delete(int id)
        {
            var entity = _machineGroupRepository.Get(t => t.id == id && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            entity.status = (int)RowState.Invalid;
            _machineGroupRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}
