using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
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.Log;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Request;
using Siger.Middlelayer.TpmRepository.Response;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.ApiTPM.Controllers
{
    public class SparepartAuditController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISparepartAuditRepository _sparepartAuditRepository;
        private readonly ISparepartRepository _sparepartRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly ISigerProjectSparepartCodeRepository _codeRepository;
        public SparepartAuditController(IUnitOfWork unitOfWork, ISparepartAuditRepository sparepartAuditRepository,
            ISparepartRepository sparepartRepository, ISigerProjectMachineRepository machineRepository,
            ISigerProjectSparepartCodeRepository codeRepository)
        {
            _unitOfWork = unitOfWork;
            _sparepartAuditRepository = sparepartAuditRepository;
            _sparepartRepository = sparepartRepository;
            _machineRepository = machineRepository;
            _codeRepository = codeRepository;
        }

        /// <summary>
        /// 获取备件审核和备货，
        /// </summary>
        /// <param name="sectionId"></param>
        /// <param name="code"></param>
        /// <param name="status"></param>
        /// <param name="category">1：审核  2：备货</param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAuditPagedList(int sectionId, string code, int status, int category,int page = 1, int pagesize = 10)
        {
            var machineids = _machineRepository.GetAttributionMachineIds(sectionId, ProjectId).ToList();
            
            var data = _sparepartAuditRepository.GetAuditPagedList(sectionId, machineids, code, status, category, ProjectId, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }

        /// <summary>
        /// 备件替换
        /// </summary>
        /// <param name="sectionId"></param>
        /// <param name="code"></param>
        /// <param name="status"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReplcaePagedList(int sectionId, string code, int status, int page = 1, int pagesize = 10)
        {
            var machineids = new List<int>();
            if (sectionId > 0)
            {
                machineids = _machineRepository.GetAttributionMachineIds(sectionId, ProjectId).ToList();
            }
            var data = _sparepartAuditRepository.GetReplcaePagedList(sectionId, machineids, code, status, ProjectId, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }

        /// <summary>
        /// 备件维修
        /// </summary>
        /// <param name="code">工单号</param>
        /// <param name="sparepart">备件编号或名称</param>
        /// <param name="repair_category">维修类型</param>
        /// <param name="status">状态</param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <param name="toexcel"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetRepairPagedList(string code, string sparepart, int repair_category, int status,int page = 1, int pagesize = 10, int toexcel = 0)
        {
            var data = _sparepartAuditRepository.GetRepairPagedList(code, sparepart, repair_category, status, ProjectId, page, pagesize, toexcel);

            if (toexcel == 0)
            {
                return new PagedObjectResult(data.Data, data.Total, page, pagesize);
            }

            return ExportRepairs(data.Data);
        }

        private IActionResult ExportRepairs(IEnumerable<GetPagedAuditSparepartList> responses)
        {
            if (!responses.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var temporaryFileName = $"repairs_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);

            var helper = new EpPlusExcelHelper<MachineRepairs>(_machineRepository.GetProjectLanguage(ProjectId));
            try
            {
                var machineYields = new List<MachineRepairs>();
                var index = 1;
                foreach (var yield in responses)
                {
                    var machineYield = new MachineRepairs
                    {
                        No = index,
                        Code = yield.code,
                        SparepartCode = yield.spcode,
                        SparepartName = yield.spname,
                        Location = yield.location,
                        RepairCount = yield.repair_count,
                        RepairUpper = yield.repair_upper,
                        RepairType = yield.apply_state == 2 ? "自主维修": "委外维修",
                        RepairState = yield.repair_status == 0 ? "维修中" : "维修完成"
                    };
                    machineYields.Add(machineYield);
                    index++;
                }

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

        [HttpGet]
        public IActionResult GetSparepartApplyList(int id)
        {
            var list = _sparepartAuditRepository.GetAuditSparepartList(id);

            return new ObjectResult(list);
        }

        /// <summary>
        /// 获取替换件列表
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReplaceSparepartList(string ids)
        {
            var responses = new List<ResponseReplaceSparepart>();
            if (string.IsNullOrWhiteSpace(ids))
            {
                throw new BadRequestException(CommonEnum.Fail);
            }

            var sids = ids.Split(',');
            foreach (var sid in sids)
            {
                var audit = _sparepartAuditRepository.GetAuditDetail(sid.ToInt());
                if (audit == null)
                {
                    continue;
                }
                var sp = _sparepartRepository.Get(audit.sparepart_id );
                if (sp != null && sp.status == (int) RowState.Valid)
                {
                    var spart = new ResponseReplaceSparepart
                    {
                        id = sid.ToInt(),
                        sparepart_id = sp.id,
                        code = sp.code,
                        name = sp.title,
                        price = sp.price,
                        repair_upper = sp.repair_upperlimit == null ? "" : sp.repair_upperlimit.Value.ToStr()
                    };
                    //入库信息
                    var record = _codeRepository.Get(q => q.sparepart_id == sp.id && q.sparepart_code == audit.qrcode &&
                                                          q.status == (int) RowState.Valid);
                    if (record != null)
                    {
                        spart.record_code = record.sparepart_code;
                        spart.repair_count = record.repair_count;
                    }
                    responses.Add(spart);
                }
            }
            return new ObjectResult(responses);
        }

        /// <summary>
        /// 批量提交替换
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ReplaceSparepartList([FromBody]RequestReplaceSparepart request)
        {
            if (request.replace_spareparts == null || !request.replace_spareparts.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            if (_sparepartAuditRepository.UpdateAuditDetail(request, UserId) > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 审核备件
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SetSparepartApplyState([FromBody]RequestSetSparepartApplyState request)
        {
            if (string.IsNullOrWhiteSpace(request.ids))
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            var auditIds = request.ids.Split(',');
            //不能审核已审核过的记录
            var records = _sparepartAuditRepository.GetList(q => auditIds.Contains(q.id.ToString()) && q.approval_status > 1);
            if (records.Any())
            {
                throw new BadRequestException(RequestEnum.CannotApplyAgain);
            }
            foreach (var auditId in auditIds)
            {
                var audit = _sparepartAuditRepository.Get(q => q.id == auditId.ToInt());
                if (audit != null)
                {
                    //通过时，进入备货
                    if (request.state == 2)
                    {
                        audit.approval_status = 2;
                    }
                    else//未通过时 发送消息
                    {
                        audit.approval_status = 3;
                    }
                    _sparepartAuditRepository.Update(audit);
                }
            }

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

        /// <summary>
        /// 完成维修
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult FinishRepairs(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids))
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }
            if (_sparepartAuditRepository.UpdateAuditDetailById(ids) < 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }
    }
}