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

namespace Siger.ApiACC.Controllers.Report
{
    public class SeqDetailByDateController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerCategory _sigerCategory;
        private readonly ISnListRepository _snListRepository;
        private readonly ISigerTrSnTraceRepository _traceRepository;
        private readonly ISigerTrSnTraceDetailsRepository _traceDetailRepository;
        public SeqDetailByDateController(IUnitOfWork unitOfWork, ISigerCategory sigerCategory, ISigerTrSnTraceRepository sigerTrSnTrace, ISigerTrSnTraceDetailsRepository sigerTrSnTraceDtl, ISnListRepository snList)
        {
            _unitOfWork = unitOfWork;
            _sigerCategory = sigerCategory;
            _traceRepository = sigerTrSnTrace;
            _traceDetailRepository = sigerTrSnTraceDtl;
            _snListRepository = snList;
        }

        [HttpGet]
        public IActionResult GetJson(string data, string posturl, string dtStart, string dtEnd, int page = 1, int pagesize = 10)
        {
            string resData = GetSeqDetail(data, dtStart, dtEnd, posturl, page, pagesize);
            JObject resJson = (JObject)JsonConvert.DeserializeObject(resData);
            string count = resJson["total"] != null ? resJson["total"].ToStr() : "";
            if (resJson["code"].ToStr() == "0")
            {
                return new PagedObjectResult(resJson["data"], count.ToInt(), page, pagesize);
            }

            throw new BadRequestException(CommonEnum.RecordNotFound);
        }

        [HttpGet]

        public IActionResult GetTree()
        {
            var response = GetCategoryTree();
            return new ObjectResult(response);
        }

        private List<CategoryTree> GetCategoryTree()
        {
            var list = new List<CategoryTree>();
            var categorys = _sigerCategory.GetList(t => t.projectId == ProjectId && t.status == (int)RowState.Valid);

            foreach (var item in categorys.ToList())
            {
                list.Add(new CategoryTree
                {
                    id = item.id,
                    name = item.Name,
                    pid = item.Pid,
                    open = true,
                    ctype = item.Ctype,
                    header = item.Header,
                    posturl = item.PostUrl,
                    json = item.Json
                });
            }

            return list;
        }

        [HttpGet]
        public async Task<IActionResult> ExportAll(string number, string data, string dtStart, string dtEnd, string posturl, string productId, int line, int station, string pn)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            int page = 1;
            int pagesize = 10000;
            DateTime.TryParse(dtStart, out DateTime begin);
            DateTime.TryParse(dtEnd, out DateTime end);
            var endtime = end.AddDays(1).AddMinutes(-1);
            var result = await _traceRepository.TrSNTraceDateRtpPagedList(number, begin, endtime, ProjectId, productId, line, station, pn, page, pagesize);
            var records = result.Data.ToList();
            if (!records.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);


            var resList = new List<SeqDetailByDateTemplate>();

            foreach (var d in records)
            {
                resList.Add(new SeqDetailByDateTemplate
                {
                    sn = d.Sn,
                    Line = d.Line,
                    Station = d.Station,
                    Result = d.Result,
                    TransDateTime = d.TransDateTime.ToStr(),
                    User = d.User
                });
            }

