using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.Log;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Request;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.ApiQMS.Controllers
{
    public class RepairPostionSettingController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IQmsReworkPositionSetting _qmsReworkPositionSetting;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSection;
        public RepairPostionSettingController(IUnitOfWork unitOfWork, IQmsReworkPositionSetting qmsReworkPosition,ISigerProjectLevelSectionRepository sigerProjectLevelSection)
        {
            _unitOfWork = unitOfWork;
            _qmsReworkPositionSetting = qmsReworkPosition;
            _sigerProjectLevelSection = sigerProjectLevelSection;
        }

        public IActionResult GetList(int prestion,int station,int page,int pageSize)
        {
            var data = _qmsReworkPositionSetting.GetPositionSettingPagedList(prestion, station, ProjectId, page, pageSize);
            var result = data.Data.ToList();
            foreach(var d in result)
            {
                d.LineDesc = GetAllTitle(d.Line);
            }

            return new PagedLongTotalObjectResult(data.Data, data.Total, page, pageSize);
        }
        private string GetAllTitle(int sectionId)
        {
            var titles = _sigerProjectLevelSection.GetLevelSectionTitles(sectionId, ProjectId);
            var list = titles.ToList();
            return list.Any() ? string.Join('-', list) : string.Empty;
        }
        [HttpPost]
        public IActionResult Add([FromBody]RequestReworkPositionSetting setting)
        {
            if (!_sigerProjectLevelSection.IsExist(f=>f.projectid==ProjectId && f.id==setting.PreStation))
                throw new BadRequestException(RequestEnum.StationIsEmpty);
            if (!_sigerProjectLevelSection.IsExist(f => f.projectid == ProjectId && f.id == setting.Station))
                throw new BadRequestException(RequestEnum.StationIsEmpty);

            var obj = _qmsReworkPositionSetting.Get(f => f.projectid == ProjectId && f.Prestation == setting.PreStation && f.Station == setting.Station && f.status == (int)RowState.Valid);
            if (obj!=null)
                throw new BadRequestException(CommonEnum.RecordExits);

            _qmsReworkPositionSetting.Insert(new Middlelayer.QmsRepository.Entities.siger_qms_rework_postion_setting {
                 projectid=ProjectId,
                 Prestation=setting.PreStation,
                 Station=setting.Station,
                 DateTime=DateTime.Now,
                 Userid=UserId,
                 status=(int)RowState.Valid
            });
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);

        }
        [HttpPost]
        public IActionResult Modify([FromBody]RequestReworkPositionSetting setting)
        {

            var obj = _qmsReworkPositionSetting.Get(f => f.id==setting.Id&& f.projectid==ProjectId);
            if (obj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            obj.Prestation = setting.PreStation;
            obj.Station = setting.Station;
            obj.Userid = UserId;

            _qmsReworkPositionSetting.Update(obj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);

        }
        [HttpPost]
        public IActionResult Del([FromBody]RequestDeleteParameter req)
        {
            if (req.ids == null || !req.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var objs = _qmsReworkPositionSetting.GetList(f => req.ids.Contains(f.id) && f.projectid == ProjectId).ToList();
            if (!objs.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            foreach(var obj in objs)
            {
                _qmsReworkPositionSetting.Delete(obj);
            }            
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpGet]
        public IActionResult GetPreStaion()
        {
            var data = _qmsReworkPositionSetting.GetList(f => f.projectid == ProjectId).Select(s => s.Prestation).ToList();
            if (data.Any())
            {
                var sections = _sigerProjectLevelSection.GetList(f => f.projectid == ProjectId && data.Contains(f.id));
                return new ObjectResult(sections);
            }
            return new ObjectResult(0);
        }
        [HttpGet]
        public IActionResult GetStaion(int preStation)
        {

            var data = _qmsReworkPositionSetting.GetList(f => f.projectid == ProjectId && f.Prestation==preStation).Select(s => s.Station).ToList();
            if (data.Any())
            {
                var sections = _sigerProjectLevelSection.GetList(f => f.projectid == ProjectId && data.Contains(f.id)).GroupBy(g=>g.id).Select(s=>s.FirstOrDefault()).ToList();
                return new ObjectResult(sections);
            }
            return new ObjectResult(0);
        }
       
        public IActionResult ExporExcel(int prestion, int station, int page, int pageSize)
        {
            var data = _qmsReworkPositionSetting.GetPositionSettingPagedList(prestion, station, ProjectId, 1, 999999);

            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            //  var data = _reworkDataRepository.GetRepairAllData(param.MaterialId, param.ProductId, param.PreRoute, param.Route, 0, param.Sn, param.BeginTime, param.EndTime, (int)param.reworkDataType, ProjectId);
            if (!data.Data.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var dataList = new List<ReworkPositionReworkSetting>();
            foreach (var item in data.Data)
            {
                var LineDesc = GetAllTitle(item.Line);
                dataList.Add(new ReworkPositionReworkSetting
                {
                  Line= LineDesc,
                  PreStation =item.PreSationDesc,
                  Station=item.StationDesc
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<ReworkPositionReworkSetting> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<ReworkPositionReworkSetting>();
                    var temporaryFileName = $"返工工位设置_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(dataList, Path.Combine(rootDir, temporaryFileName), true);
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("Export Inspection Standard Info failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 获取通道
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetChanel()
        {
            var line = _sigerProjectLevelSection.GetAccLines(ProjectId);

            return new ObjectResult(line);
        }
        /// <summary>
        /// 获取通道下 返工工位
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSettingByChanel(int Id)
        {
            var stations = _sigerProjectLevelSection.GetAccStationByline(ProjectId,Id).Select(s=>s.id).ToList();
            var data = _qmsReworkPositionSetting.GetReworkStation(ProjectId,stations).OrderBy(q => q.Id).ToList();

            return new ObjectResult(data);
        }
    }
}
