using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using OnceMi.AspNetCore.OSS;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Configs;
using ZhonTai.Admin.Core.Consts;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Core.Helpers;
using ZhonTai.Admin.Domain.File;
using ZhonTai.Admin.Domain.Project;
using ZhonTai.Admin.Domain.ProjectLink;
using ZhonTai.Admin.Domain.Role;
using ZhonTai.Admin.Repositories;
using ZhonTai.Admin.Services.Project;
using ZhonTai.Admin.Services.ProjectLink.Dto;
using ZhonTai.Common.Files;
using ZhonTai.Common.Helpers;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;

namespace ZhonTai.Admin.Services.ProjectLink
{
    /// <summary>
    /// 项目推广码服务
    /// </summary>
    [Order(10)]
    [DynamicApi(Area = AdminConsts.AreaName)]
    public class ProjectLinkService : BaseService, IProjectLinkService, IDynamicApi
    {
        private IProjectLinkRepository _ProjectLinkRepository => LazyGetRequiredService<IProjectLinkRepository>();
        private IProjectRepository _projectRepository => LazyGetRequiredService<IProjectRepository>();
        private OSSConfig _oSSConfig => LazyGetRequiredService<IOptions<OSSConfig>>().Value;
        private IHttpContextAccessor _httpContextAccessor => LazyGetRequiredService<IHttpContextAccessor>();

        public ProjectLinkService()
        {
        }