            EpPlusExcelHelper<SeqDetailByDateTemplate> helper = null;
            try
            {
                helper = new EpPlusExcelHelper<SeqDetailByDateTemplate>();
                var temporaryFileName = $"按时间段查询_SeqDetailByDate_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                helper.GenerateExcel(resList, Path.Combine(rootDir, temporaryFileName));
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ExportSeqDetailByDate failed, error:" + e);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper?.Dispose();
            }
        }

        private string GetSeqDetail(string data, string posturl, string dtStart, string dtEnd, int page = 1, int pagesize = 10)
        {
            try
            {
                JObject jsons = (JObject)JsonConvert.DeserializeObject(data);
                jsons["Offset"] = page;
                jsons["Limit"] = pagesize;
                jsons["BeginDate"] = dtStart;
                jsons["EndDate"] = dtEnd;

                var posdata = JsonConvert.SerializeObject(jsons);
                var request = (HttpWebRequest)WebRequest.Create(posturl);
                System.Net.ServicePointManager.DefaultConnectionLimit = 300;
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                var byteData = Encoding.UTF8.GetBytes(posdata);
                var length = byteData.Length;
                request.ContentLength = length;
                var writer = request.GetRequestStream();
                writer.Write(byteData, 0, length);
                writer.Close();
                var response = (HttpWebResponse)request.GetResponse();
                var resData = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
                return resData;
            }
            catch
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
        }
        /// <summary>
        /// 导出sn信息
        /// </summary>
        /// <param name="number"></param>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        ///  <param name="productId"></param>
        ///  <param name="line"></param>
        ///  <param name="pn"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportSn(string number, string dtStart, string dtEnd, string productId, int line, string pn)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            int page = 1;
            int pagesize = 10000;
            DateTime.TryParse(dtStart, out DateTime begin);
            DateTime.TryParse(dtEnd, out DateTime end);
            var endtime = end.AddDays(1).AddMinutes(-1);
            var result = await _snListRepository.SnListRptDatePagedList(number, begin, endtime, ProjectId, productId, line, pn, page, pagesize);
            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
                });
            }

            EpPlusExcelHelper<SeqDetailList> helper = null;
            try
            {
                helper = new EpPlusExcelHelper<SeqDetailList>();
                var temporaryFileName = $"按时间段查询_SN_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                helper.GenerateExcel(resList, 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();
            }
        }

        /// <summary>
        /// 导出过站信息
        /// </summary>
        /// <param name="number"></param>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        /// <param name="productId"></param>
        /// <param name="line"></param>
        /// <param name="station"></param>
        /// <param name="pn"></param>
        /// <returns></returns>
        [HttpGet]
        [NoTokenValidateFilter]
        public IActionResult ExportTrace(string number, string dtStart, string dtEnd, string productId, int line, int station, string pn)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            int page = 1;
            int pagesize = 10000;
            DateTime.TryParse(dtStart, out DateTime begin);
            DateTime.TryParse(dtEnd, out DateTime end);
            var endtime = end.AddDays(1).AddMinutes(-1);
            var result = _traceRepository.TrSNTraceDateRtpPagedList(number, begin, endtime, ProjectId, productId, line, station, pn, page, pagesize).Result;
            var records = result.Data.ToList();
            if (!records.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);


            var resList = new List<SeqDetailByDateTemplate>();

            foreach (var d in records)
            {
                resList.Add(new SeqDetailByDateTemplate
                {
                    sn = d.Sn,
                    Line = d.Line,
                    Station = d.Station,
                    Result = d.Result,
                    TransDateTime = d.TransDateTime.ToStr(),
                    User = d.User
                });
            }

            EpPlusExcelHelper<SeqDetailByDateTemplate> helper = null;
            try
            {
                helper = new EpPlusExcelHelper<SeqDetailByDateTemplate>();
                var temporaryFileName = $"按时间段查询_ExportTrace_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                helper.GenerateExcel(resList, Path.Combine(rootDir, temporaryFileName));
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ExportTrace failed, error:" + e);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper?.Dispose();
            }
        }

        /// <summary>
        /// 导出过站明细信息
        /// </summary>
        /// <param name="number"></param>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        /// <param name="productId"></param>
        /// <param name="line"></param>
        /// <param name="station"></param>
        /// <param name="pn"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportTraceDts(string number, string dtStart, string dtEnd, string productId, int line, int station, string pn)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            int page = 1;
            int pagesize = 10000;
            DateTime.TryParse(dtStart, out DateTime begin);
            DateTime.TryParse(dtEnd, out DateTime end);
            var endtime = end.AddDays(1).AddMinutes(-1);
            var result = await _traceDetailRepository.TrSNTraceDtsRtpPagedList(number, begin, endtime, ProjectId, productId, line, station, pn, page, pagesize);
            var records = result.Data.ToList();
            if (!records.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);


            var resList = new List<TraceDtlTempleate>();

            foreach (var d in records)
            {
                resList.Add(new TraceDtlTempleate
                {
                    sn = d.SN,
                    item = d.Item,
                    value = d.Value,
                    result = d.Result,
                    transdate = d.TransDateTime.ToStr(),
                });
            }

            EpPlusExcelHelper<TraceDtlTempleate> helper = null;
            try
            {
                helper = new EpPlusExcelHelper<TraceDtlTempleate>();
                var temporaryFileName = $"按时间段查询_ExportTraceDts_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                helper.GenerateExcel(resList, Path.Combine(rootDir, temporaryFileName));
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ExportTraceDts failed, error:" + e);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper?.Dispose();
            }
        }
    }
}