using CsvHelper;
using CsvHelper.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using MS.Component.Jwt.UserClaim;
using MS.Entities.AccountingService_Models;
using MS.Entities.Core;
using MS.Models;
using MS.Models.ViewModel;
using MS.Services;
using MS.WebCore.Core;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using Renci.SshNet.Messages;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace MS.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly IAccountService _accountService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public AccountController(IAccountService accountService, IHttpContextAccessor httpContextAccessor)
        {
            _accountService = accountService;
            _httpContextAccessor = httpContextAccessor;
        }
        //[AllowAnonymous]
        [Route("sadas")]
        [HttpPost]
        public async Task<ExecuteResult> Post()
        {
            return null;
        }
        [HttpPost]
        //[AllowAnonymous]
        public async Task<ExecuteResult<UserData>> Login(LoginViewModel viewModel)
        {
            return await _accountService.Login(viewModel);
        }
        [Route("syncFromVersion")]
        [HttpPost]
        [AllowAnonymous]
        public async Task<ExecuteResult<UserData>> syncFromVersion(long versionNo, bool excludingCurrentBu)
        {
            var context = _httpContextAccessor.HttpContext;
            var allHeaders = context.Request.Headers; // 获取所有请求头
            var specificHeader = context.Request.Headers["DeviceSN"].ToString(); // 获取指定请求头

            return await _accountService.syncFromVersion(versionNo, excludingCurrentBu, specificHeader);
        }
        [Route("AddEmployeeCardMonthlySummaryToRedisNumberAsync")]
        [HttpPost]
        [AllowAnonymous]
        public async Task<bool> AddEmployeeCardMonthlySummaryToRedisNumberAsync(string buid, string date, string Car, int number)
        {
            DateTime dateTime = DateTime.Parse(date);
            for (int i = 0; i < number; i++)
            {
                dateTime = dateTime.AddMonths(i);
                string time = dateTime.ToString("yyyy-MM-dd");
                await _accountService.AddEmployeeCardMonthlySummaryToRedisAsync(buid, time, Car);
            }
            return true;
        }
        [Route("AddEmployeeCardMonthlySummaryToRedisAsync")]
        [HttpPost]
        [AllowAnonymous]
        public async Task<bool> AddEmployeeCardMonthlySummaryToRedisAsync(string buid, string date, string Car, int number)
        {
            Guid sss = Guid.NewGuid();
            await _accountService.AddEmployeeCardMonthlySummaryToRedisAsync(buid, date, Car);
            return true;
        }
        [Route("AddEmployeeRedisAsync")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<bool> AddEmployeeRedisAsync(string buid, string date, string Car, int number)
        {
            _accountService.Getdate(buid, date, Car);
            return true;
        }
        [Route("addredis")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<bool> addredis(string buid)
        {
            _accountService.addredis(buid);

            return true;
        }
        [Route("ClearhashValues")]
        [HttpPost]
        [AllowAnonymous]
        public async Task<bool> ClearhashValues(string key)
        {
            await _accountService.ClearhashValues(key);
            return true;
        }
        /// <summary>
        /// 同步员工卡和个人卡汇总
        /// </summary>
        /// <returns></returns>
        [Route("AddCarRedisAsync")]
        [HttpPost]
        [AllowAnonymous]
        public async Task<bool> AddCarRedisAsync()
        {
            await _accountService.AddCarRedisAsync();
            return true;
        }

        /// <summary>
        /// 获取交易信息
        /// </summary>
        /// <returns></returns>
        [Route("GetTransactioninfo")]
        [HttpPost]
        [AllowAnonymous]
        public async Task<ExecuteResult> GetTransactioninfo(string trx_sequence_no,
            string nozzle_no,
            string business_unit_info_id,
            string transaction_time)
        {
            return await _accountService.GetTransactioninfo(trx_sequence_no, nozzle_no, business_unit_info_id, transaction_time);
        }
        [Route("GetBusinessUnits")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<ExecuteResult> GetBusinessUnits(string guid)
        {
            return await _accountService.GetBusinessUnits(guid);
        }
        /// <summary>
        /// 实体卡开票余额清零提醒
        /// </summary>
        /// <returns></returns>
        [Route("CardInvoiceClearWarn")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<ExecuteResult> CardInvoiceClearWarnAsync()
        {
            return await _accountService.CardInvoiceClearWarnAsync();
        }
        /// <summary>
        /// 实体卡开票余额清零提醒
        /// </summary>
        /// <returns></returns>
        [Route("CardInvoiceClear")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<ExecuteResult> CardInvoiceClearAsync()
        {
            return await _accountService.CardInvoiceClearAsync();
        }
        /// <summary>
        /// 电子账户开票余额清零
        /// </summary>
        /// <returns></returns>
        [Route("ElectronicAccountInvoiceClear")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<ExecuteResult> ElectronicAccountInvoiceClearAsync()
        {
            return await _accountService.ElectronicAccountInvoiceClearAsync();
        }
        /// <summary>
        /// 短信发送
        /// </summary>
        /// <returns></returns>
        [Route("CardSendSms")]
        [HttpGet]
        [AllowAnonymous]
        public async Task SendSms()
        {
            await _accountService.SendSms();
        }
        /// <summary>
        /// 短信发送
        /// </summary>
        /// <returns></returns>
        [Route("SendSMS")]
        [HttpPost]
        [AllowAnonymous]
        public async Task SendSms(IFuelSendSMSDto fuelSendSMSDto)
        {

        }
        [HttpPost("upload")]
        public async Task<IActionResult> Upload(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("No file uploaded.");

            if (!Path.GetExtension(file.FileName).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                return BadRequest("Only .csv files are allowed.");

            var people = new List<UploadTrx>();

            using (var reader = new StreamReader(file.OpenReadStream()))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                var config = new CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    HasHeaderRecord = true, // 指定第一行是标题行
                    MissingFieldFound = null, // 处理缺失字段
                    BadDataFound = null // 处理错误数据
                };
                people = csv.GetRecords<UploadTrx>().ToList();
            }
            await _accountService.Upload(people);
            // 返回读取的数据
            return Ok();
        }
        [Route("userIdAndName")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> userIdAndName(string Buid, int page = 1, int pageSize = 1000)
        {
            var data = await _accountService.userIdAndName(Buid, page, pageSize);
            return Ok(new { statusCode = "OK", message = "OK", result = data });
        }
        [Route("userIdAndNameRedis")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> userIdAndNameRedis(string Buid, int page = 1, int pageSize = 1000)
        {
            var data = await _accountService.userIdAndNameRedis(Buid, page, pageSize);
            return Ok(new { statusCode = "OK", message = "OK", result = data });
        }
        [Route("GetUserDevice")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetUserDevice(string UserID)
        {
            var data = await _accountService.GetUserDevice(UserID);
            var response = new
            {
                statusCode = "OK",
                message = "OK",
                result = data
            };
            var settings = new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver() 
            };
            string jsonResponse = JsonConvert.SerializeObject(response, Formatting.None, settings);
            return Content(jsonResponse, "application/json");
        }
        [Route("GetUserDevice_bool")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetUserDevice_bool(string UserID,string Sn)
        {
            var data = await _accountService.GetUserDevice_bool(UserID, Sn);
            return Ok(new { statusCode = "OK", message = "OK", result = data});
        }

    }
}