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

namespace Siger.ApiACC.Controllers
{
    public class FixtureToolsProductController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IAutomationFixtureToolsCategoryRepository _toolsCategoryRepository;
        private readonly IAutomationFixtureToolsRepository _toolsRepository;
        private readonly IAutomationFixtureToolsProductRepository _toolsProductRepository;
        private readonly ISigerProjectProductRepository _productRepository;

        public FixtureToolsProductController(IUnitOfWork unitOfWork, IAutomationFixtureToolsCategoryRepository toolsCategoryRepository, 
            IAutomationFixtureToolsRepository toolsRepository, IAutomationFixtureToolsProductRepository toolsProductRepository,
            ISigerProjectProductRepository productRepository)
        {
            _unitOfWork = unitOfWork;
            _toolsCategoryRepository = toolsCategoryRepository;
            _toolsRepository = toolsRepository;
            _toolsProductRepository = toolsProductRepository;
            _productRepository = productRepository;
        }

        [HttpGet]
        public IActionResult GetPageList(string category, string tool, string product, int page, int pagesize, string toexcel)
        {
            var data = _toolsProductRepository.GetPagedList(category.ToInt(), tool.ToInt(), product.ToInt(), ProjectId, page, pagesize, toexcel);
            var categorys = _toolsCategoryRepository.GetList(q => q.projectId == ProjectId && q.status == (int)RowState.Valid).ToList();
            var list = new List<ResponseAumationFixtureToolsProduct>();
            foreach(var item in data.Data)
            {
                var cates = GetParentCategoryList(item.cate_guid, categorys);
                var cateIds = cates.Select(q => q.id).ToList();
                cateIds.Reverse();
                item.categoryids = cateIds;
                list.Add(item);
            }
            if(toexcel.ToInt() == 1)
            {
                return ExportExcel(list);
            }
            return new PagedObjectResult(list, data.Total, page, pagesize);
        }

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

            if (!data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var dataList = new List<FixtureToolsProductList>();

            foreach (var item in data)
            {
                dataList.Add(new FixtureToolsProductList
                {
                    Category = item.categoryname,
                    PartNumber = item.partnumber,
                    FixtureTool = item.fixturetool,
                    Specfication = item.specfication,
                    Product = item.productname,
                    ProductCode = item.productcode,
                    Remark = item.remark,
                    Updator = item.updator,
                    UpdateTime = item.updatetime
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<FixtureToolsProductList> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<FixtureToolsProductList>();
                    var temporaryFileName = $"工装对应产品_FixtureToolsProductData_{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 Fixture Tools Product Data failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        private IEnumerable<siger_automation_fixture_tools_category> GetParentCategoryList(string parentId, List<siger_automation_fixture_tools_category> sections)
        {
            var query = from c in sections where c.guid == parentId select c;

            return query.ToList().Concat(query.ToList().SelectMany(t => GetParentCategoryList(t.parent, sections)));
        }

        [HttpPost]
        public IActionResult Add([FromBody]RequestAddFixtureToolsProduct req)
        {
            if(string.IsNullOrEmpty(req.fixturetoolid) || string.IsNullOrEmpty(req.productid))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var fixtureTool = _toolsRepository.Get(q => q.projectId == ProjectId && q.id == req.fixturetoolid.ToInt());
            if(fixtureTool == null)
            {
                throw new BadRequestException(RequestEnum.FixtureToolNotFound);
            }
            var product = _productRepository.Get(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.id == req.productid.ToInt());
            if(product == null)
            {
                throw new BadRequestException(RequestEnum.ProductNotFound);
            }
            var data = _toolsProductRepository.Get(q => q.projectId == ProjectId && q.status == (int)RowState.Valid && (q.fixturetools == fixtureTool.guid ||
                q.productid == req.productid.ToInt()));
            if (data != null)
            {
                throw new BadRequestException(RequestEnum.DataExist);
            }

            var entity = new siger_automation_fixture_tools_product
            {
                guid = Guid.NewGuid().ToString(),
                fixturetools = fixtureTool.guid,
                remark = req.remark,
                productid = req.productid.ToInt(),
                productcode = product.code,
                projectId = ProjectId,
                createtime = DateTime.Now,
                updatetime = DateTime.Now,
                creator = UserId,
                updator = UserId,
                attachment = req.fileurl,
                filename = req.filename
            };
            _toolsProductRepository.Insert(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        [HttpPost]
        public IActionResult Update([FromBody]RequestUpdateFixtureToolsProduct req)
        {
            if (string.IsNullOrEmpty(req.fixturetoolid) || string.IsNullOrEmpty(req.productid))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var entity = _toolsProductRepository.Get(q => q.projectId == ProjectId && q.status == (int)RowState.Valid && q.id == req.id);
            if(entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var fixtureTool = _toolsRepository.Get(q => q.projectId == ProjectId && q.id == req.fixturetoolid.ToInt());
            if (fixtureTool == null)
            {
                throw new BadRequestException(RequestEnum.FixtureToolNotFound);
            }
            var product = _productRepository.Get(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.id == req.productid.ToInt());
            if (product == null)
            {
                throw new BadRequestException(RequestEnum.ProductNotFound);
            }
            var data = _toolsProductRepository.Get(q => q.projectId == ProjectId && q.status == (int)RowState.Valid && (q.fixturetools == fixtureTool.guid ||
                q.productid == req.productid.ToInt()) && q.id != req.id);
            if (data != null)
            {
                throw new BadRequestException(RequestEnum.DataExist);
            }

            entity.fixturetools = fixtureTool.guid;
            entity.remark = req.remark;
            entity.productid = req.productid.ToInt();
            entity.productcode = product.code;
            entity.updatetime = DateTime.Now;
            entity.updator = UserId;
            entity.filename = req.filename;
            entity.attachment = req.fileurl;
            _toolsProductRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        [HttpGet]
        public IActionResult Delete(int id)
        {
            var entity = _toolsProductRepository.Get(q => q.projectId == ProjectId && q.status == (int)RowState.Valid && q.id == id);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

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

        [HttpPost]
        public IActionResult Deletes([FromBody]RequestDeleteRange req)
        {
            if (req.ids == null || !req.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var entities = _toolsProductRepository.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;
                _toolsProductRepository.Update(entity);
            }

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