using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TellerSystem.Contract.ContractBase;
using TellerSystem.Communication;
using System.IO;
using Platform.Common.RunningParameters;

namespace TellerSystem.Contract.Function
{
    public abstract class TFInput : EntryBase
    {
        #region 域格式化函数
        /// <summary>
        /// 去空格函数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected string DelSpace(string str)
        {
            return str.Trim();
        }
        /// <summary>
        /// 格式化成数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected string Number(string str)
        {
            decimal temp = 0;
            if (!decimal.TryParse(str.Trim(), out temp))
                return str;
            return temp.ToString();
        }
        #endregion

        #region 属性
        /// <summary> 
        /// 主交易码  
        /// </summary> 
        public string MainCode { get; set; }

        /// <summary>
        /// 是否提示警告信息
        /// </summary>
        public bool IsShowWarning { get; set; }
        #endregion

        #region Ctor
        public TFInput()
        {
            IsShowWarning = true;
        }
        #endregion

        /// <summary>
        /// 执行逻辑数据填充
        /// </summary>
        public abstract TFOutput Raise();
        /// <summary>
        /// 执行操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="page"></param>
        /// <returns></returns>
        public T DoAction<T>(PageBase page) where T : TFOutput
        {
            LoadData(page, new Communication.Message());
            //获取主交易码
            if (string.IsNullOrEmpty(MainCode))
            {
                //从PageBase获取数据
                MainCode = page.TradeInfo.MainCode;
            }
            var ret = Raise() as T;
            //若返回WARN，则进行提示
            if (IsShowWarning && MessageData.Fd12 == "WARN")
            {
                PageData.TradeAPIs.ShowWarnMessageBox(PageData.TradeAPIs.GetError(MessageData));
                ret.IsFailed = false;
            }
            return ret;
        }

        /// <summary>
        /// 解析列表数据，format按照|分隔进行
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static List<T> AnilyzeFileData<T>(string fileData, string format, Func<Dictionary<string, string>, T> action) where T : new()
        {
            var ret = new List<T>();
            if (!string.IsNullOrEmpty(fileData))
            {
                var sr = new StringReader(fileData);
                var line = sr.ReadLine();
                if (string.IsNullOrEmpty(format) && line.StartsWith("~"))
                {
                    var cols = line.Substring(1).Split('|');
                    //处理重复项
                    var tmp = new Dictionary<string, string>();
                    foreach (var col in cols)
                    {
                        var cnt = tmp.Count(x => x.Value == col);
                        tmp.Add(col + (cnt > 0 ? cnt.ToString() : ""), col);
                    }
                    format = string.Join("|", tmp.Keys);
                    line = sr.ReadLine();
                }
                var colNames = format.Split('|');
                while (!string.IsNullOrEmpty(line))
                {
                    if (!line.StartsWith("~"))
                    {
                        var rowData = line.Split('|');
                        Dictionary<string, string> dict = null;
                        dict = new Dictionary<string, string>();
                        for (int i = 0; i < colNames.Length; i++)
                        {
                            if (string.IsNullOrEmpty(colNames[i])) continue;
                            dict.Add(colNames[i], rowData.Length > i ? rowData[i] : string.Empty);
                        }
                        ret.Add(action(dict));
                    }
                    line = sr.ReadLine();
                }
            }
            return ret;
        }

        /// <summary>
        /// 按格式解析返回字典
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="formatString"></param>
        /// <returns></returns>
        public static Dictionary<string, string> AnilyzeFileData(string fileData, string formatString)
        {
            var dict = new Dictionary<string, string>();
            if (string.IsNullOrEmpty(fileData) || string.IsNullOrEmpty(formatString))
            {
                return dict;
            }

            #region 解析格式化字符串

            var lengths = formatString.ToLower().Split(new char[] { 'o', 't', 'v' });
            //单位元素长度
            var cellLength = 0;
            //title的位置索引和长度
            var titleIndex = 0;
            var titleLength = 0;
            //value的位置索引和长度
            var valueIndex = 0;
            var valueLength = 0;
            //计数器
            int counter = 0;
            for (int i = 1; i < lengths.Length; i++)
            {
                var length = int.Parse(lengths[i]);
                switch (formatString[counter])
                {
                    case 't':
                        {
                            titleIndex = cellLength;
                            titleLength = length;
                            break;
                        }
                    case 'v':
                        {
                            valueIndex = cellLength;
                            valueLength = length;
                            break;
                        }
                    case 'o':
                        {
                            break;
                        }
                    default:
                        {
                            return dict;
                        }
                }
                counter++;
                counter += lengths[i].Length;
                cellLength += length;
            }

            #endregion 解析格式化字符串

            var data = PlatformSettings.Encoding.GetBytes(fileData);
            var count = data.Length / cellLength;
            var titleMaxLength = 0;
            //分批次处理单元元素

            for (int i = 0; i < count; i++)
            {
                var btemp = new byte[titleLength];
                Array.Copy(data, titleIndex + i * cellLength, btemp, 0, titleLength);
                string title = PlatformSettings.Encoding.GetString(btemp).Trim();//FormatTitle(PlatformSettings.Encoding.GetString(btemp));

                btemp = new byte[valueLength];
                Array.Copy(data, valueIndex + i * cellLength, btemp, 0, valueLength);
                string varValue = PlatformSettings.Encoding.GetString(btemp);

                dict.Add(title, varValue);

                if (title.Length > titleMaxLength)
                    titleMaxLength = title.Length;
            }

            return dict;
        }
    }

    public abstract class TFOutput
    {
        /// <summary>
        /// 执行结果
        /// </summary>
        public bool IsFailed { get; internal set; }
        /// <summary>
        /// 失败原因
        /// </summary>
        public string FailureCause { get; internal set; }

        /// <summary>
        /// 设置失败标志
        /// </summary>
        /// <param name="failureCause"></param>
        public void SetFailure(string failureCause)
        {
            IsFailed = true;
            FailureCause = failureCause;
        }
    }
}
