using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PTMedicalInsurance.Common.SMLib;
using PTMedicalInsurance.Entity;
using PTMedicalInsurance.Helper;
using PTMedicalInsurance.Variables;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Windows.Forms;


namespace PTMedicalInsurance.Business
{
    public class OneCodePay
    {
        public string url;
        InvokeHelper invoker = new InvokeHelper();  

        public OneCodePay() { }

        public int GetCertAndSendToHis(decimal cashPay, out string msg)
        {
            msg = "";

            if (string.IsNullOrEmpty(Global.pat.ecToken))
            {
                msg = "一码付介质必须是电子凭证或人脸支付，其他介质暂不支持！";
                return -1;
            }

            if (!Global.pat.isOneCodePayEnabled)
            {
                msg = "未在界面勾选启用一码付！";
                return -1;
            }


            //先查询状态
            if (QuerySignedPayStatus(out msg) != 0)
            {
                return -1;
            }

            JObject jo = JObject.Parse(msg);
            string stasFlag = JsonHelper.getDestValue(jo, "stasFlag");
            string abnRea = JsonHelper.getDestValue(jo, "abnRea");
            //解析状态
            switch (stasFlag)
            {
                case "0":
                    msg  = "未签约不可用！" +  abnRea;
                    return -1;
                case "1":
                    //msg = "已签约且可用";
                    //return 0;
                    break;
                case "2":
                    msg = "已签约不可用" + abnRea;
                    return -1;
                default:
                    msg = "返回stasFlag值不正确！";
                    return -1;
            }

            //获取凭证
            if (GetPayCert(cashPay, out msg) != 0)
            {
                return -1;
            }
            else
            {
                jo = JObject.Parse(msg);
                string payCert = JsonHelper.getDestValue(jo, "payCert");
                string payChnlName = JsonHelper.getDestValue(jo, "payChnlName");
                msg = BuildOneCodePaySuccessResult(payChnlName,payCert);
                Global.writeLog($"BuildOneCodePaySuccessResult:{msg}");
                return 0;
            }

        }

        /// <summary>
        /// 构建一码付结算成功的返回结果（含支付信息）
        /// </summary>
        /// <param name="payChannel">支付渠道，如 "ALIPAY" 或 "WECHAT"</param>
        /// <param name="authCode">用户授权码（付款码）</param>
        /// <returns>JSON 格式的 Iris 返回值字符串</returns>
        private string BuildOneCodePaySuccessResult(string payChannel, string authCode)
        {
            if (string.IsNullOrWhiteSpace(payChannel))
                MessageBox.Show($"支付渠道不能为空{nameof(payChannel)}");

            if (string.IsNullOrWhiteSpace(authCode))
                MessageBox.Show($"授权码不能为空{nameof(authCode)}");

            string paywCode = "";

            if (payChannel == "支付宝")
            {
                paywCode = "ALIPAY"; //ALIPAY，WECHAT
            }

            if (payChannel == "微信")
            {
                paywCode = "WECHAT"; //ALIPAY，WECHAT
            }

            var payInfo = new JObject
            {
                
                ["paywCode"] = paywCode,
                ["authcode"] = authCode
            };

            var result = JsonHelper.setIrisReturnValue(
                 0,
                 "结算成功",
                 new JObject { ["payInfo"] = payInfo }
            );

            return result.ToString(Formatting.None); // 紧凑格式，符合接口规范
        }

        ///查询一码付状态
        public int QuerySignedPayStatus(out string msg)
        {
            var request = new QuerySignedPayStatusRequest
            {
                token = Global.pat.ecToken,      // 电子凭证令牌（模拟值）
                orgCodg = Global.inf.hospitalNO,               // 定点医药机构代码（示例医保编码）
                orgName = Global.inf.hospitalName,             // 机构名称（中文支持）
                opterId = Global.user.ID,                      // 经办人员编号
                opterName = Global.user.name,                       // 经办人姓名
                devId = Global.curEvt.mac,        // 设备唯一标识（如 MAC 地址或 UUID）
                devIP = Global.curEvt.ip                   // 设备 IP 地址
            };
            string jsonStr = JsonConvert.SerializeObject(request, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });//紧凑格式
            JObject joRtn = invoker.invokeOneCodePayService("QuerySignedPayStatus", jsonStr);
            if (JsonHelper.parseOneCodePayRtnValue(joRtn, out msg) != 0)
            {
                return -1;
            }
            else
            {
                msg = OneCodePayEncryptUtil.decrypt(JsonHelper.getDestValue(joRtn, "data.encData"), Global.inf.oneCodePay.businessSystemKey);
                Global.writeLog("QuerySignedPayStatus(明文)",jsonStr,msg);
                return 0;
            }
            
        }

