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

namespace Siger.ApiACC.Controllers
{
    public class AssemblyMaintenanceController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerTrAssemblyMaintenanceRepository _assemblyMaintenance;
        private readonly ISigerTrMaterialsRepository _materials;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSection;

        public AssemblyMaintenanceController(IUnitOfWork unitOfWork, ISigerTrAssemblyMaintenanceRepository assemblyMaintenance
            , ISigerTrMaterialsRepository materials, ISigerProjectLevelSectionRepository sigerProjectLevelSection)
        {
            _unitOfWork = unitOfWork;
            _assemblyMaintenance = assemblyMaintenance;
            _materials = materials;
            _sigerProjectLevelSection = sigerProjectLevelSection;
        }

        /// <summary>
        /// 获取分页 
        /// </summary>
        /// <param name="line"></param>
        /// <param name="station"></param>
        /// <param name="serial_number"></param>
        /// <param name="parent_serial"></param>
        /// <param name="child_serial"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetList(string line, string station, string serial_number, string parent_serial,
            string child_serial, int page = 1, int pagesize = 10)
        {

            var stationIds = _sigerProjectLevelSection.GetLevelSectionIds(station.ToInt(), ProjectId).ToList();

            var reponse = _assemblyMaintenance.GetPagedList(stationIds, serial_number,
                parent_serial, child_serial, ProjectId, page, pagesize);

            var data = new List<AssemblyMaintenance>();
            foreach (var item in reponse.Data)
            {
                var result = _sigerProjectLevelSection.GetParentLevelSections(item.station, ProjectId).OrderBy(o => o.id).ToList();
                data.Add(new AssemblyMaintenance
                {
                    child_serial = item.child_serial,
                    child_serial_value = item.child_serial_value,
                    serial_number = item.serial_number,
                    quantity = item.quantity,
                    serial_number_value = item.serial_number_value,
                    id = item.id,
                    station = item.station,
                    station_value = string.Join("/", result.Select(s => s.title).ToList()),
                    parent_serial = item.parent_serial,
                    parent_serial_value = item.parent_serial_value,
                    line = item.line,
                    line_value = item.line_value,
                    role = item.role,
                    transdatetime = item.transdatetime
                });
            }
            return new PagedObjectResult(data, reponse.Total, page, pagesize);
        }
        /// <summary>
        /// 修改记录
        /// </summary>
        /// <param name="maintenance"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody] RequestAddAssemblyMaintenance maintenance)
        {
            var isexist = _assemblyMaintenance.IsExist(t => t.serial_number == maintenance.serial_number &&
                                t.status == (int)RowState.Valid && t.projectId == ProjectId);
            if (isexist)
                throw new BadRequestException(RequestEnum.ProductidExist);

            var model1 = _materials.Get(t => t.pn == maintenance.parent_serial &&
                                t.status == (int)RowState.Valid && t.projectId == ProjectId);

            var model2 = _materials.Get(t => t.pn == maintenance.child_serial &&
                                t.status == (int)RowState.Valid && t.projectId == ProjectId);
            if (model1 == null || model2 == null)
                throw new BadRequestException(CommonEnum.DataNotNull);

            _assemblyMaintenance.Insert(new SigerTrAssemblyMaintenance
            {
                projectId = ProjectId,
                serial_number = maintenance.serial_number,
                station = maintenance.station,
                line = maintenance.line,
                parent_serial = maintenance.parent_serial.ToInt(),
                parent_serial_pn = model1.pn,
                child_serial = maintenance.child_serial.ToInt(),
                child_serial_pn = model2.pn,
                quantity = maintenance.quantity,
                role = maintenance.role,
                TransDateTime = DateTime.Now
            });
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult Modify([FromBody] RequestUpdateAssemblyMaintenance maintenance)
        {
            var newObj = _assemblyMaintenance.Get(maintenance.id);
            if (newObj == null)
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var model1 = _materials.Get(t => t.pn == maintenance.parent_serial &&
                    t.status == (int)RowState.Valid && t.projectId == ProjectId);

            var model2 = _materials.Get(t => t.pn == maintenance.child_serial &&
                                t.status == (int)RowState.Valid && t.projectId == ProjectId);
            if (model1 == null || model2 == null)
                throw new BadRequestException(CommonEnum.DataNotNull);

            if (_assemblyMaintenance.IsExist(t => t.serial_number == maintenance.serial_number && t.status == (int)RowState.Valid && t.projectId == ProjectId && t.id != newObj.id))
            {
                throw new BadRequestException(RequestEnum.DataExist);
            }

            newObj.serial_number = maintenance.serial_number;
            newObj.station = maintenance.station;
            newObj.line = maintenance.line;
            newObj.child_serial = maintenance.child_serial.ToInt();
            newObj.child_serial_pn = model2.pn;
            newObj.parent_serial = maintenance.parent_serial.ToInt();
            newObj.parent_serial_pn = model1.pn;
            newObj.quantity = maintenance.quantity;
            newObj.role = maintenance.role;
            _assemblyMaintenance.Update(newObj);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Delete(int id)
        {
            var entity = _assemblyMaintenance.Get(id);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            entity.status = (int)RowState.Invalid;
            _assemblyMaintenance.Update(entity);
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult ExportAll(string line, string station, string serial_number, string parent_serial, string child_serial)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            //int lineid = line.ToInt();
            //int stationid = station.ToInt();
            //var datas = _assemblyMaintenance.GetDataList(lineid, stationid, serial_number, parent_serial, child_serial, ProjectId).ToList();
            //if (!datas.Any())
            //{
            //    throw new BadRequestException(CommonEnum.RecordNotFound);
            //}
            var stationIds = _sigerProjectLevelSection.GetLevelSectionIds(station.ToInt(), ProjectId).ToList();
            var reponse = _assemblyMaintenance.GetPagedList(stationIds, serial_number,
                parent_serial, child_serial, ProjectId, 1, 9999999);
            if (!reponse.Data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var temporaryFileName = $"组装维护信息_AssemblyMaintenanceInfo_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);

            var helper = new EpPlusExcelHelper<AssemblyMaintenanceTemplate>();
            try
            {
                var mas = new List<AssemblyMaintenanceTemplate>();
                foreach (var pro in reponse.Data)
                {
                    var result = _sigerProjectLevelSection.GetParentLevelSections(pro.station, ProjectId).OrderBy(o => o.id).ToList();
                    var assemblyMaintenance = new AssemblyMaintenanceTemplate
                    {
                        linename = pro.line_value,
                        stationname = string.Join("/", result.Select(s => s.title).ToList()),
                        serial_number = pro.serial_number_value,
                        parent_serial = pro.parent_serial_value,
                        child_serial = pro.child_serial_value,
                        quantity = pro.quantity.ToStr(),
                        role = pro.role
                    };
                    mas.Add(assemblyMaintenance);
                }

                helper.GenerateExcel(mas, fileName);
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ExportAssemblyMaintenance failed, error: " + e.Message);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper.Dispose();
            }
        }
    }
}