using BBM.ChatGLM.Dtos;
using BBM.ChatGLM.User;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using OfficeOpenXml;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Identity;


namespace BBM.ChatGLM.Controllers
{
    [Route("User")]
    public class UserController : ChatGLMController, IUsersAppService
    {
        private readonly IUsersAppService _usersAppService;
        private readonly IConfiguration _configuration;
        public UserController(IUsersAppService usersAppService, IConfiguration configuration)
        {
            _usersAppService = usersAppService;
            _configuration = configuration;
        }

        [HttpPost("create")]
        public async Task<IdentityUserDto> CreateAsync([FromBody] UserCreateInput input)
        {
            return await _usersAppService.CreateAsync(input);
        }

        [HttpPost("delete")]
        public async Task<bool> DeleteAsync([FromBody] GuidIdInput input)
        {
            return await _usersAppService.DeleteAsync(input);
        }

        [HttpPost("update")]
        public async Task<IdentityUserDto> UpdateAsync([FromBody] UserUpdateInput input)
        {
            return await _usersAppService.UpdateAsync(input);
        }

        [HttpPost("reset")]
        public async Task<bool> ResetPasswordAsync([FromBody] UserResetPasswordInput input)
        {
            return await _usersAppService.ResetPasswordAsync(input);
        }

        [HttpPost("page")]
        public async Task<PagedResultDto<UserDto>> PageAsync([FromBody] UserPageInput input)
        {
            return await _usersAppService.PageAsync(input);
        }

        [HttpPost("roles")]
        public async Task<List<string>> GetRolesAsync()
        {
            return await _usersAppService.GetRolesAsync();
        }

        [HttpPost("token")]
        public async Task<string> GetTokenAsync()
        {
            return await _usersAppService.GetTokenAsync();
        }

        [HttpPost("excelFile")]
        public async Task<IActionResult> UploadExcel(IFormFile file)
        {
            /**
             *  操作步骤
             *      1、React中，使用antd的Upload组件来上传Excel表格数据，并且在上传之前需要将表格数据转换成FormData。
             *      2、在ASP.NET中，建立一个Controller用于接收上传的文件，并且使用[HttpPost]属性来指定使用POST方法接收请求。
             *      3、在Controller中，使用IFormFile接口来接收上传的Excel文件，然后使用EPPlus等工具来读取Excel文件数据
             *      4、将读取到的Excel数据进行处理，例如存储到数据库中或者进行数据分析等操作
             */

            Console.WriteLine("\n\n\n\n");
            Console.WriteLine("react + antd 访问 \t");
            Console.WriteLine("comeback welcome UploadExcel(IFormFile excel)");


            var failNum = 0;                                                                                                    //添加失败的人数变量

            if (file == null || file.Length == 0)
                return BadRequest("Excel文件为空");

            var fileName = file.FileName;


            Console.WriteLine(fileName);
            var filePath = Path.Combine("C:\\Excel", fileName);
            Console.WriteLine(filePath);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            using (var package = new ExcelPackage(new FileInfo(filePath)))
            {
                var worksheet = package.Workbook.Worksheets["sheet1"];                                                          //reader space Name 可能要更灵活-通过指定的空间名称
                var totalRows = worksheet.Dimension.Rows;
                var row = 2;                                                                                                    //First line is UserName And Phone

                while (row <= totalRows)
                {
                    // 处理Excel数据
                    var userName    = worksheet.Cells[row, 1].Value?.ToString() ?? "";
                    var phoneNumber = worksheet.Cells[row, 2].Value?.ToString() ?? "";
                    var password = "Zs"+ phoneNumber.Substring(phoneNumber.Length - 6);                                         //1、可能需要加密操作... 2、以及判断账户是否在数据库重复

                    UserCreateInput userInput = new UserCreateInput();
                    userInput.UserName = userName;
                    userInput.Password = password;
                    userInput.Name = "";
                    userInput.Role = "";
                    userInput.IsActive = false;

                    failNum++;

                    //try
                    //{
                    //    //添加用户方法
                    //}
                    //catch (Exception ex)
                    //{
                    //    failNum ++;                                                                                           //账户添加 失败一次 数量+1
                    //    Console.WriteLine(ex.Message);
                    //    continue;
                    //}


                    row++;
                }
                package.Dispose();
            }

            return Ok(failNum==0?"用户新增成功":failNum);

            //return Ok("Excel文件上传成功");
        }

    }
}
