using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.QmsRepository.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Log;
using System.IO;
using Siger.Middlelayer.Utility.ImportEntities;
using Siger.Middlelayer.Common.AppSettings;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.QmsRepository.Entities;
using NPOI.SS.Formula.Functions;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using Siger.Middlelayer.Common.Helpers;

namespace Siger.ApiQMS.Controllers
{

    public class ManufacturingMaterialController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSection;
        private readonly IQmsmanufacturingMaterial _qmsmanufacturingMaterial;
        private readonly IQmsCellStationRepository _qmsCellStationRepository;
        private readonly IQmscellRepository _qmscell;

        public ManufacturingMaterialController(IUnitOfWork unitOfWork,ISigerProjectLevelSectionRepository sigerProjectLevelSection, IQmsmanufacturingMaterial qmsmanufacturingMaterial, IQmsCellStationRepository qmsCellStation,IQmscellRepository qmscell)
        {
            _unitOfWork = unitOfWork;
            _sigerProjectLevelSection = sigerProjectLevelSection;
            _qmsmanufacturingMaterial = qmsmanufacturingMaterial;
            _qmsCellStationRepository = qmsCellStation;
            _qmscell = qmscell;
        }

        [HttpGet]
        public IActionResult Getlist(int productId, int materialId, int section, int page, int pageSize)
        {
            var levelsections = _sigerProjectLevelSection.GetLevelSectionIds(section, ProjectId).ToList();
            var data = _qmsmanufacturingMaterial.GetManufacturingPagedList(levelsections, materialId, productId, ProjectId, page, pageSize);

            var result = data.Data.ToList();
            foreach (var d in result)
            {
                d.SectionDesc = GetAllTitle(d.Section);
            }
            return new PagedLongTotalObjectResult(result, data.Total, page, pageSize);
        }
        [HttpGet]
        public IActionResult ExportExcel(int productId, int materialId, int section)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            var levelsections = _sigerProjectLevelSection.GetLevelSectionIds(section, ProjectId).ToList();
            var data = _qmsmanufacturingMaterial.GetManufacturingPagedList(levelsections, materialId, productId, ProjectId, 1, 9999999);

            var result = data.Data.ToList();
            var dataList = new List<ImportManufacturingMaterial>();
            foreach (var item in result)
            {
                var lineObj = _sigerProjectLevelSection.Get(f => f.id == item.Line);
                var sectionObj = _sigerProjectLevelSection.Get(f => f.id == item.Line);
                dataList.Add(new ImportManufacturingMaterial
                {
                    Line=lineObj!=null?lineObj.title:item.Line.ToString(),
                    Section= sectionObj != null ? sectionObj.title : item.Section.ToString(),
                    Product=item.ProdcutName,
                    ProductCode=item.ProductCode,
                    Material = $"{item.MaterialName}-{item.MaterialSpec}",
                    Qty =item.Count,
                });
            }

            if (dataList.Any())
            {
                EpPlusExcelHelper<ImportManufacturingMaterial> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<ImportManufacturingMaterial>();
                    var temporaryFileName = $"物料结构_ImportManufacturingMaterial_{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 ImportManufacturingMaterial Info failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);

        }
        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]RequestManufacturing request)
        {
            if ( _qmsmanufacturingMaterial.IsExist(f=>f.projectid==ProjectId && f.section==request.Section && f.productId==request.ProductId && f.materail==request.MaterialId))
                throw new BadRequestException(CommonEnum.RecordExits);

            _qmsmanufacturingMaterial.Insert(new Middlelayer.QmsRepository.Entities.siger_qms_cell_manufacturing
            {
                projectid = ProjectId,
                productId = request.ProductId,
                materail = request.MaterialId,
                section = request.Section,
                count = request.Count,
                status = (int)RowState.Valid
            });

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

        }
        [HttpPost]
        public IActionResult Modify([FromBody]RequestManufacturing request)
        {
            var Obj = _qmsmanufacturingMaterial.Get(f => f.projectid == ProjectId && f.id == request.Id);
            if (Obj==null)
                return new ObjectResult(CommonEnum.RecordNotFound);
            if (_qmsmanufacturingMaterial.IsExist(f =>
                f.projectid == ProjectId && f.section == request.Section && f.productId == request.ProductId &&
                f.materail == request.MaterialId && f.id != request.Id))
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }
            Obj.section = request.Section;
            Obj.productId = request.ProductId;
            Obj.materail = request.MaterialId;
            Obj.count = request.Count;

            _qmsmanufacturingMaterial.Update(Obj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Del([FromBody]RequestIds request)
        {
            if (!request.ids.Any())
                throw new BadRequestException(RequestEnum.ParameterMiss);
            foreach (var id in request.ids)
            {
                var obj = _qmsmanufacturingMaterial.Get(f => f.id == id);
                if (obj == null)
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                _qmsmanufacturingMaterial.Delete(obj);
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetMaterialByCell(int section,int productId)
        {
            var dataCellStation = _qmsCellStationRepository.Get(f => f.section == section);
            if (dataCellStation == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var dataCell = _qmscell.Get(f => f.id == dataCellStation.cell);
            if (dataCell==null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var sections = GetCellStation(section);
            var data = _qmsmanufacturingMaterial.GetMaterialByCells(ProjectId, productId, sections);
            return new ObjectResult(data);
        }

        IEnumerable<int> GetCellStation(int section)
        {
            var result = new List<int> { section };
            //var station = _sigerProjectLevelSection.GetAccStation(ProjectId);
            var levelSection = _sigerProjectLevelSection.Get(f => f.projectid == ProjectId && f.id == section);
            if (levelSection == null)
                return result;
            //同一通道/产线
            var currentStationLevel = _sigerProjectLevelSection.GetList(f => f.projectid == ProjectId && f.parentid == levelSection.parentid);
            var stations = currentStationLevel.Select(s => s.id).ToList();
            var data = _qmsCellStationRepository.GetList(f => f.projectid == ProjectId && stations.Contains(f.section)).ToList();
            var comboxIds = data.Select(s => s.cell).ToList();
            var cellCombox = _qmscell.GetList(f => f.projectid == ProjectId && comboxIds.Contains(f.id)).ToList();

            var cStaion = _qmsCellStationRepository.Get(f => f.projectid == ProjectId && f.section == section);
            // var cellCombox = _qmscell.GetList(f => f.projectid == ProjectId && f.status == (int)RowState.Valid);
            var cellObj = _qmscell.Get(f => f.id == cStaion.cell);
            var CellIds = GetCellComboxIds(cellCombox, cellObj.cell);
            CellIds.Add(cStaion.cell);

            var cStaionList = data.Where(f => f.projectid == ProjectId  && CellIds.Contains(f.cell));

            var ids = new List<int>();
            foreach(var station in cStaionList)
            {
                if (station.cell == cStaion.cell)
                {
                    if (station.step > cStaion.step)
                        continue;
                }
                ids.Add(station.section);
            }
           // var stationsArry = cStaionList.Select(s => s.section);
            result.AddRange(ids);
            return result;
        }
        List<int> GetCellComboxIds(List<siger_qms_cell> data, int Cell)
        {
            var comboxIds = new List<int>();
            var comboxs = data.Where(f => f.nextcell == Cell);
            foreach (var combox in comboxs)
            {
                if (combox != null)
                {
                    comboxIds.Add(combox.id);
                    comboxIds.AddRange(GetCellComboxIds(data, combox.cell));
                }
            }

            return comboxIds;
        }
    }
}
