using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Core.Standard.AliYun;
using XYY.Core.Standard.Mvc;
using XYY.Service.Standard.KnowledgeBase;

namespace XYY.Api.KnowledgeBase.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class FileController : ControllerBase
    {
        IAliYunPostFileSerivce _aliYunPostFileSerivce;
        IKnowledgeSevice knowledgeSevice;

        public FileController(IKnowledgeSevice knowledgeSevice, IAliYunPostFileSerivce aliYunPostFileSerivce)
        {
            this.knowledgeSevice = knowledgeSevice;
            _aliYunPostFileSerivce = aliYunPostFileSerivce;
        }

        [HttpDelete]
        public async Task Delete(int Id)
        {
            await knowledgeSevice.Delete(Id);
        }

        [HttpPut]
        public async Task Put([FromBody] XYY.Service.Standard.KnowledgeBase.Model.KnowledgeBase model)
        {
            await knowledgeSevice.UpdateFile(model);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="base">上传参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiJsonModel> Post([FromQuery] string dict)
        {
            var filelist = (await Request.ReadFormAsync()).Files;

            if (filelist != null && filelist.Count > 0)
            {
                var file = filelist[0];
                 
               
                string fielName = Guid.NewGuid() + file.FileName.Substring(file.FileName.LastIndexOf('.'));
                string url = _aliYunPostFileSerivce.PostHttpFile(file.OpenReadStream(), fielName);
                var model = new XYY.Service.Standard.KnowledgeBase.Model.KnowledgeBase
                {
                    Url = url,
                    FileName = file.FileName.Length > 0 ? file.FileName.Substring(0, file.FileName.IndexOf('.')) : file.FileName,
                    DictName = dict
                };
                await this.knowledgeSevice.UpdateFile(model); 
                return ApiJsonModel.OK();
            }
            else
            {
                return ApiJsonModel.Error("必须上传一个文件");
            }
        }

    }
}
