using System.Security.Policy;
using System.Web;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using PTCMS.API.Domain.Entities;
using PTCMS.API.Domain.Repositories;
using PTCMS.API.Infrastructure.Dtos;

namespace PTCMS.API.Controllers
{
    /// <summary>
    /// 证书查询服务接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CertificateController : ControllerBase
    {
        private readonly ICertificateRepository _certificateRepository;
        private readonly IHostEnvironment _hostEnvironment;

        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="certificateRepository"></param>
        /// <param name="hostEnvironment"></param>
        public CertificateController(ICertificateRepository certificateRepository, IHostEnvironment hostEnvironment)
        {
            _certificateRepository = certificateRepository;
            _hostEnvironment = hostEnvironment;
        }

        /// <summary>
        /// 根据姓名+身份证号或者姓名+证书编码进行查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetCertificateAsync([FromBody] CertificateSearchDto input)
        {
            try
            {
                var list = new List<Certificate>();
                var data = await _certificateRepository.GetCertificateAsync(input);

                if (data != null)
                {
                    list.Add(data);
                }

                return Ok(list);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ShowImage(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
                return BadRequest("文件名无效");

            url = HttpUtility.HtmlDecode(url);

            var ext = Path.GetExtension(url);
            if (ext == ".jpg" || ext == ".png")
            {
                var path = Path.Combine(_hostEnvironment.ContentRootPath, "Images");

                try
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    using (var sw = new FileStream(Path.Combine(path, url), FileMode.Open))
                    {
                        var bytes = new byte[sw.Length];
                        sw.Read(bytes, 0, bytes.Length);
                        sw.Close();
                        return new FileContentResult(bytes, "image/jpeg");
                    }
                }
                catch (Exception ex)
                {
                    return BadRequest(ex.Message);
                }
            };

            return BadRequest("目前只支持jpg和png格式");
        }
    }
}