        //获取一码付凭证
        public int GetPayCert(decimal cashPay,out string msg)
        {
            var request = new GetPayCertRequest
            {
                token = Global.pat.ecToken,      // 电子凭证令牌（模拟值）
                ownPaySetlAmt = cashPay.ToString("0.00"),          //现金支付金额
                orgCodg = Global.inf.hospitalNO,               // 定点医药机构代码（示例医保编码）
                orgName = Global.inf.hospitalName,             // 机构名称（中文支持）
                opterId = Global.user.ID,                      // 经办人员编号
                opterName = Global.user.name,                       // 经办人姓名
                devId = Global.curEvt.mac,        // 设备唯一标识（如 MAC 地址或 UUID）
                devIP = Global.curEvt.ip,                   // 设备 IP 地址
                fixmedinsTrnsSn = Global.pat.recordID  //医疗机构交易流水号
            };
            string jsonStr = JsonConvert.SerializeObject(request, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });//紧凑格式
            JObject joRtn = invoker.invokeOneCodePayService("GetPayCert", jsonStr);
            if (JsonHelper.parseOneCodePayRtnValue(joRtn, out msg) != 0)
            {
                return -1;
            }
            else
            {
                msg = OneCodePayEncryptUtil.decrypt(JsonHelper.getDestValue(joRtn, "data.encData"), Global.inf.oneCodePay.businessSystemKey);
                Global.writeLog("GetPayCert(明文)", jsonStr, msg);
                return 0;
            }

        }

        //按照HIS约定返回给前端，前端根据返回结果调用

    }


    /// <summary>
    /// 查询用户一码付状态 - 请求参数
    /// </summary>
    public class QuerySignedPayStatusRequest:EntityBase
    {
        /// <summary>
        /// 电子凭证令牌
        /// </summary>
        [Column(Name = "token", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("电子凭证令牌")]
        public string token { get; set; }

        /// <summary>
        /// 定点医药机构代码
        /// </summary>
        [Column(Name = "orgCodg", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("定点医药机构代码")]
        public string orgCodg { get; set; }

        /// <summary>
        /// 定点医药机构名称
        /// </summary>
        [Column(Name = "orgName", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("定点医药机构名称")]
        public string orgName { get; set; }

        /// <summary>
        /// 经办人员编号
        /// </summary>
        [Column(Name = "opterId", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("经办人员编号")]
        public string opterId { get; set; }

        /// <summary>
        /// 经办人员姓名
        /// </summary>
        [Column(Name = "opterName", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("经办人员姓名")]
        public string opterName { get; set; }

        /// <summary>
        /// 设备唯一标识
        /// </summary>
        [Column(Name = "devId", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("设备唯一标识")]
        public string devId { get; set; }

        /// <summary>
        /// 设备网络IP
        /// </summary>
        [Column(Name = "devIP", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("设备网络IP")]
        public string devIP { get; set; }
    }

    /// <summary>
    /// 查询用户一码付状态 - 响应结果
    /// </summary>
    public class QuerySignedPayStatusResponse : EntityBase
    {
        /// <summary>
        /// 状态标识
        /// 0-未签约不可用，1-已签约且可用，2-已签约不可用
        /// </summary>
        [Column(Name = "stasFlag", DbType = "VARCHAR2(3)", CanBeNull = false)]
        [StringLength(3)]
        [DisplayName("状态标识")]
        public string stasFlag { get; set; }

        /// <summary>
        /// 不可用原因
        /// 状态异常原因描述，可用于定点医药机构侧识别及展示
        /// </summary>
        [Column(Name = "abnRea", DbType = "VARCHAR2(200)", CanBeNull = true)]
        [StringLength(200)]
        [DisplayName("不可用原因")]
        public string abnRea { get; set; }

        /// <summary>
        /// 支付渠道用户账号名
        /// 支付渠道自定义，可用于定点医药机构侧识别及展示
        /// </summary>
        [Column(Name = "payChnlUserName", DbType = "VARCHAR2(40)", CanBeNull = true)]
        [StringLength(40)]
        [DisplayName("支付渠道用户账号名")]
        public string payChnlUserName { get; set; }

        /// <summary>
        /// 支付渠道名称
        /// 可用于定点医药机构侧识别支付渠道
        /// </summary>
        [Column(Name = "payChnlName", DbType = "VARCHAR2(40)", CanBeNull = true)]
        [StringLength(40)]
        [DisplayName("支付渠道名称")]
        public string payChnlName { get; set; }
    }
    /// <summary>
    /// 获取一码付付款凭据请求
    /// </summary>
    public class GetPayCertRequest : EntityBase
    {
        /// <summary>
        /// 电子凭证令牌
        /// </summary>
        [Column(Name = "token", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("电子凭证令牌")]
        public string token { get; set; }

        /// <summary>
        /// 现金支付金额
        /// </summary>
        [Column(Name = "ownPaySetlAmt", DbType = "VARCHAR2(20)", CanBeNull = false)]
        [StringLength(20)]
        [DisplayName("现金支付金额")]
        public string ownPaySetlAmt { get; set; }

        /// <summary>
        /// 定点医药机构代码
        /// </summary>
        [Column(Name = "orgCodg", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("定点医药机构代码")]
        public string orgCodg { get; set; }

        /// <summary>
        /// 定点医药机构名称
        /// </summary>
        [Column(Name = "orgName", DbType = "VARCHAR2(200)", CanBeNull = false)]
        [StringLength(200)]
        [DisplayName("定点医药机构名称")]
        public string orgName { get; set; }

        /// <summary>
        /// 经办人员编号
        /// </summary>
        [Column(Name = "opterId", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("经办人员编号")]
        public string opterId { get; set; }

        /// <summary>
        /// 经办人员姓名
        /// </summary>
        [Column(Name = "opterName", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("经办人员姓名")]
        public string opterName { get; set; }

        /// <summary>
        /// 设备唯一标识
        /// </summary>
        [Column(Name = "devid", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("设备唯一标识")]
        public string devId { get; set; }

        /// <summary>
        /// 设备网络IP
        /// </summary>
        [Column(Name = "devIP", DbType = "VARCHAR2(40)", CanBeNull = false)]
        [StringLength(40)]
        [DisplayName("设备网络IP")]
        public string devIP { get; set; }

        /// <summary>
        /// 定点医药机构交易流水号
        /// </summary>
        [Column(Name = "fixmedinsTrnsSn", DbType = "VARCHAR2(200)", CanBeNull = false)]
        [StringLength(200)]
        [DisplayName("定点医药机构交易流水号")]
        public string fixmedinsTrnsSn { get; set; }
    }

    /// <summary>
    /// 获取一码付付款凭据响应
    /// </summary>
    public class GetPayCertResponse:EntityBase
    {
        /// <summary>
        /// 付款凭据
        /// </summary>
        [Column(Name = "payCert", DbType = "VARCHAR2(2000)", CanBeNull = false)]
        [StringLength(2000)]
        [DisplayName("付款凭据")]
        public string payCert { get; set; }

        /// <summary>
        /// 支付渠道用户账号名
        /// </summary>
        [Column(Name = "payChnlUserName", DbType = "VARCHAR2(400)", CanBeNull = true)]
        [StringLength(400)]
        [DisplayName("支付渠道用户账号名")]
        public string payChnlUserName { get; set; }

        /// <summary>
        /// 支付渠道名称
        /// </summary>
        [Column(Name = "payChnlName", DbType = "VARCHAR2(400)", CanBeNull = true)]
        [StringLength(400)]
        [DisplayName("支付渠道名称")]
        public string payChnlName { get; set; }
    }

}
