using Microsoft.AspNetCore.Mvc;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Attributes;
using ZhonTai.Admin.Core.Consts;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Domain.User;
using ZhonTai.Admin.Repositories.Project;
using ZhonTai.Admin.Repositories.ProjectLink;
using ZhonTai.Admin.Services.DiTuiAPI.Dto;
using ZhonTai.Admin.Services.Notice.Dto;
using ZhonTai.Admin.Services.ProjectLink.Dto;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;

namespace ZhonTai.Admin.Services.DiTuiAPI
{
    /// <summary>
    /// 项目接口
    /// </summary>
    [DynamicApi(Area = AdminConsts.DiTuiName)]
    //public class DiTuiAPIService : BaseService, IDiTuiAPIService, IDynamicApi
    public class ProjectsService : BaseService, IProjectsService, IDynamicApi
    {
        private ProjectLinkRepository _ProjectLinkRepository;
        private ProjectRepository _projectRepository;
        private ProjectPriceRepository _projectPriceRepository;
        public ProjectsService(ProjectLinkRepository projectLinkRepository,ProjectRepository projectRepository,ProjectPriceRepository projectPriceRepository)
        {
            _ProjectLinkRepository = projectLinkRepository;
            _projectRepository = projectRepository;
            _projectPriceRepository = projectPriceRepository;
        }

        /// <summary>
        /// 我的项目
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoOprationLog]
        public async Task<MyProjectOutput> MyProjectAsync()
        {
            MyProjectOutput myProjectOutput = new MyProjectOutput();

            var linkList = _ProjectLinkRepository.Select
                .DisableGlobalFilter(FilterNames.Tenant)
                .Where(a => a.ModifiedUserId == User.Id)
                .GroupBy(m => new { m.ProjectId, m.Company })
                .ToList(m => new ProjectLinkManagePageOutput()
                {
                    ProjectId = m.Key.ProjectId,
                    Company = m.Key.Company,
                    Count = m.Count(),
                    UseCount = m.Sum(m.Value.IsUse == 1 ? 1 : 0),
                    ProjectName = ""
                });

            var listProjectId = linkList.Select(m => m.ProjectId).Distinct().ToList();

            if (listProjectId.Count() > 0)
            {
                var listProject = await _projectRepository.Select.DisableGlobalFilter(FilterNames.Tenant).Where(m => listProjectId.Contains(m.Id)).ToListAsync(m => new MyProject(
                    m.Id,
                    m.Name,
                    m.Logo,
                    m.MaxPrice.ToString() + "元",
                    "T+" + m.SettleDay.ToString() + "结算"
                ));
                myProjectOutput.MyProjects = listProject;
            }
            return myProjectOutput;

            //List<MyProject> myProjects = new List<MyProject>();
            //myProjects.Add(new MyProject(
            //        414497860591685,
            //         "快手极速版",
            //        "https://test-dt.zhongjie51.com/assetsImg/ks_logo.png",
            //        "25元",
            //        "T+1结算"
            //    ));
            //myProjects.Add(new MyProject(
            //        414497860591687,
            //         "点淘拉新",
            //        "https://test-dt.zhongjie51.com/assetsImg/dt_logo.png",
            //        "30元",
            //        "T+3结算"
            //    ));
            //myProjectOutput.MyProjects = myProjects;
            //return myProjectOutput;
        }

        /// <summary>
        /// 项目详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [NoOprationLog]
        public async Task<ProjectDescOutput> ProjectDescAsync(long id = 0)
        {
            if(id == 0)
            {
                throw ResultOutput.Exception($"ID 不可为空");
            }

            // 根据ID查询到项目的相关信息返回
            
            var result = await _projectRepository.Select.DisableGlobalFilter()
                .Where(a => a.Id == id)
                .FirstAsync(a => new ProjectDescOutput(a.Id,a.Logo,a.Name,a.MaxPrice.ToString(),a.SettleDay.ToString(),a.Tips));
            return result;

            //ProjectDescOutput projectDescOutput = new ProjectDescOutput();
            //var doubleUser = await _ProjectLinkRepository.Select.Where(a => a.SalesmanPhone == input.SalesmanPhone && a.ProjectId == input.ProjectId)
            //    .FirstAsync(a => new { a.Salesman, a.SalesmanPhone, a.Id });
            //projectDescOutput.Id = result.Id;
            //projectDescOutput.Logo = result.Logo;
            //projectDescOutput.Name = "快手极速版";
            //projectDescOutput.Price = "25";
            //projectDescOutput.SettleDay = "T+1结算";
            //projectDescOutput.Description = "快手极速版APP的新用户，全国可做不限推广方式，实时进件数据，不测次播，官方直推版。";
            //return projectDescOutput;
        }

