using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TellerSystem.Contract.ContractBase;
using Newtonsoft.Json;
using TellerSystem.Library.Ext.Function;
using Platform.Presentation.PageFunctions;
using Platform.Presentation.Interfaces;
using Platform.Library;

namespace TellerSystem.Contract.Entry
{
    public class CashCodeEntry : EntryBase
    {
        #region static
        private const string _action_ = "Trade.OperationManage.CASHVIEWER";

        public static bool Enabled { get; private set; }

        public static string lastendTime;

        public static List<CashCodeEntry.BizItem> History { get; private set; }
        static CashCodeEntry()
        {
            Enabled = ServiceProxy.Ext.ServiceSettings.GetConfig("CashCodeManage", false);
            History = new List<CashCodeEntry.BizItem>();
        }

        public static bool Init(IPage target)
        {
            if (!Enabled) return true;
            var flag = false;
            try
            {
                //初始化点钞机节点程序
                dynamic page = PageFactory.CreatePage(_action_);
                while (true)
                {
                    target.OwnerContainer.ModalInvoke(() =>
                    {
                        flag = page.InitDevice();
                    }, "链接冠字号设备，请稍候...");
                    if (flag)
                        break;
                    var i = target.ShowComfirmBox("链接冠字号设备失败，是否重试？", new string[] { "重试", "关闭功能", "稍后处理" });
                    if (i == 2) Enabled = false;
                    if (i != 1) break;
                }
            }
            catch (Exception ex)
            {
                Platform.Common.LogSystem.PlatformLogger.SystemErrorInfo("CashCodeEntry.InitDevice:发生异常！", ex);
                //throw new InvalidOperationException("初始化现金冠字号程序失败！");
            }
            return flag;
        }
        #endregion

        #region ctor
        /// <summary>
        /// 构造函数
        /// </summary>
        public CashCodeEntry()
        {
            Item = new BizItem();
            Item.StartTime = DateTime.Now;
        }

        /// <summary>
        /// 业务类型
        /// </summary>
        public enum BizType
        {
            /// <summary>
            /// 存款业务
            /// </summary>
            Deposit = 0,
            /// <summary>
            /// 取款业务
            /// </summary>
            Withdrawal = 1,
            /// <summary>
            /// 残缺币兑换
            /// </summary>
            Incomplete = 4,
            /// <summary>
            /// 假币收缴
            /// </summary>
            Counterfeit = 5,
            /// <summary>
            /// 其他
            /// </summary>
            Other = 6,
        }

        public class BizItem
        {
            /// <summary>
            /// 业务开始办理时间
            /// </summary>
            public DateTime? StartTime { get; internal set; }
            /// <summary>
            /// 业务结束办理时间
            /// </summary>
            public DateTime? EndTime { get; internal set; }

            /// <summary>
            /// 业务类型
            /// </summary>
            public BizType Biz { get; internal set; }

            /// <summary>
            /// 交易卡号
            /// </summary>
            public string CardNo { get; internal set; }

            /// <summary>
            /// 用户名称
            /// </summary>
            public string UserName { get; internal set; }

            /// <summary>
            /// 交易金额
            /// </summary>
            public decimal Money { get; internal set; }

            /// <summary>
            /// 柜面交易码
            /// </summary>
            public string TxCode { get; internal set; }

            /// <summary>
            /// 交易流水
            /// </summary>
            public string SerialNo { get; internal set; }
        }

        public class MyBizItem : BizItem
        {
            public void MyMethod(DateTime startTime, DateTime endTime, BizType biz, string cardNo, string userName, decimal money, string txCode, string serialNo)
            {
                this.StartTime = startTime;
                this.EndTime = endTime;
                this.Biz = biz;
                this.CardNo = cardNo;
                this.UserName = userName;
                this.Money = money;
                this.TxCode = txCode;
                this.SerialNo = serialNo;
            }
        }

        /// <summary>
        /// 预处理时的柜员钱箱余额
        /// </summary>
        public Dictionary<string, decimal> Bals2Init { get; private set; }

        /// <summary>
        /// 当前处理的Item对象
        /// </summary>
        public BizItem Item { get; private set; }

        /// <summary>
        /// 预处理
        /// </summary>
        /// <param name="cardNo"></param>
        /// <param name="userName"></param>
        /// <param name="biz"></param>
        /// <returns></returns>
        internal bool Preview(string cardNo, string userName, BizType biz)
        {
            if (!Enabled) return true;
            if (!string.IsNullOrEmpty(TradeBus["__StartTime__"]))
                Item.StartTime = DateTime.ParseExact(TradeBus["__StartTime__"], "yyyyMMddHHmmss", null);
            this.Item.CardNo = cardNo;
            this.Item.UserName = userName;
            this.Item.Biz = biz;
            this.Item.TxCode = PageData.TradeModel.Code;
            var dict = new Dictionary<string, string>();
            //登记入库
            //if (PageData.TradeAPIs.TraderecordsExp("CashCodeEntry", JsonConvert.SerializeObject(dict)))
            //{
            var current = PageData.GetTellerBalanceMoney();
            if (current != null)
            {
                Bals2Init = current;
                //打印后触发
                PageData.PagePrinted -= PageData_PagePrinted;
                PageData.PagePrinted += PageData_PagePrinted;
                return true;
            }
            //}
            return false;
        }

        void PageData_PagePrinted(object sender, PageBase.PagePrintedEventArgs e)
        {
            Proc(e.PrintAttr.SerialNumber);
        }

        /// <summary>
        /// 业务处理
        /// </summary>
        void Proc(string serialNo)
        {
            if (!Enabled) return;
            //未调用Preview，不触发
            if (Bals2Init == null) return;
            this.Item.SerialNo = serialNo;
            this.Item.EndTime = DateTime.Now;
            //检查余额变化，目前仅检测人民币
            var current = PageData.GetTellerBalanceMoney();
            this.Item.Money = current["01"] - Bals2Init["01"];
            if (this.Item.Money != 0 || this.Item.Biz == BizType.Counterfeit)//假币收缴业务不会影响钱箱
            {
                //History.Add(this.Item);
                while (true)
                {
                    //提示处理
                    //if (PageData.TradeAPIs.ShowQuestionMessageBox("本次交易存在现金处理，是否进行现金冠字号处理？\n是：立即提交\n否：等待下一笔业务提交") == System.Windows.MessageBoxResult.No)
                    //    break;
                    var key = this.TradeAPIs.ShowComfirmBox("本次交易存在现金处理，是否进行现金冠字号处理？\n", "立即提交", "等待下一笔业务提交", "该交易无点钞操作无需处理");
                    if (key == 3) break;
                    History.Add(this.Item);
                    if (key != 1) break;

                    //弹窗处理业务
                    var guid = PageData.OpenTradePage(_action_, TradePageExtension.OpenOptions.Dialog, new Dictionary<string, object> { { "STATUS_CASHVIEWER", "init" }, }, null, "现金业务-冠字号管理");
                    var status = (string)PageData.ViewStateData["STATUS_CASHVIEWER"];
                    //已提交或取消，跳出循环
                    if (status == "commit" || status == "cancel")
                        break;
                }
            }
        }
        #endregion
    }
}
