using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.Data.Infrastructure;

namespace XYY.Data.Standard.WX
{
    public interface IWXBindRepository
    {
        Task<IEnumerable<WXUserInfo>> GetWXUserId(int[] xyyUserId);

        Task<IEnumerable<WXCustomerInfo>> GetCustomerWXUserId(int[] CustomerId);
    }

    public class WXCustomerInfo
    {
        public string NickName
        {
            get; set;
        }

        public int UserId
        {
            get; set;
        }

        public string WXUserId
        {
            get; set;
        }
    }
    public class WXUserInfo
    {
        public string NickName
        {
            get; set;
        }

        public int UserId
        {
            get; set;
        }

        public string WXUserId
        {
            get; set;
        }
    }

    public class WXBindRepository : IWXBindRepository
    {

        public IUnitOfWork _unitOfWork;

        public WXBindRepository(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<IEnumerable<WXCustomerInfo>> GetCustomerWXUserId(int[] CustomerId)
        {
            string sql = @"select a.Id as UserId , isnull( a.Abbreviation, a.CompanyName),b.WXUserId from user_customer(nolock)a left join QWCustomer_Info(nolock)b 
on a.id=b.CustomerId
	where a.Id in @CustomerId";
            var data = await _unitOfWork.QueryBySqlAsync<WXCustomerInfo>(sql, null, new { CustomerId });
            if (CustomerId.Count() != data.Count())
            {
                throw new Exception("客户信息不一致，请核实传入客户ID无误");
            }
            else
            {
                string noUsers = string.Join(",", data.Where(x => x.WXUserId == null).Select(x => x.NickName));
                if (!string.IsNullOrEmpty(noUsers))
                {
                    throw new Exception($"以下用户未同步微信客户信息，请联系客服/行政人员：{noUsers}");
                }
            }
            return data;
        }

        public async Task<IEnumerable<WXUserInfo>> GetWXUserId(int[] xyyUserId)
        {
            string sql = @"select a.Id as UserId ,a.NickName,b.WXUserId from User_Info(nolock)a left join QWUser_Info(nolock)b 
on a.id=b.UserId where a.Id in @xyyUserId";
            var data = await _unitOfWork.QueryBySqlAsync<WXUserInfo>(sql, null, new { xyyUserId });
            if (xyyUserId.Count() != data.Count())
            {
                throw new Exception("用户信息不一致，请核实传入用户ID无误");
            }
            else
            {
                string noUsers = string.Join(",", data.Where(x => x.WXUserId == null).Select(x => x.NickName));
                if (!string.IsNullOrEmpty(noUsers))
                {
                    throw new Exception($"以下用户未同步微信用户信息，请联系客服/行政人员：{noUsers}");
                }
            }
            return data;
        }
    }
}
