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.Entities;
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 Siger.Middlelayer.Common.Helpers;

namespace Siger.ApiACC.Controllers.Report
{
    public class SeqDetailController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerCategory _sigerCategory;
        public SeqDetailController(IUnitOfWork unitOfWork, ISigerCategory sigerCategory)
        {
            _unitOfWork = unitOfWork;
            _sigerCategory = sigerCategory;
        }

        [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 IActionResult GetJson(string number, string data, string posturl, int page = 1, int pagesize = 10)
        {
            string resData = GetSeqDetail(number, data, 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 ExportAll(string number, string data, string posturl)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            int page = 1;
            int pagesize = 10000;
            string resData = GetSeqDetail(number, data, posturl, page, pagesize);
            JObject resJson = (JObject)JsonConvert.DeserializeObject(resData);

            if (resJson["code"] != null && resJson["code"].ToStr() == "0")
            {
                var resdata = resJson["data"];
                if (resdata != null)
                {
                    var resStr = JsonConvert.SerializeObject(resdata);
                    var resList = JsonConvert.DeserializeObject<List<SeqDetailTemplate>>(resStr);
                    if (resList != null && resList.Any())
                    {
                        EpPlusExcelHelper<SeqDetailTemplate> helper = null;
                        try
                        {
                            helper = new EpPlusExcelHelper<SeqDetailTemplate>();
                            var temporaryFileName = $"序列号详细信息_SeqDetail_{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("ExportSeqDetail failed, error:" + e);
                            throw new BadRequestException(RequestEnum.ExportFailed);
                        }
                        finally
                        {
                            helper?.Dispose();
                        }
                    }
                }
                else
                {
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
            }
            else
            {
                throw new BadRequestException(RequestEnum.ExportFailed);
            }

            throw new BadRequestException(CommonEnum.RecordNotFound);
        }

        private string GetSeqDetail(string number, string data, string posturl, int page = 1, int pagesize = 10)
        {
            try
            {
                JObject jsons = (JObject)JsonConvert.DeserializeObject(data);
                jsons["Offset"] = page;
                jsons["Limit"] = pagesize;
                jsons["Number"] = number;
                var posdata = JsonConvert.SerializeObject(jsons);
                var request = (HttpWebRequest)WebRequest.Create(posturl);
                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);
            }
        }
    }
}