        /// <summary>
        /// 项目说明
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [NoOprationLog]
        public async Task<ProjectSpecOutput> ProjectSpecAsync(long id = 0)
        {
            if (id == 0)
            {
                throw ResultOutput.Exception($"ID 不可为空");
            }
            var result = await _projectRepository.Select.DisableGlobalFilter()
                .Where(a => a.Id == id)
                .FirstAsync(a => new ProjectSpecOutput(a.Id, a.VideoUrl, a.Detail));


            result.Prices = await _projectPriceRepository.Select.DisableGlobalFilter()
                .Where(a => a.ProjectId == id)
                .ToListAsync(a => new ProjectPrice(
                        a.Name,
                        a.Price.ToString()
                    ));

            return result;


            //ProjectSpecOutput projectSpecOutput = new ProjectSpecOutput();

            //projectSpecOutput.VideoUrl = "https://test-dt.zhongjie51.com/assetsImg/test.mp4";
            //projectSpecOutput.Detail = "<p><b id=\"4g60c\" style=\"letter-spacing: 0.00735em;\"><font id=\"8o15r\" color=\"#1c487f\">注意事项：</font></b><br/></p><p>\r\n1.<font color=\"#f9963b\">新老用户均可下单，从未在抖店下过单的即可。成功领取抖音平台通用新人券的为电商新用户</font></p><p>2.提醒用户第二天务必打开APP，查看物流信息，确保商家正常发货&nbsp;</p><p>3.<font color=\"#c24f4a\"><b>仅限抖音APP</b>，请勿使用极速版、火山版下单</font></p><p><font color=\"#c24f4a\">4.<b>复购订单必须直接在抖音商城下单！直播间下单无法结算！</b></font></p><p>5.必须真实推广，禁止机刷，机刷不结算并上报司法机关&nbsp;</p><p>6.禁止一机多单，禁止一个支付账号（微信、支付宝、银行卡）多次支付，禁止代付等行为&nbsp;</p><p>7.禁止填写同一收货人姓名、手机号、地址，必项填写注册手机号及客户真实收货信息&nbsp;</p><p>8.禁止使用WIFI、热点作业\r\n\r\n</p><p>9.为了避免活动下线，做单没有数据。请所有业务员务必<font color=\"#c24f4a\">每天扫描一次母码，获取新的作业码！</font></p><p>（具体步骤请参考下图）<br/><img src=\"https://media.jietui.cn/article/20230420223625687184.png\" contenteditable=\"false\" style=\"font-size: 14px; max-width: 100%;\"/></p><hr/><h4><b id=\"4g60c\" style=\"letter-spacing: 0.00735em;\"><font id=\"de97j\" color=\"#1c487f\">拉新流程：</font></b></h4><p>\r\n1.使用抖音扫描拉新二维码&nbsp;</p><p>2.扫码以后弹出的活动界面，完成新人首购，挑选任意商品，点击领券购买</p><p>3.填写收货信息（注意必须填写真实的收货信息）选择任意支付方式，支付即可</p><p>4.第二天，再次扫码（不扫码也可复购，只是没有实时数据）跳转到活动界面，完成复购，复购无金额要求！</p><h4><hr/><p><b style=\"letter-spacing: 0.00735em;\"><font id=\"g98c4\" color=\"#1c487f\">图文教程：</font></b><br/></p></h4>\r\n<p><img src=\"https://media.jietui.cn/personal/douyin_dianshang/123.png\" style=\"max-width:100%;\" contenteditable=\"false\"/></p><p><br/></p>";

            //List<ProjectPrice> projectPrices = new List<ProjectPrice>();
            ////projectPrices.Add(new ProjectPrice( ));
            //projectPrices.Add(new ProjectPrice("新设备次播", "25"));
            //projectPrices.Add(new ProjectPrice("新设备3留", "8"));
            //projectPrices.Add(new ProjectPrice("申领礼品", "20"));
            //projectPrices.Add(new ProjectPrice("老设备次留", "5"));

            //projectSpecOutput.Prices = projectPrices;

            //return projectSpecOutput;
        }

