using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.ModuleEnum;
using System.Collections.Generic;
using Siger.Middlelayer.AccRepository.Response;
using System.Linq;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Utility.ImportEntities;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common.AppSettings;
using System.IO;
using System;
using System.Threading.Tasks;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Common.Log;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;

namespace Siger.ApiACC.Controllers.Report
{
    public class SNController : BaseController
    {
        private readonly ISnListRepository _snListRepository;
        private readonly ISigerTrSnTraceRepository _traceRepository;
        private readonly ISigerTrSnTraceDetailsRepository _traceDetailRepository;
        private readonly ISigerAccTraceRepository _accTrace;
        private readonly ISigerProjectLevelSectionRepository _projectLevelSectionRepository;
        private readonly ISigerTrSnTraceSummaryRepository _traceSummaryRepository;
        private IUnitOfWork _unitOfWork;
        public SNController(IUnitOfWork unitOfWork, ISnListRepository snListRepository, ISigerTrSnTraceRepository traceRepository, ISigerTrSnTraceDetailsRepository snTraceDetailsRepository
            , ISigerAccTraceRepository accTrace, ISigerTrSnTraceSummaryRepository traceSummaryRepository, ISigerProjectLevelSectionRepository projectLevelSectionRepository
            )
        {
            _unitOfWork = unitOfWork;
            _snListRepository = snListRepository;
            _traceRepository = traceRepository;
            _traceDetailRepository = snTraceDetailsRepository;
            _projectLevelSectionRepository = projectLevelSectionRepository;
            _traceSummaryRepository = traceSummaryRepository;
            _accTrace = accTrace;
        }
        [HttpPost]
        public async Task<IActionResult> GetData([FromBody]RequestACCRpt rpt)
        {
            if (rpt.Category != AccEnum.SN)
                throw new BadRequestException(AccEnum.Msg_Category_Err);

            switch (rpt.Rpt)
            {
                case AccEnum.Sn_List:
                    {
                        var result = await _snListRepository.SnListRptDatePagedList(rpt.Number, rpt.DtStart, rpt.DtEnd.AddDays(1).AddMinutes(-1), ProjectId, rpt.ProductId, rpt.Line, rpt.PN, rpt.Offset, rpt.Limit);
                        if (!result.Data.Any())
                            throw new BadRequestException(AccEnum.EmtyResult);
                        return new PagedObjectResult(result.Data, result.Total, rpt.Offset, rpt.Limit);
                    }
                case AccEnum.Sn_Trace:
                    {
                        var result = await _traceRepository.TrSNTraceDateRtpPagedList(rpt.Number, rpt.DtStart, rpt.DtEnd.AddDays(1).AddMinutes(-1), ProjectId, rpt.ProductId, rpt.Line, rpt.Station, rpt.PN, rpt.Offset, rpt.Limit);
                        if (!result.Data.Any())
                            throw new BadRequestException(AccEnum.EmtyResult);
                        return new PagedObjectResult(result.Data, result.Total, rpt.Offset, rpt.Limit);

                    }
                case AccEnum.Sn_TraceDetails:
                    {
                        var result = await _traceDetailRepository.TrSNTraceDtsRtpPagedList(rpt.Number, rpt.DtStart, rpt.DtEnd.AddDays(1).AddMinutes(-1), ProjectId, rpt.ProductId, rpt.Line, rpt.Station, rpt.PN, rpt.Offset, rpt.Limit);
                        if (!result.Data.Any())
                            throw new BadRequestException(AccEnum.EmtyResult);
                        return new PagedObjectResult(result.Data, result.Total, rpt.Offset, rpt.Limit);
                    }
                default:
                    {
                        throw new BadRequestException(AccEnum.Msg_Rpt_Null);
                    }
            }

        }
        /// <summary>
        /// 1.2追溯查询SN
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetSnData([FromBody]RequestQuerySnData req)
        {
            var result = await _snListRepository.SnListRptDatePagedList(req, ProjectId);
            return new PagedObjectResult(result.Data, result.Total, req.page, req.pagesize);
        }
        /// <summary>
        /// 1.2追溯查询Trace
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetTraceDataAsync([FromBody]RequestQuerySnData req)
        {
            var result = await _traceRepository.TrSNTraceDateRtpPagedList(req.Sn, DateTime.Now, DateTime.Now, ProjectId, req.ProductId, req.Line, req.Station, req.Pn, req.page, req.pagesize);
            return new ObjectResult(result.Data);
        }
        /// <summary>
        /// 1.2追溯查询TraceDetail
        /// </summary>
        /// <param name="seqid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTraceDetail(string seqid)
        {
            var result = _traceDetailRepository.GetList(f => f.SeqID.Equals(seqid) && f.projectId.Equals(ProjectId) && f.status != (int)RowState.Invalid);
            return new ObjectResult(result);
        }