        ///// <summary>
        ///// 查询模块
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public async Task<ProjectLinkGetOutput> GetAsync(long id)
        //{
        //    var result = await _ProjectLinkRepository.GetAsync<ProjectLinkGetOutput>(id);
        //    return result;
        //}

        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<ProjectLinkListOutput>> GetPageAsync(PageInput<ProjectLinkGetPageDto> input)
        {
            var IsUse = input.Filter?.IsUse;
            var Company = input.Filter?.Company;
            var key = input.Filter?.Keywords;

            var list = await _ProjectLinkRepository.Select.DisableGlobalFilter(FilterNames.Tenant)
                .WhereIf(IsUse.HasValue && IsUse.Value >= 0, a => a.IsUse == IsUse)
                .WhereIf(Company.NotNull(), a => a.Company == Company)
            .WhereIf(key.NotNull(), a => a.Num == key || a.Salesman == key || a.SalesmanPhone == key)
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(m => new ProjectLinkListOutput()
            {
                Company = m.Company,
                OrgName = m.TenantId.ToString(),
                Num = m.Num,
                ShortUrl = m.ShortUrl,
                QrcodeUrl = m.QrcodeUrl,
                ShareCommand = m.ShareCommand,
                IsUse = m.IsUse,
                UseTime = m.UseTime,
                Salesman = m.Salesman,
                SalesmanPhone = m.SalesmanPhone,
                SalesmanRemark = m.SalesmanRemark,
            });

            var data = new PageOutput<ProjectLinkListOutput>()
            {
                List = list,
                Total = total
            };

            return data;
        }
        /// <summary>
        /// 上传推广码文件
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="ProjectId">文件目录</param>
        /// <param name="Company">文件重命名</param>
        /// <returns></returns>
        public async Task UploadLinkAsync([Required] IFormFile file, [Required] long ProjectId, [Required] string Company)
        {
            var localUploadConfig = _oSSConfig.LocalUploadConfig;

            var extention = Path.GetExtension(file.FileName).ToLower();
            if (extention != ".xlsx")
            {
                throw new Exception($"请上传excel格式文件");
            }
            var fileLenth = file.Length;
            if (fileLenth <= 0)
            {
                throw new Exception("文件不能为空");
            }
            if (fileLenth > localUploadConfig.MaxSize)
            {
                throw new Exception($"文件大小不能超过{new FileSize(localUploadConfig.MaxSize)}");
            }
            if (ProjectId <= 0)
            {
                throw new Exception($"请输入有效项目Id");
            }


            string fileDirectory = "link";

            string SaveFileName = FreeUtil.NewMongodbId().ToString();

            var filePath = Path.Combine(fileDirectory, SaveFileName + extention).ToPath();

            var uploadHelper = LazyGetRequiredService<UploadHelper>();
            var env = LazyGetRequiredService<IWebHostEnvironment>();
            fileDirectory = Path.Combine(env.WebRootPath, fileDirectory).ToPath();
            if (!Directory.Exists(fileDirectory))
            {
                Directory.CreateDirectory(fileDirectory);
            }
            filePath = Path.Combine(env.WebRootPath, filePath).ToPath();
            await uploadHelper.SaveAsync(file, filePath);

            //导入数据
            var datatable = NOPIHelper.ReadExcel(filePath);
            if (datatable == null || datatable.Rows.Count <= 0)
            {
                throw new Exception($"文件不能为空");
            }
            if (datatable.Columns["编号"] == null || datatable.Columns["口令"] == null || datatable.Columns["短链"] == null || datatable.Columns["二维码"] == null || datatable.Columns["查单链接"] == null)
            {
                throw new Exception($"导入格式不正确");
            }
            var projectAny = await _projectRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.Id == ProjectId).AnyAsync();
            if (!projectAny)
            {
                throw new Exception($"项目不存在");
            }
            var ListCompany = _ProjectLinkRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => m.ProjectId == ProjectId)
                 .GroupBy(m => m.Company).Select(m => m.Key).ToList();
            if (ListCompany.Count > 0 && !ListCompany.Contains(Company))
            {
                throw new Exception($"一个项目只能上传一个推广码来源");
            }
            List<string> listNum = (from d in datatable.AsEnumerable() select d.Field<string>("编号")).ToList();
            var count = await _ProjectLinkRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => listNum.Contains(m.Num)).CountAsync();
            if (count > 0)
            {
                throw new Exception($"编码重复");
            }
            List<ProjectLinkEntity> list = new List<ProjectLinkEntity>();
            foreach (DataRow row in datatable.Rows)
            {
                list.Add(new ProjectLinkEntity()
                {
                    Num = row["编号"]?.ToString(),
                    ShareCommand = row["口令"]?.ToString(),
                    ShortUrl = row["短链"]?.ToString(),
                    QrcodeUrl = row["二维码"]?.ToString(),
                    QueryUrl = row["查单链接"]?.ToString(),
                    ProjectId = ProjectId,
                    Company = Company,
                    TenantId=-1
                });
            }
            await _ProjectLinkRepository.InsertAsync(list);            
        }
        /// <summary>
        /// 下载推广码模板
        /// </summary>        
        /// <returns></returns>        
        [HttpGet]
        public string DownLinkCodeAsync()
        {
            string fileDirectory = "link";
            var filePath = Path.Combine(fileDirectory, "linkcode.xlsx").ToPath();

            var env = LazyGetRequiredService<IWebHostEnvironment>();
            var file = Path.Combine(env.WebRootPath, filePath).ToPath();
            if (!System.IO.File.Exists(file))
            {
                throw new Exception($"推广码模板文件不存在");
            }

            var linkUrl = $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Value}/{filePath}";

            return linkUrl;
        }

        ///// <summary>
        ///// 修改
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //public async Task UpdateAsync(ProjectLinkUpdateInput input)
        //{
        //    var entity = await _ProjectLinkRepository.GetAsync(input.Id);
        //    if (!(entity?.Id > 0))
        //    {
        //        throw ResultOutput.Exception("模块不存在");
        //    }

        //    Mapper.Map(input, entity);
        //    await _ProjectLinkRepository.UpdateAsync(entity);
        //}

        ///// <summary>
        ///// 彻底删除
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public async Task DeleteAsync(long id)
        //{
        //    await _ProjectLinkRepository.DeleteAsync(m => m.Id == id);
        //}

        ///// <summary>
        ///// 删除
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public async Task SoftDeleteAsync(long id)
        //{
        //    await _ProjectLinkRepository.SoftDeleteAsync(id);
        //}

        ///// <summary>
        ///// 批量删除
        ///// </summary>
        ///// <param name="ids"></param>
        ///// <returns></returns>
        //public async Task BatchSoftDeleteAsync(long[] ids)
        //{
        //    await _ProjectLinkRepository.SoftDeleteAsync(ids);
        //}

    }
}
