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

namespace Siger.ApiTools.Controllers
{
    public class ToolSupplierController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        readonly ISigerProjectToolRepository _sigerProjectToolRepository;
        readonly ISigerProjectToolCutterLocationTrueRepository _sigerProjectToolCutterLocationTrueRepository;

        public ToolSupplierController(IUnitOfWork unitOfWork,ISigerProjectToolRepository sigerProjectToolRepository, ISigerProjectToolCutterLocationTrueRepository sigerProjectToolCutterLocationTrueRepository)
        {
            _unitOfWork = unitOfWork;
            _sigerProjectToolRepository = sigerProjectToolRepository;
            _sigerProjectToolCutterLocationTrueRepository = sigerProjectToolCutterLocationTrueRepository;
        }

        [HttpPost]
        public IActionResult GetList([FromBody]RequestGetToolSupplierList request)
        {
            var response = new List<ResponseSigerProjectTool>();

            var list = _sigerProjectToolRepository.GetList(ProjectId, request.name, request.brand,
                request.supplier, request.start, request.end, null, request.page, request.pagesize, out var total);
            foreach (var sigerProjectTool in list)
            {
                var tool = Mapper<SigerProjectTool, ResponseSigerProjectTool>.Map(sigerProjectTool);
                tool.unitprice = sigerProjectTool.unitprice.HasValue ? sigerProjectTool.unitprice.Value.ToString(CultureInfo.InvariantCulture) : "";
                response.Add(tool);
            }
            return new PagedObjectResult(response, total, request.page, request.pagesize);
        }

        [HttpGet]
        public ResponseDropDownList GetDropDownList()
        {
            return _sigerProjectToolRepository.GetDropDownList(ProjectId);
        }

        [HttpGet]
        public ResponseDropDownList GetDropDownList2(string toolname)
        {
            return _sigerProjectToolRepository.GetDropDownList(ProjectId, toolname.ToValidParameter());
        }

        [HttpGet]
        public ResponseDropDownList GetDropDownList3(string toolname, string brand)
        {
            return _sigerProjectToolRepository.GetDropDownList(ProjectId, toolname.ToValidParameter(), brand.ToValidParameter());
        }

        [HttpGet]
        public IActionResult GetToolSupplierDropDownList()
        {
            var data = _sigerProjectToolRepository.GetToolSupplierDropDownList(ProjectId);
            return new ObjectResult(data);
        }

        [HttpGet]
        public IActionResult GetToolTypes(int sectionId)
        {
            var data = _sigerProjectToolCutterLocationTrueRepository.GetToolTypes(ProjectId, sectionId);
            
            return new ObjectResult(data);
        }

        /// <summary>
        /// 添加刀具信息
        /// </summary>
        /// <param name="requestSupplier"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddToolSupplier([FromBody]RequestSupplier requestSupplier)
        {
            var entity = _sigerProjectToolRepository.Get(q =>
                q.drawingcode == requestSupplier.DrawingCode && q.status == (int) RowState.Valid);
            if (entity != null)
            {
                throw new BadRequestException(RequestEnum.DrawingCodeHasExist);
            }
            var record = new SigerProjectTool
            {
                projectid = ProjectId,
                name = requestSupplier.Name,
                spec = requestSupplier.Spec,
                brand = requestSupplier.Brand,
                material = requestSupplier.Material,
                hardness = requestSupplier.Hardness,
                drawingcode = requestSupplier.DrawingCode,
                supplier = requestSupplier.Supplier,
                suppliercode = requestSupplier.SupplierCode,
                supplierimg = requestSupplier.Supplierimg,
                unitprice = requestSupplier.Unitprice.ToFloat(),
                description = requestSupplier.Description,
                status = (int)RowState.Valid
            };
            _sigerProjectToolRepository.Insert(record);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetToolSupplierItem(int id)
        {
            var record = _sigerProjectToolRepository.Get(id);
            if (record == null || record.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return new ObjectResult(record);
        }

        /// <summary>
        /// 编辑刀具信息
        /// </summary>
        /// <param name="requestSupplier"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult EditToolSupplier([FromBody]RequestSupplier requestSupplier)
        {
            var entity = _sigerProjectToolRepository.Get(q =>
                q.drawingcode == requestSupplier.DrawingCode && q.status == (int)RowState.Valid && q.id != requestSupplier.ID);
            if (entity != null)
            {
                throw new BadRequestException(RequestEnum.DrawingCodeHasExist);
            }
            var record = _sigerProjectToolRepository.Get(requestSupplier.ID);
            if (record == null || record.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            record.name = requestSupplier.Name;
            record.spec = requestSupplier.Spec;
            record.brand = requestSupplier.Brand;
            record.material = requestSupplier.Material;
            record.hardness = requestSupplier.Hardness;
            record.drawingcode = requestSupplier.DrawingCode;
            record.supplier = requestSupplier.Supplier;
            record.suppliercode = requestSupplier.SupplierCode;
            record.supplierimg = requestSupplier.Supplierimg;
            record.unitprice = requestSupplier.Unitprice.ToFloat();
            record.description = requestSupplier.Description;
            _sigerProjectToolRepository.Update(record);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);

        }
        /// <summary>
        /// 删除刀具 信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DeleteToolSupplier(int id)
        {
            var record = _sigerProjectToolRepository.Get(id);
            if (record == null || record.status != (int) RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            record.status = (int) RowState.Invalid;
            _sigerProjectToolRepository.Update(record);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 导出刀具供应商
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Export(string name, string brand, string supplier, double? start, double? end)
        {
            if (null != start && null != end && start < end)
            {
                throw new BadRequestException(ToolEnum.PriceRangeError);
            }
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var data = _sigerProjectToolRepository.GetList(ProjectId, name, brand, supplier, start, end, 1, 0, 0, out var total);
            var sigerProjectTools = data.ToList();
            if (!sigerProjectTools.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var exportData = new List<ToolSupplierList>();
            var index = 1;
            foreach (var item in sigerProjectTools)
            {
                var toolItem = new ToolSupplierList
                {
                    No = index,
                    Name = item.name,
                    DrawingCode = item.drawingcode,
                    Spec = item.spec,
                    Brand = item.brand,
                    Material = item.material,
                    Hardness = string.IsNullOrEmpty(item.hardness) ? "NA" : item.hardness,
                    Supplier = item.supplier,
                    SupplierCode = item.suppliercode,
                    UnitPrice = !item.unitprice.HasValue ? "" : item.unitprice.ToString(),
                    Description = item.description
                };
                index++;
                exportData.Add(toolItem);
            }

            EpPlusExcelHelper<ToolSupplierList> helper = null;
            try
            {
                helper = new EpPlusExcelHelper<ToolSupplierList>();
                var temporaryFileName = $"toolsupplier_{DateTime.Now:yyyyMMddHHmmss}刀具供应商信息.xlsx";
                helper.GenerateExcel(exportData, Path.Combine(rootDir, temporaryFileName));
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("Export tool supplier failed, error:" + e);
                throw new BadRequestException(CommonEnum.SystemExcetion);
            }
            finally
            {
                helper?.Dispose();
            }
        }

    }

}