        /// <summary>
        /// 项目详情-推广码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageOutput<ProjectQrcodePageOutput>> ProjectQrcodePageAsync(PageInput<ProjectQrcodePageInput> input)
        {
            var keyWrods = input.Filter?.Keywords;

            string Salesman = null;
            string SalesmanPhone = null;
            //var Salesman = input.Filter?.Salesman;
            //var Salesman = input.Filter?.Salesman;
            //var SalesmanPhone = input.Filter?.SalesmanPhone;
            //var SalesmanPhone = input.Filter?.SalesmanPhone;
            //var SalesmanPhone = input.Filter?.SalesmanPhone;
            if (!string.IsNullOrEmpty(keyWrods))
            {
                if(IsPhoneNumber(keyWrods))
                {
                    SalesmanPhone = keyWrods;
                }
                else
                {
                    Salesman = keyWrods;
                }

            }

            
            var ProjectId = input.Filter?.ProjectId;
            if (ProjectId == 0 || string.IsNullOrEmpty(ProjectId.ToString()))
            {
                throw ResultOutput.Exception("项目 ID 不可为空");
            }

            var list = _ProjectLinkRepository.Select.DisableGlobalFilter(FilterNames.Tenant)
                .WhereIf(ProjectId.HasValue && ProjectId.Value > 0, a => a.ProjectId == ProjectId)
                .WhereIf(Salesman.NotNull(), a => a.Salesman.Contains(Salesman))
                .WhereIf(SalesmanPhone.NotNull(), a => a.SalesmanPhone.Contains(SalesmanPhone))
                .Where(a=> a.IsUse == 1)
            .Count(out var total)
            .Page(input.CurrentPage, input.PageSize)
            .ToList(m => new ProjectQrcodePageOutput()
            {
                Id = m.Id,
                Salesman = m.Salesman,
                UseTime = m.UseTime,
                QrcodeUrl = m.QrcodeUrl,
                QueryUrl = m.QueryUrl
            });

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

            return data;
        }

        /// <summary>
        /// 项目统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageOutput<ProjectCountPageOutput>> ProjectCountPageAsync(PageInput<ProjectCountPageInput> input)
        {
            var ProjectId = input.Filter?.ProjectId;
            var Date = input.Filter?.Date;
            if(ProjectId == null)
            {
                ProjectId = 0;
            }


            //var list = _ProjectLinkRepository.Select.DisableGlobalFilter(FilterNames.Tenant)
            //    .WhereIf(ProjectId.HasValue && ProjectId.Value > 0, a => a.ProjectId == ProjectId)
            //    .WhereIf(Salesman.NotNull(), a => a.Salesman.Contains(Salesman))
            //    .WhereIf(SalesmanPhone.NotNull(), a => a.SalesmanPhone.Contains(SalesmanPhone))
            //.Count(out var total)
            //.Page(input.CurrentPage, input.PageSize)
            //.ToList(m => new ProjectQrcodePageOutput()
            //{
            //    Id = m.Id,
            //    Salesman = m.Salesman,
            //    UseTime = m.UseTime,
            //    QrcodeUrl = m.QrcodeUrl,
            //    QueryUrl = m.QueryUrl
            //});

            List<ProjectCountPageOutput> list = new List<ProjectCountPageOutput>();
            List<SettleCount> settleCounts = new List<SettleCount>();
            settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            settleCounts.Add(new SettleCount("电商首购B级", "201/300单", "201元"));
            settleCounts.Add(new SettleCount("电商首购C级", "202/300单", "202元"));
            settleCounts.Add(new SettleCount("今日汇总", "603/900单", "603元"));

            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            list.Add(new ProjectCountPageOutput((long)(ProjectId != 0 ? ProjectId : 416237348180038), "2023-05-02","", settleCounts));

            List<SettleCount> settleCounts1 = new List<SettleCount>();
            settleCounts1.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            settleCounts1.Add(new SettleCount("电商首购B级", "199/300单", "199元"));
            settleCounts1.Add(new SettleCount("电商首购C级", "198/300单", "198元"));
            settleCounts1.Add(new SettleCount("今日汇总", "597/900单", "597元"));

            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            list.Add(new ProjectCountPageOutput((long)(ProjectId != 0 ? ProjectId : 416237348180038), "2023-05-01","", settleCounts1));

            // 项目日统计数据
            List<ProjectCountPageOutput> listDay = new List<ProjectCountPageOutput>();
            List<SettleCount> settleCountsDay = new List<SettleCount>();
            settleCountsDay.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            settleCountsDay.Add(new SettleCount("电商首购B级", "201/300单", "201元"));
            settleCountsDay.Add(new SettleCount("电商首购C级", "202/300单", "202元"));
            settleCountsDay.Add(new SettleCount("今日汇总", "603/900单", "603元"));

            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            listDay.Add(new ProjectCountPageOutput((long)(ProjectId != 0 ? ProjectId : 416237348180038), !string.IsNullOrEmpty(Date)? Date :"2023-05-02", "中捷乐淘", settleCountsDay));

            List<SettleCount> settleCountsDay1 = new List<SettleCount>();
            settleCountsDay1.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            settleCountsDay1.Add(new SettleCount("电商首购B级", "199/300单", "199元"));
            settleCountsDay1.Add(new SettleCount("电商首购C级", "198/300单", "198元"));
            settleCountsDay1.Add(new SettleCount("今日汇总", "597/900单", "597元"));

            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            listDay.Add(new ProjectCountPageOutput((long)(ProjectId != 0 ? ProjectId : 416237348180038), !string.IsNullOrEmpty(Date) ? Date : "2023-05-02", "suzhou柿集", settleCountsDay1));

            if(!string.IsNullOrEmpty(Date))
            {
                list = listDay;
            }
            

            var total = list.Count;


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

            return data;
        }

