using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.AccRepository.Response;
using Siger.Middlelayer.Common.Helpers;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common.AppSettings;
using System.IO;
using Siger.Middlelayer.Utility.ImportEntities;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Log;


namespace Siger.ApiACC.Controllers
{
    public class SerinumConfigController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISeriNumCfg _serinumCfgRepository;
        public SerinumConfigController(IUnitOfWork unitOfWork, ISeriNumCfg serinumCfgRepository)
        {
            _unitOfWork = unitOfWork;
            _serinumCfgRepository = serinumCfgRepository;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="rule"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetList(string productCode,int rule, int page = PageIndex, int pagesize = PageSize)
        {
            var data = _serinumCfgRepository.GetPagedConfigList(productCode,rule, page, pagesize);
            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="requestAdd"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody] RequestAddSerinumCfg requestAdd)
        {
            var isExist = _serinumCfgRepository.IsExist(f => f.ProductID == requestAdd.productId && f.Rule== requestAdd.ruleType && f.projectId == ProjectId && f.Seq==requestAdd.step && f.status == (int)RowState.Valid);
            if (isExist)
            {
                throw new BadRequestException(RequestEnum.ProductidExist);
            }
            _serinumCfgRepository.Insert(new SigerTrSerinumcfg
            {
                ProductID = requestAdd.productId,
                Rule = requestAdd.ruleType,
                Seq = requestAdd.step,
                ItemType = requestAdd.codeType,
                TypeFormat = requestAdd.codeFormat,
                Length=requestAdd.length,
                ItemValue = requestAdd.codeValue,
                status = (int)RowState.Valid,
                projectId = ProjectId
            });
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="requestUpdate"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Update([FromBody] RequestAddSerinumCfg requestUpdate)
        {
            var serinumEntity = _serinumCfgRepository.Get(requestUpdate.id);
            if (serinumEntity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
         
            serinumEntity.ProductID = requestUpdate.productId;
            serinumEntity.Rule = requestUpdate.ruleType;
            serinumEntity.Seq = requestUpdate.step;
            serinumEntity.ItemType = requestUpdate.codeType;
            serinumEntity.TypeFormat = requestUpdate.codeFormat;
            serinumEntity.Length = requestUpdate.length;
            serinumEntity.ItemValue = requestUpdate.codeValue;
            _serinumCfgRepository.Update(serinumEntity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="requestDel"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Delete([FromBody] RequestUpdateSeriumCfg requestDel)
        {
            var indata = _serinumCfgRepository.Get(f => f.id == requestDel.id);
            if (indata == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            _serinumCfgRepository.Delete(indata);
            if (_unitOfWork.Commit() == 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="runtype"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExportData(string productCode,int runtype)
        {
            var data = _serinumCfgRepository.GetPagedConfigList(productCode, runtype, 1, 999999);
            if (data.Data == null)
            {
                throw new BadRequestException(CommonEnum.NoData);
            }
            var datalist = new List<SerinumData>();
            data.Data.ToList().ForEach(da =>
            datalist.Add(Mapper<ResponseSerialNum, SerinumData>.Map(da)));
           
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            if (datalist.Any())
            {
                EpPlusExcelHelper<SerinumData> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<SerinumData>();
                    var temporaryFileName = $"二维码规则-{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(datalist, Path.Combine(rootDir, temporaryFileName));
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("Export failed,error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {

                    helper?.Dispose();
                }
            }
            throw new BadRequestException(CommonEnum.RecordNotFound);
        }

    }
}
