using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.API.SINO.Order.Model;
using XYY.Core.Standard.Mvc;
using XYY.Service.Standard.UserService;
using XYY.Service.Standard.UserService.Model;
using XYY.Authentication.Standard;

namespace XYY.API.SINO.Order.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]

    public class AuthController : ControllerBase
    {
        IUserService _userService;
        public AuthController(IUserService userService)
        {
            _userService = userService;
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<UserLoginResult> Login([FromBody] LoginParam param)
        {
            var user = await _userService.LoginV2(param.username, param.password);
            if (user != null)
            {
                if (user.IsSuccess)
                {

                    string roleNames = string.Empty;
                    if (user.RoleNames != null && user.RoleNames.Length > 0)
                    {
                        roleNames = string.Join(',', user.RoleNames);
                    }


                    return new UserLoginResult { Token = user.Token, UserNickName = user.Name, Roles = roleNames, Success = true };
                }

                else
                    throw new Exception(user.ErrorMessage);
            }
            else
                throw new Exception("登陆失败");
        }

        public RoleInfoResult GetInfo()
        {
            var userInfo = User.GetUserContent();
            var roleNames = userInfo.Roles;
            var userName = userInfo.NiceName;
            return new RoleInfoResult { Name = userName, Roles = roleNames };
        }
    }
}