        /// <summary>
        /// 获取首页汇总数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSummaryData()
        {
            var resp = new List<ResponseTraceSummary>();
            var lines = _projectLevelSectionRepository.GetAccLines(ProjectId);
            var summaryData = _traceSummaryRepository.GetList(f => f.projectId.Equals(ProjectId) && f.status == (int)RowState.Valid, "station", false);
            foreach (var line in lines)
            {
                var respModel = new ResponseTraceSummary();
                var summaryModel = summaryData.Where(f => f.Line == line.id);
                summaryModel.ToList().ForEach(data =>
                {
                    var model = new ResponseStationSummary
                    {
                        Name = _projectLevelSectionRepository.Get(f => f.id == data.Station).title,
                        NgCount = data.NgCount,
                        OkCount = data.OkCount,
                        Quantity = data.Quantity,
                        WorkCount = data.WorkCount
                    };
                    respModel.Stations.Add(model);
                });
                respModel.Line = _accTrace.GetLineStationData(line.id, ProjectId);
                resp.Add(respModel);
            }
            return new ObjectResult(resp);
        }

        /// <summary>
        /// 导出sn信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ExportData([FromBody]RequestQuerySnData req)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            //sn
            req.page = 1;
            req.pagesize = 10000;
            var result = await _snListRepository.SnListRptDatePagedList(req, ProjectId);
            var records = result.Data.ToList();
            if (!records.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var resList = new List<SeqDetailList>();
            foreach (var d in records)
            {
                resList.Add(new SeqDetailList
                {
                    sn = d.Sn,
                    productID = d.ProcutId,
                    line = d.Line,
                    wo = d.WO,
                    inputDateTime = d.InputDateTime.ToStr(),
                    transDateTime = d.UpdateTime.ToStr(),
                    productname = d.ProcutName,
                    result = d.Result,
                    station = d.Station
                });
            }
            var sns = resList.Select(s => s.sn).ToList();
            //trace
            var traceResult = await _traceRepository.TrSNTraceDateRtpPagedList(sns, ProjectId);
            var traceList = new List<SeqDetailByDateTemplate>();
            if (traceResult.Any())
            {
                foreach (var d in traceResult)
                {
                    traceList.Add(new SeqDetailByDateTemplate
                    {
                        sn = d.Sn,
                        Line = d.Line,
                        Station = d.Station,
                        Result = d.Result,
                        TransDateTime = d.TransDateTime.ToStr(),
                        User = d.User
                    });
                }
            }
            //detail
            var detailResult = await _traceDetailRepository.TrSNTraceDtsRtpPagedList(sns, ProjectId);
            var detailList = new List<TraceDtlTempleate>();
            if (detailResult.Any())
            {
                foreach (var d in detailResult)
                {
                    detailList.Add(new TraceDtlTempleate
                    {
                        sn=d.SN,
                        item = d.Item,
                        value = d.Value,
                        result = d.Result,
                        transdate = d.TransDateTime.ToStr(),
                    });
                }
            }

            EpPlusExcelHelper<SeqDetailList> helper = null;
            try
            {
                helper = new EpPlusExcelHelper<SeqDetailList>();
                var temporaryFileName = $"查询统计_SN_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                helper.GenerateExcel(resList,traceList,detailList, Path.Combine(rootDir, temporaryFileName));
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ExportSn failed, error:" + e);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper?.Dispose();
            }
        }

    }
}