using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
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;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Siger.ApiQMS.Controllers
{
    public class ProductAddtionController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectProductRepository _sigerProjectProduct;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSection;
        private readonly IQmsProductAddtion _productAddtion;

        public ProductAddtionController(IUnitOfWork unitOfWork, ISigerProjectProductRepository sigerProjectProduct, ISigerProjectLevelSectionRepository sigerProjectLevelSection, IQmsProductAddtion productAddtion)
        {
            _unitOfWork = unitOfWork;
            _sigerProjectProduct = sigerProjectProduct;
            _sigerProjectLevelSection = sigerProjectLevelSection;
            _productAddtion = productAddtion;
        }
        [HttpGet]
        public IActionResult Getlist(int sectionid,string productCode,int page,int pageSize)
        {
            //var staions = _sigerProjectLevelSection.GetLevelSectionIds(sectionid, ProjectId).Distinct().ToList();
            var data = _productAddtion.GetAddtionPagedList(sectionid, productCode, "", ProjectId, page, pageSize);

            return new PagedLongTotalObjectResult(data.Data, data.Total, page, pageSize);
        }
        [HttpPost]
        public IActionResult Add([FromBody]RequestAddtion request)
        {
            var obj = _productAddtion.Get(f => f.projectid == ProjectId && f.productid == request.ProductId && f.sectionid==request.sectionid);
            if (obj!=null)
                throw new BadRequestException(CommonEnum.RecordExits);

            _productAddtion.Insert(new Middlelayer.QmsRepository.Entities.siger_qms_product_addition
            {
                projectid=ProjectId,
                productid=request.ProductId,
                addval=request.Addval,
                sectionid=request.sectionid,
                status=(int)RowState.Valid
            });
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        [HttpPost]
        public IActionResult Modify([FromBody]RequestAddtion request)
        {
            var obj = _productAddtion.Get(f => f.projectid == ProjectId && f.productid == request.ProductId && f.id == request.Id);
            if (obj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            obj.productid = request.ProductId;
            obj.addval = request.Addval;
            obj.sectionid = request.sectionid;
            _productAddtion.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 = _productAddtion.Get(f => f.id == id);
                if (obj == null)
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                _productAddtion.Delete(obj);
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);

        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="sectionid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExporExcel(string productCode,int sectionid)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var data = _productAddtion.GetAddtionPagedList(sectionid, productCode, "", ProjectId, 1, 9999999).Data;
            
            if (!data.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var dataList = new List<ImportProductAddtion>();
            int step = 0;
            foreach (var item in data)
            {
                step += 1;
                dataList.Add(new ImportProductAddtion
                {
                    No = step,
                    ProductCode = item.ProductCode,
                    section=item.sectoindesc,
                  //ProductName = item.ProductName,
                   Val = item.AddVal
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<ImportProductAddtion> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<ImportProductAddtion>();
                    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("Export Inspection Standard Info failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}
