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.Sell;
using GxPress.Request.User;
using GxPress.Result.sell;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace GxPress.Api.AdminControllers
{
    /// <summary>
    /// 发行数据
    /// </summary>
    [Route("api/admin/sell")]
    [ApiController]
    [Authorize]
    public class AdminSellController : ControllerBase
    {
        private readonly ILogger<AdminSellController> _logger;
        private readonly ISellRepository _repository;

        public AdminSellController(ILogger<AdminSellController> logger, ISellRepository repository)
        {
            _logger = logger;
            _repository = repository;
        }
        /// <summary>
        /// 发行数据Excel数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<bool> SellExcelUpload([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 listSell = new List<Sell>();
            for (int i = 1; i < sheet.Rows.Count; i++) //行
            {
                var sell = new Sell();
                if (i == 1)
                    continue;
                var sellAmount = sheet.Rows[i][0].ToString().Trim(); //金额
                if (string.IsNullOrEmpty(sellAmount))
                    error = "发行金额";
                sell.SellAmount = int.Parse(sellAmount);
                var sellVolumeCount = sheet.Rows[i][1].ToString().Trim(); //类型
                if (string.IsNullOrEmpty(sellVolumeCount))
                    error = "发行册数";
                sell.SellVolumeCount = int.Parse(sellVolumeCount);
                var enteringDateTime = sheet.Rows[i][2].ToString().Trim(); //录入时间
                if (string.IsNullOrEmpty(enteringDateTime))
                    error = "录入时间必填";
                sell.EnteringDateTime = DateTime.Parse(enteringDateTime);
                if (!string.IsNullOrEmpty(error))
                    break;
                listSell.Add(sell);
            }

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