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

namespace Siger.ApiQMS.Controllers
{
    public class ReworkReferenceController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IQmsReworkReferenceRepository _qmsReworkReference;

        public ReworkReferenceController(IUnitOfWork unitOfWork, IQmsReworkReferenceRepository qmsReworkReference)
        {
            _unitOfWork = unitOfWork;
            _qmsReworkReference = qmsReworkReference;
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Getlist(int page ,int pageSize, string keyword)
        {
            var data = _qmsReworkReference.GetReworkReasonPagedList(keyword, ProjectId, page, pageSize);
            return new PagedLongTotalObjectResult(data.Data, data.Total, page, pageSize);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExportExcel(string keyword)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            
            var dataPage = _qmsReworkReference.GetReworkReasonPagedList(keyword, ProjectId, 1, 999999);
            var data = dataPage.Data;
            if (!data.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);
            var dataList = new List<ImportReworkReason>();
            foreach (var item in data)
            {
                dataList.Add(new ImportReworkReason
                {
                    No=item.id,
                    Type=item.type,
                    Name=item.referDesc,
                    Reason=item.reason
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<ImportReworkReason> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<ImportReworkReason>();
                    var temporaryFileName = $"返工返修原因_InspectionStandardInfo_{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);

        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="reference"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody]RequestReworkReference reference)
        {
            if (_qmsReworkReference.IsExist(f=>f.projectid==ProjectId && f.Type==reference.type && f.ReferType==reference.refertype && f.Remark==reference.reason))
                throw new BadRequestException(CommonEnum.RecordExits);

            _qmsReworkReference.Insert(new siger_qms_rework_reference
            {
                 Type=reference.type,
                 ReferType =reference.refertype,
                 projectid=ProjectId,
                 Remark=reference.reason,
                 DateTime=DateTime.Now,
                 status=(int)RowState.Valid
            });

            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="reference"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Modify([FromBody]RequestReworkReference reference)
        {

            var obj = _qmsReworkReference.Get(f => f.id == reference.id);
            if (obj==null)
                throw new BadRequestException(CommonEnum.RecordNotFound);
            obj.Remark = reference.reason;
            obj.Type = reference.type;
            obj.ReferType = reference.refertype;
            obj.DateTime = DateTime.Now;

            _qmsReworkReference.Update(obj);

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

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Del([FromBody]RequestIds request)
        {
            if (!request.ids.Any())
                throw new BadRequestException(RequestEnum.ParameterMiss);
            foreach (var id in request.ids)
            {
                var obj = _qmsReworkReference.Get(f => f.id == id);
                if (obj == null)
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                _qmsReworkReference.Delete(obj);
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">1.返工  2.报废</param>
        /// <param name="referType"> 类型分类</param>
        /// <returns></returns>
        [HttpGet]
        public  IActionResult GetItem(int type,int referType)
        {
            var data = _qmsReworkReference.GetList(f => f.projectid == ProjectId && f.Type == type && f.ReferType == referType);
            return new ObjectResult(data);
        }
    }
}
