using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Model.Standard;
using XYY.Common.Standard;
using XYY.Data.Standard;
using XYY.Service.Standard.Customer.Dto;

namespace XYY.Service.Standard.Customer
{
    public interface ICustomerService
    {
        Task<IEnumerable<User_Customer>> CacheGetAllCustomers();
        Task<IEnumerable<User_Customer>> GetFirstCustomers();


        Task AlertFreezeCustomer(int freezedInDays);
        Task<int> NoAlertFreezedUntil(string customerIds, int days);
        Task<int> DelayFreezed(string customerIds, int days);
    }

    public class CustomerService : ICustomerService
    {
        const string CustomerCacheKey = "@@CustomerCacheKey";

        IDistributedCache _distributedCache;
        IUserCustomerRepository _customerRepository;

        public CustomerService(IDistributedCache distributedCache, IUserCustomerRepository customerRepository)
        {
            _distributedCache = distributedCache;
            _customerRepository = customerRepository;
        }

        public async Task AlertFreezeCustomer(int freezedInDays)
        {
            var customers = await GetAllFreezeSoonCustomer(freezedInDays);
            var targetCustomers = customers.Where(c => c.SalesmanUserId.HasValue);
            if (targetCustomers?.Any() != true)
                return;

            var groups = targetCustomers.GroupBy(c => c.SalesmanUserId.Value);

            var salesmanUserIds = groups.Select(i => i.Key);
            //var salesmans = await _userRepository.QueryAsync(u => u.Id.In(salesmanUserIds));

            int financeUserId = 200;//财务李素
            //var financeUser = await _userRepository.GetAsync(financeUserId);

            string host = "http://120.24.149.148:9513";
//#if DEBUG
//           host = "http://localhost:9513";
//#endif
            foreach (var g in groups)
            {
                //var salesman = salesmans.FirstOrDefault(c => c.Id == g.Key);
                int salesmanId = g.Key;
//#if DEBUG
//                salesmanId = 164;
//#endif
                string companyNames = string.Join(',', g.Select(i => i.CompanyName));
                string customerIds = string.Join(',', g.Select(i => i.Id));
                string title = $"客户在{freezedInDays}天后即将冻结，请操作";


                string noAskUrl = $"/api/customer/NoAlertFreezedUntil?customerIds={customerIds}&days=30";
                string delayUrl = $"/api/customer/DelayFreezed?customerIds={customerIds}&days=30";

                var buttons = new List<ActionCardButton>
                {
                    new ActionCardButton{ Text="不再提示",Link=$"{host}{noAskUrl}"},
                    new ActionCardButton{ Text="延期冻结",Link=$"{host}{delayUrl}"},
                };
                ActionCardNoticeTarget actionCardNoticeTarget = new ActionCardNoticeTarget
                {
                    ButtonOrient = "1",
                    Buttons = buttons,
                    ServiceType = "钉钉",
                    Text = $"以下客户在{freezedInDays}天后即将冻结，请操作:{companyNames}",
                    Title = title,
                    UserIds = new List<int> { salesmanId , financeUserId },
                    ToAllUser = false
                };

                await SendAlertFreezedMessage(actionCardNoticeTarget);
            }
        }

        private async Task SendAlertFreezedMessage(ActionCardNoticeTarget actionCardNoticeTarget)
        {
            string host = "http://localhost:9505";
            string url = "WarningNotice/NoticeCard";
            RestSharp.RestClient client = new RestSharp.RestClient(host);
            RestSharp.RestRequest request = new RestSharp.RestRequest(url, RestSharp.Method.POST);
            request.AddJsonBody(actionCardNoticeTarget);
            await client.ExecuteAsync(request);
        }

        public async Task<IEnumerable<User_Customer>> CacheGetAllCustomers()
        {
            var result = await _distributedCache.GetAsync(CustomerCacheKey, async () =>
            {
                var result = await _customerRepository.QueryAsync();
                return result;
            });
            return result;
        }

        public async Task<IEnumerable<User_Customer>> GetAllFreezeSoonCustomer(int inDays)
        {
            var customers = await _customerRepository.GetAllFreezeSoonCustomer(inDays);
            return customers;

        }

        public async Task<IEnumerable<User_Customer>> GetFirstCustomers()
        {
            string sql = " select * from User_Customer where type=2 ";
            var result = await _customerRepository.QueryBySqlAsync(sql);
            return result;
        }

        public async Task<int> NoAlertFreezedUntil(string customerIds, int days)
        {

            int count = await _customerRepository.NoAlertFreezedUntil(customerIds,days);
            return count;
        }

        public async Task<int> DelayFreezed(string customerIds, int days)
        {
            int count = await _customerRepository.DelayFreezed(customerIds, days);
            return count;
        }

        private int[] splitId(string customerIds)
        {
            var ids = customerIds?.SplitToArray<int>();
            return ids;
        }
    }
}
