using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.FieldEnum;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository;
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.ApiConfig.Controller
{
    public class MonthReportController : BaseController
    {
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly IMonthReportConfigRepository _reportConfigRepository;
        private readonly ISigerProjectLevelRepository _levelRepository;
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectMachineRepository _machineRepository;
        public MonthReportController(IMonthReportConfigRepository reportConfigRepository, ISigerProjectLevelSectionRepository levelSectionRepository,
            IUnitOfWork unitOfWork, ISigerProjectLevelRepository levelRepository, ISigerProjectMachineRepository machineRepository)
        {
            _levelSectionRepository = levelSectionRepository;
            _reportConfigRepository = reportConfigRepository;
            _unitOfWork = unitOfWork;
            _levelRepository = levelRepository;
            _machineRepository = machineRepository;
        }

        [HttpGet]
        public IActionResult GetConfigPagedList(int page = 1, int pagesize = 10)
        {
            var configs = _reportConfigRepository.GetConfigPagedList(page, pagesize, ProjectId);

            return new PagedObjectResult(configs.Data, configs.Total, page, pagesize);
        }

        [HttpGet]
        public IActionResult GetReportConfigItem(int id)
        {
            var entity = _reportConfigRepository.Get(q => q.id == id && q.project_id == ProjectId && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var repsonse = new ResponseGetReportConfig
            {
                id = entity.id,
                cycle = (int)entity.cycle,
                first_date = entity.first_date.ToString(ParameterConstant.DateFormat),
                name = entity.name,
                product_id = entity.product_id,
                remark = entity.remark,
                send_time = entity.send_time,
                sectionids = entity.sectionids,
                template_id = (int)entity.template_id,
                user_mids = string.IsNullOrWhiteSpace(entity.user_mids)
                    ? new List<string>()
                    : entity.user_mids.Split(',').ToList(),
                day_interval = string.IsNullOrWhiteSpace(entity.day_interval) 
                    ? new List<string>() 
                    : entity.day_interval.Split(',').ToList()
            };

            return new ObjectResult(repsonse);
        }

        /// <summary>
        /// 添加配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddReportConfig([FromBody]RequestAddReportConfig request)
        {
            var success = DateTime.TryParse(request.first_date, out var dtFirstTime);
            if (!success)
            {
                throw new ServerException(500146);
            }

            var isExist = _reportConfigRepository.Get(q => q.name == request.name && q.project_id == ProjectId && q.status == (int) RowState.Valid);
            if (isExist != null)
            {
                throw new BadRequestException(RequestEnum.NameHasExist);
            }

            var entity = new siger_project_monthreport_config
            {
                name = request.name,
                cycle = (MonthReportCycle)request.cycle,
                day_interval = request.day_interval,
                first_date = dtFirstTime,
                send_time = request.send_time,
                remark = request.remark,
                template_id = (ReportTemplate)request.template_id,
                user_mids = request.userIds,
                sectionids = request.sectionIds,
                product_id = request.productId.ToInt(),
                project_id = ProjectId,
                company_id = CompanyId,
                create_time = DateTime.Now,
                create_mid = UserId
            };

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

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

            var isExist = _reportConfigRepository.Get(q => q.name == request.name && q.project_id == ProjectId && q.status == (int)RowState.Valid
                                                           && q.id != request.id);
            if (isExist != null)
            {
                throw new BadRequestException(RequestEnum.NameHasExist);
            }

            var success = DateTime.TryParse(request.first_date, out var dtFirstTime);
            if (!success)
            {
                throw new ServerException(500146);
            }
            entity.name = request.name;
            entity.cycle = (MonthReportCycle) request.cycle;
            entity.day_interval = request.day_interval;
            entity.first_date = dtFirstTime;
            entity.send_time = request.send_time;
            entity.remark = request.remark;
            entity.sectionids = request.sectionIds;
            entity.product_id = request.productId.ToInt();
            entity.user_mids = request.userIds;

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

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

            entity.status = (int) RowState.Invalid;
            _reportConfigRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 取产线层级
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSectionTreeForMonthReport(int id = 0, int type = 1, int nc = 0)
        {
            var levels = _levelRepository.GetList(t => t.status == (int) RowState.Valid && t.projectid == ProjectId).OrderBy(t=>t.id).ToList();
            var list = new List<LevelSectionTree>();
            if (nc == 0)
            {
                list = _levelSectionRepository.GetLevelSectionTree(ProjectId).ToList();
            }
            else
            {
                var levelSections = _machineRepository.GetNCLevelSections(0, ProjectId);
                list = levelSections.Select(t => new LevelSectionTree
                {
                    id = t.id,
                    name = t.title,
                    title = t.title,
                    pid = t.parentid,
                    levelId = t.levelid,
                    open = true,
                }).ToList();
            }
            if (type == 2)
            {
                //去掉最后一层
                var lastLevel = levels.Last().id;
                list = list.Where(q => q.levelId != lastLevel).ToList();
            }
            var responses = new List<LevelSectionTree>();
            //是否选中
            if (id > 0)
            {
                var entity = _reportConfigRepository.Get(q => q.id == id && q.project_id == ProjectId && q.status == (int)RowState.Valid);
                if (entity == null)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }

                if (!string.IsNullOrWhiteSpace(entity.sectionids))
                {
                    var checkedIds = entity.sectionids.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries).ToList();
                    foreach (var levelSectionTree in list)
                    {
                        levelSectionTree.@checked = checkedIds.Contains(levelSectionTree.id.ToStr());
                        responses.Add(levelSectionTree);
                    }
                }
                else
                {
                    responses = list;
                }
            }
            else
            {
                responses = list;
            }

            var response = new ResponseLevelSectionChildren(ConvertToTree(responses));

            return new ObjectResult(response);
        }

        private IList<LevelSectionTree> ConvertToTree(IEnumerable<LevelSectionTree> models)
        {
            var section = new Dictionary<int, LevelSectionTree>();
            foreach (var item in models)
            {
                item.disabled = false;
                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;
        }
        /// <summary>
        /// 获取倒数第二层产线结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllLines()
        {
            var lines = _levelSectionRepository.GetAllLines(ProjectId);

            return new ObjectResult(lines);
        }


    }
}