using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Request;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;
using Siger.Middlelayer.Common.Extensions;

namespace Siger.ApiQMS.Controllers
{
    public class ProductWarehousingController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectProductRepository _sigerProjectProduct;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSection;
        private readonly IQmsProductWarehousing _qmsProductWarehousing;

        public ProductWarehousingController(IUnitOfWork unitOfWork, ISigerProjectProductRepository sigerProjectProduct,ISigerProjectLevelSectionRepository sigerProjectLevelSection,IQmsProductWarehousing qmsProductWarehousing)
        {
            _unitOfWork = unitOfWork;
            _sigerProjectProduct = sigerProjectProduct;
            _sigerProjectLevelSection = sigerProjectLevelSection;
            _qmsProductWarehousing = qmsProductWarehousing;
        }
        [HttpGet]
        public IActionResult Getlist(string productCode,int section, string startdate, string enddate, int page, int pageSize)
        {
            var staions = _sigerProjectLevelSection.GetLevelSectionIds(section, ProjectId).Distinct().ToList();
            var data = _qmsProductWarehousing.GetWarehousPagedList(productCode, staions, startdate, enddate, ProjectId, page, pageSize);

            return new PagedLongTotalObjectResult(data.Data, data.Total, page, pageSize);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="section"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExporExcel(string productCode, int section, string startdate, string enddate)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            if (!Directory.Exists(rootDir))
                Directory.CreateDirectory(rootDir);

            var staions = _sigerProjectLevelSection.GetLevelSectionIds(section, ProjectId).Distinct().ToList();
            var data = _qmsProductWarehousing
                .GetWarehousPagedList(productCode, staions, startdate, enddate, ProjectId, 1, 9999999).Data;

            if (!data.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var dataList = new List<ImportProductWarehouse>();
            var step = 0;
            foreach (var item in data)
            {
                step += 1;
                dataList.Add(new ImportProductWarehouse
                {
                    No = step,
                    Section = item.SectoinDesc,
                    CreateDate = item.CreateTimeDt.ToString(ParameterConstant.DateFormat),
                    ProductCode = item.ProductCode,
                    User = item.UserName,
                    Operate = item.Operate,
                    Qty = item.Qty
                });
            }

            if (dataList.Any())
            {
                EpPlusExcelHelper<ImportProductWarehouse> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<ImportProductWarehouse>();
                    var temporaryFileName = $"入库数量管理_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(dataList, Path.Combine(rootDir, temporaryFileName), true);
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("ExporExcel Info failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Add([FromBody]RequestWareHous request)
        {           
            _qmsProductWarehousing.Insert(new Middlelayer.QmsRepository.Entities.siger_qms_product_warehousing
            {
                projectid = ProjectId,
                productid = request.ProductId,
                section = request.Section,
                createtime = request.Inputtime.ToDateTime(),
                qty = request.Count,
                mid = UserId,
                operate = DateTime.Now,
                type = 1,
                status = (int)RowState.Valid
            });
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpPost]
        public IActionResult Modify([FromBody]RequestWareHous request)
        {
            var obj = _qmsProductWarehousing.Get(request.Id);
            if (obj==null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            obj.productid = request.ProductId;
            obj.section = request.Section;
            obj.qty = request.Count;
            obj.createtime = request.Inputtime.ToDateTime();

            _qmsProductWarehousing.Update(obj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpPost]
        public IActionResult Del([FromBody]RequestIds request)
        {
            if (!request.ids.Any())
                throw new BadRequestException(RequestEnum.ParameterMiss);
            foreach (var id in request.ids)
            {
                var obj = _qmsProductWarehousing.Get(id);
                if (obj == null)
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                _qmsProductWarehousing.Delete(obj);
               
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}
