using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using ExcelDataReader;
using GxPress.Common.Exceptions;
using GxPress.Common.Page;
using GxPress.Entity;
using GxPress.Repository.Interface;
using GxPress.Request.Print;
using GxPress.Request.User;
using GxPress.Result.Print;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace GxPress.Api.AdminControllers
{
    /// <summary>
    /// 出版数据
    /// </summary>
    [Route("api/admin/print")]
    [ApiController]
    [Authorize]
    public class AdminPrintController : ControllerBase
    {
        private readonly ILogger<AdminPrintController> _logger;
        private readonly IPrintRepository _repository;

        public AdminPrintController(ILogger<AdminPrintController> logger, IPrintRepository repository)
        {
            _logger = logger;
            _repository = repository;
        }

        /// <summary>
        /// 导入出版Excel数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<bool> PrintExcelUpload([FromBody] UserExcelUploadRequest request)
        {
            var relativePath = request.ExcelUrl;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //获取excel分析
            var stream = System.IO.File.Open("wwwroot/" + relativePath, FileMode.Open, FileAccess.Read);
            IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream);
            var result = reader.AsDataSet();
            var sheet = result.Tables["Sheet1"];
            var error = string.Empty;
            var listPrint = new List<Print>();
            for (int i = 1; i < sheet.Rows.Count; i++) //行
            {
                var print = new Print();
                if (i == 1)
                    continue;
                var amount = sheet.Rows[i][0].ToString().Trim(); //出版金额
                if (string.IsNullOrEmpty(amount))
                    error = "出版金额";
                print.PublishAmount = int.Parse(amount);
                var volumeCount = sheet.Rows[i][1].ToString().Trim(); //出版册数
                if (string.IsNullOrEmpty(volumeCount))
                    error = "出版册数";
                print.VolumeCount = int.Parse(volumeCount);
                var printAmount = sheet.Rows[i][2].ToString().Trim(); //印刷金额
                if (string.IsNullOrEmpty(printAmount))
                    error = "印刷金额";
                print.PrintAmount = int.Parse(printAmount);
                var enteringDateTime = sheet.Rows[i][3].ToString().Trim(); //录入时间
                if (string.IsNullOrEmpty(enteringDateTime))
                    error = "录入时间必填";
                print.EnteringDateTime = DateTime.Parse(enteringDateTime);
                if (!string.IsNullOrEmpty(error))
                    break;
                listPrint.Add(print);
            }

            if (!string.IsNullOrEmpty(error)) throw new BusinessException(error);
            //计算
            var success = await _repository.InsertAsync(listPrint);
            if (success == false)
                throw new BusinessException("服务器异常");
            return true;
        }
        /// <summary>
        /// 出版数据列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("list")]
        public async Task<PagedList<Print>> GetPagedList(PageParameter request)
        {
            return await _repository.GetPageListAsync(request);
        }
        /// <summary>
        /// 发行图表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("chart")]
        public async Task<PrintResult> GetSellChart(PrintRequest request)
        {
            return await _repository.GetPrintChartAsync(request);
        }
    }
}