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

namespace Siger.ApiQMS.Controllers
{
    public class StandardPartsSnController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IStandardPartsSnRepository _standardPartsSnRepository;
        private readonly ISigerProjectProductRepository _productRepository;
        private readonly ISigerTrMaterialsRepository _materialsRepository;
        public StandardPartsSnController(IUnitOfWork unitOfWork, IStandardPartsSnRepository standardPartsSnRepository,
            ISigerProjectProductRepository productRepository, ISigerTrMaterialsRepository materialsRepository)
        {
            _unitOfWork = unitOfWork;
            _standardPartsSnRepository = standardPartsSnRepository;
            _productRepository = productRepository;
            _materialsRepository = materialsRepository;
        }
        [HttpGet]
        public IActionResult GetPageList(int productid, int materialid, string sn, int page, int pagesize, int toexcel)
        {
            var datas = _standardPartsSnRepository.GetPagedList(productid, materialid, sn, page, pagesize, ProjectId, toexcel);
            if(toexcel == 1)
            {
                return ExportExcel(datas.Data);
            }
            return new PagedObjectResult(datas.Data, datas.Total, page, pagesize);
        }

        private IActionResult ExportExcel(IEnumerable<ResponseStandardPartsSn> data)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            if (!data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var dataList = new List<StandardPartsSn>();
            int index = 1;
            foreach(var item in data)
            {
                dataList.Add(new StandardPartsSn
                {
                    No = index,
                    ProductCode = item.productcode,
                    ProductName=item.productname,
                    MaterialName=item.materialname,
                    MaterialPn=item.materialpn,
                    MaterialSpec=item.materialspec,
                    Sn = item.sn,
                    UpdateUser = item.updator,
                    UpdateTime = item.updatetime
                });
                index++;
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<StandardPartsSn> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<StandardPartsSn>();
                    var temporaryFileName = $"标准件二维码_StandardPartsSn_{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 Standard Parts SN failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Delete([FromBody]RequestDeleteParameter req)
        {
            if (req.ids == null || !req.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var entities = _standardPartsSnRepository.GetList(t => req.ids.Contains(t.id) && t.projectid == ProjectId && 
                t.status == (int)RowState.Valid).ToList();
            if(!entities.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            foreach(var entity in entities)
            {
                entity.status = (int)RowState.Invalid;
                entity.update_mid = UserId;
                entity.update_time = DateTime.Now;
                _standardPartsSnRepository.Update(entity);
            }            
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Update([FromBody]RequestUpdateStandardPartsSn req)
        {
            var entity = _standardPartsSnRepository.Get(t => t.id == req.id && t.projectid == ProjectId);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var product = _productRepository.Get(t => t.id == req.productid);
            if(product == null)
            {
                throw new BadRequestException(RequestEnum.ProductNotFound);
            }

            var material = _materialsRepository.Get(t => t.id == req.materialid);
            if (material == null)
            {
                throw new BadRequestException(RequestEnum.MaterialNotExist);
            }

            entity.productid = req.productid;
            entity.materialid = req.materialid;
            entity.update_mid = UserId;
            entity.update_time = DateTime.Now;
            _standardPartsSnRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Add([FromBody]RequestAddStandardPartsSn req)
        {            
            if (string.IsNullOrEmpty(req.sn))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            var exsit = _standardPartsSnRepository.Get(t => t.sn == req.sn && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if(exsit != null)
            {
                throw new BadRequestException(RequestEnum.DataExist);
            }

            var product = _productRepository.Get(t => t.id == req.productid);
            if (product == null)
            {
                throw new BadRequestException(RequestEnum.ProductNotFound);
            }

            var material = _materialsRepository.Get(t => t.id == req.materialid);
            if (material == null)
            {
                throw new BadRequestException(RequestEnum.MaterialNotExist);
            }
            var entity = new siger_qms_standard_parts_sn
            {
                productid = req.productid,
                materialid = req.materialid,
                sn = req.sn,
                projectid = ProjectId,
                update_mid = UserId,
                update_time = DateTime.Now
            };
            _standardPartsSnRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}