        /// <summary>
        /// 开码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [NoOprationLog]
        public async Task<string> BindQrcodeAsync(BindQrcodeInput input)
        {
            // 判断用户是否已经 开码  同租户 同项目 手机号唯一
            var doubleUser = await _ProjectLinkRepository.Select.Where(a => a.SalesmanPhone == input.SalesmanPhone && a.ProjectId == input.ProjectId)
                .FirstAsync(a => new { a.Salesman, a.SalesmanPhone, a.Id });
            if(doubleUser != null)
            {
                throw ResultOutput.Exception($"手机号已开码");
            }

            // 查询未使用的链接的第一条数据
            var existsLink = await _ProjectLinkRepository.Select.Where(a => a.IsUse == 0 && a.ProjectId == input.ProjectId)
                .FirstAsync(a => new { a.Id, a.ModifiedTime});
            if (existsLink == null)
            {
                throw ResultOutput.Exception($"当前项目已无可用链接");
            }

            var qrcode = await _ProjectLinkRepository.GetAsync(existsLink.Id);
            if (!(qrcode?.Id > 0))
            {
                throw ResultOutput.Exception("链接不存在");
            }
            if(qrcode?.IsUse > 0)
            {
                throw ResultOutput.Exception("链接已使用，请重新开码");
            }

            Mapper.Map(input, qrcode);
            qrcode.IsUse = 1;

            await _ProjectLinkRepository.UpdateAsync(qrcode);

            // 返回 链接ID 
            return qrcode.Id.ToString();
        }

        /// <summary>
        /// 获取开码信息
        /// </summary>
        /// <param name="id">二维码ID（链接ID）</param>
        /// <returns></returns>
        [HttpGet]
        [NoOprationLog]
        public async Task<BindQrcodeOutput> GetBindQrcodeAsync(long id = 0)
        {
            if (id == 0)
            {
                throw ResultOutput.Exception($"无效参数");
            }
            var result = await _ProjectLinkRepository.GetAsync<BindQrcodeOutput>(id);
            return result;
        }


        /// <summary>
        /// 推广码每日统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageOutput<ProjectCountPageOutput>> QrcodeCountPageAsync(PageInput<QrcodeCountPageInput> input)
        {
            var Id = input.Filter?.Id;
            if (Id == null)
            {
                Id = 0;
            }


            //var list = _ProjectLinkRepository.Select.DisableGlobalFilter(FilterNames.Tenant)
            //    .WhereIf(ProjectId.HasValue && ProjectId.Value > 0, a => a.ProjectId == ProjectId)
            //    .WhereIf(Salesman.NotNull(), a => a.Salesman.Contains(Salesman))
            //    .WhereIf(SalesmanPhone.NotNull(), a => a.SalesmanPhone.Contains(SalesmanPhone))
            //.Count(out var total)
            //.Page(input.CurrentPage, input.PageSize)
            //.ToList(m => new ProjectQrcodePageOutput()
            //{
            //    Id = m.Id,
            //    Salesman = m.Salesman,
            //    UseTime = m.UseTime,
            //    QrcodeUrl = m.QrcodeUrl,
            //    QueryUrl = m.QueryUrl
            //});

            List<ProjectCountPageOutput> list = new List<ProjectCountPageOutput>();
            List<SettleCount> settleCounts = new List<SettleCount>();
            settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            settleCounts.Add(new SettleCount("电商首购B级", "201/300单", "201元"));
            settleCounts.Add(new SettleCount("电商首购C级", "202/300单", "202元"));
            settleCounts.Add(new SettleCount("今日汇总", "603/900单", "603元"));

            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            list.Add(new ProjectCountPageOutput((long)(Id != 0 ? Id : 416237348180038), "2023-05-02", "", settleCounts));

            List<SettleCount> settleCounts1 = new List<SettleCount>();
            settleCounts1.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            settleCounts1.Add(new SettleCount("电商首购B级", "199/300单", "199元"));
            settleCounts1.Add(new SettleCount("电商首购C级", "198/300单", "198元"));
            settleCounts1.Add(new SettleCount("今日汇总", "597/900单", "597元"));

            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            //settleCounts.Add(new SettleCount("电商首购A级", "200/300单", "200元"));
            list.Add(new ProjectCountPageOutput((long)(Id != 0 ? Id : 416237348180038), "2023-05-01", "", settleCounts1));

            var total = list.Count;


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

            return data;
        }

        /// <summary>
        /// 判断字符串是否是手机号
        /// </summary>
        /// <param name="str_handset"></param>
        /// <returns></returns>
        private static bool IsPhoneNumber(string str_handset)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(str_handset, @"^1[3456789]\d{9}$");
        }
    }
}
