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

namespace Siger.ApiQMS.Controllers
{
    public class RepairSettingController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IQmsReworkSettingRepository _qmsReworkSetting;
        private readonly ISigerProjectProductRepository _sigerProjectProduct;
        public RepairSettingController(IUnitOfWork unitOfWork, IQmsReworkSettingRepository  qmsReworkSetting, ISigerProjectProductRepository sigerProjectProduct)
        {
            _unitOfWork = unitOfWork;
            _qmsReworkSetting = qmsReworkSetting;
            _sigerProjectProduct = sigerProjectProduct;
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Getlist([FromBody]RequestRepairlist param)
        {
            var data = _qmsReworkSetting.GetSettingPagedList(param.ProductId, param.MaterialId, param.PreRoute, param.Route, ProjectId, param.Page, param.PageSize);

            return new PagedLongTotalObjectResult(data.Data, data.Total, param.Page, param.PageSize);
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ExporExcel([FromBody]RequestRepairlist param)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            
            var data = _qmsReworkSetting.GetAllData(param.ProductId, param.MaterialId, param.PreRoute, param.Route, ProjectId);
            if (!data.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var dataList = new List<ReworkSetting>();
            foreach (var item in data)
            {
                dataList.Add(new ReworkSetting
                {
                  ProductCode=item.ProductCode,
                  ProductName=item.ProductName,
                  Material=item.MaterialName,
                  Pn=item.Pn,
                  MaterialSpec=item.MaterialSpec,
                  PreRoute=item.PreRouteDesc,
                  Route=item.RouteDesc
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<ReworkSetting> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<ReworkSetting>();
                    var temporaryFileName = $"返工工艺信息维护_InspectionStandardInfo_{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 Inspection Standard Info failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 添加设置
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody]RequestReworkSetting param)
        {
            if (param.ProductId==0 ||param.MaterialId == 0||param.PreRoute==0||param.Route==0)
                throw new BadRequestException(RequestEnum.ParameterMiss);
            var product = _sigerProjectProduct.Get(param.ProductId);
            if (product==null)
                throw new BadRequestException(RequestEnum.ProductNotFound);
            _qmsReworkSetting.Insert(new Middlelayer.QmsRepository.Entities.siger_qms_rework_setting {
                 Product_Id=product.id,
                 Material_Id=param.MaterialId,
                 Preroute_Id=param.PreRoute,
                 Route_Id=param.Route,
                 projectid=ProjectId,
                 DateTime=DateTime.Now,
                 status=(int)RowState.Valid
            });

            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        public IActionResult Modify([FromBody]RequestReworkSetting param)
        {
            var obj = _qmsReworkSetting.Get(param.Id);
            if (obj==null)
                throw new BadRequestException(RequestEnum.ProductNotFound);
            var product = _sigerProjectProduct.Get(param.ProductId);
            if (product == null)
                throw new BadRequestException(RequestEnum.ProductNotFound);
            obj.Product_Id = param.ProductId;
            obj.Material_Id = param.MaterialId;
            obj.Route_Id = param.Route;
            obj.Preroute_Id = param.PreRoute;
            obj.DateTime = DateTime.Now;
            _qmsReworkSetting.Update(obj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Delete([FromBody]RequestDeleteParameter req)
        {
            if (req.ids == null || !req.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var objs = _qmsReworkSetting.GetList(t => req.ids.Contains(t.id)).ToList();
            if (!objs.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            foreach (var obj in objs)
            {
                _qmsReworkSetting.Delete(obj);
            }
            
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        ///  返修到工序
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="route"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReworkRoute(int productId,int route)
        {
            var data = _qmsReworkSetting.GetReworkRoute(productId, route, ProjectId);

            return new ObjectResult(data);
        }
    }
}
