
using New_College.IServices;
using New_College.Model.Models;
using New_College.Services.BASE;
using New_College.IRepository.Base;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.IO;
using System.Collections.Generic;
using New_College.Model.ViewModels;
using New_College.Model;
using System.Linq;

namespace New_College.Services
{
    public class D_UniversityServices : BaseServices<D_University>, ID_UniversityServices
    {
        private readonly IBaseRepository<D_University> _dal;
        public D_UniversityServices(IBaseRepository<D_University> dal)
        {
            this._dal = dal;
            base.BaseDal = dal;
        }

        /// <summary>
        /// 下载图片
        /// </summary>
        /// <returns></returns>
        public async Task<bool> SaveImg()
        {
            var info = await _dal.QuerySql("SELECT Logo FROM `D_University`");
            foreach (var item in info)
            {
                var url = item.Logo;
                if (!string.IsNullOrWhiteSpace(url))
                {
                    var name = item.Logo.Substring(item.Logo.LastIndexOf("/"));
                    if (!System.IO.File.Exists("D:\\Ashuju\\schoologo\\" + name + ""))
                    {
                        WebClient my = new WebClient();
                        byte[] mybyte;
                        mybyte = my.DownloadData(url);
                        MemoryStream ms = new MemoryStream(mybyte);
                        System.Drawing.Image img;
                        img = System.Drawing.Image.FromStream(ms);
                        img.Save("D:\\Ashuju\\schoologo\\" + name + "");   //保存
                    }
                }
            }
            return true;
        }


        /// <summary>
        /// 获取搜索学校
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<MessageModel<List<IdNameResult>>> GetUniversitList(NameQuery query)
        {
            var info = await _dal.Query(x => x.Name.Contains(query.Name) && x.IsDelete == false);
            if (info.Count <= 0)
                return new MessageModel<List<IdNameResult>>() { success = false, msg = "获取失败，数据为空" };
            return new MessageModel<List<IdNameResult>>()
            {
                success = true,
                msg = "获取成功",
                response = info.Select(x => new IdNameResult()
                {
                    Id = x.Id,
                    Name = x.Name
                }).ToList()
            };
        }
    }
}