using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PushPlatform.Common.Util
{
    /// <summary>
    /// 瓮式分组
    /// </summary>
    public class BlockUrnHelper
    {
        public BlockUrnHelper()
        {

        }

        public BlockUrnHelper(int blockSize)
        {
            this.BlockSize = blockSize;
        }

        /// <summary>
        /// 每组数量
        /// </summary>
        public int BlockSize { get; set; }

        /// <summary>
        /// 获取随机种子数
        /// </summary>
        /// <returns></returns>
        private static int GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }

        /// <summary>
        /// 每次随机使用到的随机数
        /// </summary>
        private double _RndNum
        {
            get
            {
                int seed = GetRandomSeed();
                Random rnd = new Random(seed);
                int num = rnd.Next(1, 1000);
                return Math.Round(num * 0.001, 3);
            }
        }

        /// <summary>
        /// 获取随机结果
        /// </summary>
        /// <param name="randomSequence">随机序号，对应每个中心的入组序号</param>
        /// <param name="blockACount">当前A组的数量</param>
        /// <param name="blockBcount">当前B组的数量</param>
        /// <param name="rndNum">这次随机使用的随机数</param>
        /// <returns></returns>
        public double GetRandomResult(int randomSequence, int blockACount, int blockBcount, out double rndNum)
        {
            double numerator = (this.BlockSize / 2 + Math.Min(blockACount, blockBcount) - blockACount);
            double denominator = (this.BlockSize + 2 * Math.Min(blockACount, blockBcount) - (randomSequence - 1));
            rndNum = this._RndNum;
            return Math.Round(numerator / denominator, 3);
        }
    }


    /// <summary>
    /// 中心随机结果
    /// </summary>
    public class SiteRndResult
    {
        /// <summary>
        /// 中心
        /// </summary>
        public string Site { get; set; }

        /// <summary>
        /// 随机结果数据集合
        /// </summary>
        public List<RndData> RndData { get; set; }
    }

    /// <summary>
    /// 随机结果数据
    /// </summary>
    public class RndData
    {
        /// <summary>
        /// 序号
        /// </summary>
        public int Sequence { get; set; }

        /// <summary>
        /// 随机数
        /// </summary>
        public double RndNum { get; set; }

        /// <summary>
        /// 概率
        /// </summary>
        public double Probability { get; set; }

        /// <summary>
        /// 分组
        /// </summary>
        public string Block { get; set; }
    }
}
