using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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.Finance;
using GxPress.Request.User;
using GxPress.Result.Finance;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace GxPress.Api.AdminControllers
{
    /// <summary>
    /// 财务数据
    /// </summary>
    [Route("api/admin/finance")]
    [ApiController]
    [Authorize]
    public class AdminFinanceController : ControllerBase
    {
        private readonly ILogger<AdminFinanceController> _logger;
        private readonly IFinanceRepository _repository;

        public AdminFinanceController(ILogger<AdminFinanceController> logger, IFinanceRepository repository)
        {
            _logger = logger;
            _repository = repository;
        }

        /// <summary>
        /// 解析财务数据Excel数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<bool> FinanceExcelUpload([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 listFinance = new List<Finance>();
            for (int i = 1; i < sheet.Rows.Count; i++) //行
            {
                var finance = new Finance();
                if (i == 1)
                    continue;
                var amount = sheet.Rows[i][0].ToString().Trim(); //金额
                if (string.IsNullOrEmpty(amount))
                    error = "金额必填";
                finance.Amount = int.Parse(amount);
                var financeType = sheet.Rows[i][1].ToString().Trim(); //类型
                if (string.IsNullOrEmpty(financeType))
                    error = "类型必须";
                finance.FinanceType = int.Parse(financeType);
                var enteringDateTime = sheet.Rows[i][2].ToString().Trim(); //录入时间
                if (string.IsNullOrEmpty(enteringDateTime))
                    error = "录入时间必填";
                finance.EnteringDateTime = DateTime.Parse(enteringDateTime);
                if (!string.IsNullOrEmpty(error))
                    break;
                listFinance.Add(finance);
            }

            if (!string.IsNullOrEmpty(error)) throw new BusinessException(error);
            //计算
            var success = await _repository.InsertAsync(listFinance);
            if (success == false)
                throw new BusinessException("服务器异常");
            return true;
        }
        /// <summary>
        /// 财务列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("list")]
        public async Task<PagedList<Finance>> GetPagedList(PageParameter request)
        {
            return await _repository.GetPageListAsync(request);
        }
        /// <summary>
        /// 财务图表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("chart")]
        public async Task<FinanceResult> GetFinanceChart(FinanceRequest request)
        {
            return await _repository.GetFinanceChartAsync(request);
        }
    }
}