using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Performance.DtoModels;
using Performance.Services;
using Performance.Services.OnlineExcel;

namespace Performance.Api.Controllers
{
    [Route("api/online/excel")]
    [ApiController]
    public class OnlineExcelController : Controller
    {
        private readonly AllotService _allotService;
        private readonly OnlineExcelService _excelService;

        public OnlineExcelController(
            AllotService allotService,
            OnlineExcelService excelService)
        {
            _allotService = allotService;
            _excelService = excelService;
        }

        [Route("sheet/name")]
        [HttpGet]
        [AllowAnonymous]
        public ApiResponse SheetName(int allotId)
        {
            var allot = _allotService.GetAllot(allotId);
            if (allot == null)
                return new ApiResponse(ResponseType.Fail, "当前绩效信息无效", "当前绩效信息无效");

            var sheetNames = _excelService.GetExcelSheetName(allot);
            if (sheetNames == null || sheetNames.Count == 0)
                return new ApiResponse(ResponseType.Fail, "未能找到有效[SHEET]", "未能找到有效[SHEET]");

            return new ApiResponse(ResponseType.OK, sheetNames);
        }


        [Route("sheet/data")]
        [HttpGet]
        [AllowAnonymous]
        public ApiResponse SheetName(int allotId, string sheetName)
        {
            var allot = _allotService.GetAllot(allotId);
            if (allot == null)
                return new ApiResponse(ResponseType.Fail, "当前绩效信息无效", "当前绩效信息无效");

            var s = _excelService.ReadSheet(allot, sheetName);

            return new ApiResponse(ResponseType.OK, "", JsonConvert.SerializeObject(s, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
        }

        [Route("sheet/chanage/{allotId}")]
        [HttpPost]
        [AllowAnonymous]
        public ApiResponse WriteSheet(int allotId, [FromBody] EpChanage chanage)
        {
            var allot = _allotService.GetAllot(allotId);
            if (allot == null)
                return new ApiResponse(ResponseType.Fail, "当前绩效信息无效", "当前绩效信息无效");

            _excelService.WriteSheet(allot, chanage);

            return new ApiResponse(ResponseType.OK);
        }
    }
}
