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.Sell;
using GxPress.Request.Storehouse;
using GxPress.Request.User;
using GxPress.Result.Storehouse;
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/storehouse")]
    [ApiController]
    [Authorize]
    public class AdminStorehouseController : ControllerBase
    {
        private readonly ILogger<AdminStorehouseController> _logger;
        private readonly IStorehouseRepository _repository;

        public AdminStorehouseController(ILogger<AdminStorehouseController> logger, IStorehouseRepository repository)
        {
            _logger = logger;
            _repository = repository;
        }

        /// <summary>
        /// 仓库数据Excel数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<bool> StorehouseExcelUpload([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 listStorehouse = new List<Storehouse>();
            for (int i = 1; i < sheet.Rows.Count; i++) //行
            {
                var storehouse = new Storehouse();
                if (i == 1)
                    continue;
                var storehouseCount = sheet.Rows[i][0].ToString().Trim(); //金额
                if (string.IsNullOrEmpty(storehouseCount))
                    error = "库存数";
                storehouse.StorehouseCount = int.Parse(storehouseCount);

                var enteringDateTime = sheet.Rows[i][1].ToString().Trim(); //录入时间
                if (string.IsNullOrEmpty(enteringDateTime))
                    error = "录入时间必填";
                storehouse.EnteringDateTime = DateTime.Parse(enteringDateTime);
                if (!string.IsNullOrEmpty(error))
                    break;
                listStorehouse.Add(storehouse);
            }

            if (!string.IsNullOrEmpty(error)) throw new BusinessException(error);
            //计算
            var success = await _repository.InsertAsync(listStorehouse);
            if (success == false)
                throw new BusinessException("服务器异常");
            return true;
        }

        /// <summary>
        /// 仓库数据列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("list")]
        public async Task<PagedList<Storehouse>> GetPagedList(PageParameter request)
        {
            return await _repository.GetPageListAsync(request);
        }

        /// <summary>
        /// 库存图标
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("chart")]
        public async Task<StorehouseResult> GetStorehouseChart(StorehouseRequest request)
        {
            return await _repository.GetStorehouseChartAsync(request);
        }
    }
}