using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Enums.OP;
using APT.CMS.Domain.Entities.SO;
using APT.CMS.Domain.Enums.FC;
using APT.CMS.Domain.Enums.SO;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace APT.OP.WebApi.Controllers.Api
{
    [Route("api/OP/WeiXin")]
    public class WeiXinController : APTApiController<T_OP_CLIENT>
    {
        /// <summary>
        /// 付款回调
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("Notify")]
        public async Task<IActionResult> Notify()
        {
            String xmlData = getPostStr();
            //保存付款成功过来的数据
            LoggerManager.GetLogger().Info("GXL", xmlData);
            PayResult(xmlData);
            return Content("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>", "text/xml");
        }



        [HttpPost("CancelNotify")]
        /// <summary>
        /// 付款返回的数据
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> CancelNotify()
        {
            String xmlData = getPostStr();
            //保存付款成功过来的数据
            LoggerManager.GetLogger().Info("GXL", xmlData);
            CancelResult(xmlData);
            return Content("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>", "text/xml");
        }

        //获得Post过来的数据  
        public string getPostStr()
        {
            //Int32 intLen = Convert.ToInt32(System.Web.HttpContext.Current.Request.InputStream.Length);
            //byte[] b = new byte[intLen];
            //System.Web.HttpContext.Current.Request.InputStream.Read(b, 0, intLen);
            Request.EnableBuffering();
            using (Stream stream = Request.Body)
            {
                byte[] buffer = new byte[Request.ContentLength.Value];
                stream.Read(buffer, 0, buffer.Length);
                string content = Encoding.UTF8.GetString(buffer);
                return content;
            }
        }
        /// <summary>
        /// 付款结果处理
        /// </summary>
        public void PayResult(string ResultMsg)
        {
            if (!string.IsNullOrEmpty(ResultMsg))
            {
                LoggerManager.GetLogger().Info("收到回调数据1:" + ResultMsg);
                var xml = new XmlDocument();
                xml.LoadXml(ResultMsg);
                //处理返回的值
                DataSet ds = new DataSet();
                StringReader stram = new StringReader(ResultMsg);
                XmlTextReader reader = new XmlTextReader(stram);
                ds.ReadXml(reader);
                string return_code = ds.Tables[0].Rows[0]["return_code"].ToString();
                if (return_code.ToUpper() == "SUCCESS")
                {
                    //通信成功  
                    string result_code = ds.Tables[0].Rows[0]["result_code"].ToString();//业务结果  
                    if (result_code.ToUpper() == "SUCCESS")
                    {
                        string appid = ds.Tables[0].Rows[0]["appid"].ToString();
                        //string attach = ds.Tables[0].Rows[0]["attach"].ToString();
                        string mch_id = ds.Tables[0].Rows[0]["mch_id"].ToString();
                        string openid = ds.Tables[0].Rows[0]["openid"].ToString();
                        string orderid = ds.Tables[0].Rows[0]["out_trade_no"].ToString();
                        Int32 total_fee = Convert.ToInt32(ds.Tables[0].Rows[0]["total_fee"].ToString());
                        string transaction_id = ds.Tables[0].Rows[0]["transaction_id"].ToString();
                        LoggerManager.GetLogger().Info("付款成功:小程序appID:" + appid + ",商户号:" + mch_id +
                            ",支付人:" + openid + ",付款金额:" + total_fee + ",商户交易号:" + transaction_id);

                        //var gOrder = orderid.Substring(0, 8) + "-" + orderid.Substring(8, 4) + "-" + orderid.Substring(12, 4) + "-" + orderid.Substring(16, 4) + "-" + orderid.Substring(20);
                        var orderAry = orderid.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                        //var orderId = new Guid(gOrder);
                        //var order = this.GetEntity<T_FM_SALE_ORDER>(i => i.CODE == orderAry[0], "Nav_ClinetOpen.NavClient",
                        //    "Nav_Orders.Nav_Details.Nav_Stock.Nav_HotelRoomTypeDetail.Nav_HotelRoomType",
                        //    "Nav_Orders.Nav_Details.Nav_Stock.Nav_HotelRoomTypeDetail.Nav_Hotel");                       
                        if (orderAry[2] == "DK")//电卡订单
                        {
                            BaseFilter filter = new BaseFilter();
                            filter.IgnoreOrgRule = true;
                            filter.IsMultipleDb = true;
                            var order = this.GetEntity<T_SO_RECHARGE_ORDER>(i => i.CODE == orderAry[0], filter, "Nav_RechargeCard");
                            if (order == null)
                                LoggerManager.GetLogger().Error("订单不存在:" + order);
                            order.ORDER_STATUS = (int)OPRechargeOrderStatus.成功;
                            if (order.Nav_RechargeCard != null)
                            {
                                var rechargeCard = order.Nav_RechargeCard;
                                rechargeCard.BALANCE += order.AMOUNT;
                                this.UpdateEntityByConn(order, order.DbConn,"ORDER_STATUS");
                                this.UpdateEntityByConn(rechargeCard, order.DbConn, "BALANCE");
                                LoggerManager.GetLogger().Info("充值成功" + order.CODE);
                            }
                            else
                            {
                                order.ORDER_STATUS = (int)OPRechargeOrderStatus.失败;
                                this.UpdateEntityByConn(order, order.DbConn, "ORDER_STATUS");
                                LoggerManager.GetLogger().Error("微信充值成功,电卡金额未更新:" + ResultMsg);
                            }
                        }
                        else//微信直接支付
                        {
                            BaseFilter filter = new BaseFilter();
                            filter.IgnoreOrgRule = true;
                            filter.IsMultipleDb = true;
                            var order = this.GetEntity<T_SO_CHARGING_ORDER>(x => x.CODE == orderAry[0], filter);//查询订单
                            order.PAY_TYPE = (int)FCPayType.微信支付;
                            order.ORDER_STATUS = (int)FCOrderStatus.已付款;
                            this.UpdateEntityByConn(order, order.DbConn);//更新订单状态
                        }
                    }
                    else
                    {
                        LoggerManager.GetLogger().Error("支付失败:" + ResultMsg);
                    }
                }
                else
                {
                    LoggerManager.GetLogger().Error("支付失败:" + ResultMsg);
                }
            }
        }

        /// <summary>
        /// 付款结果处理
        /// </summary>
        public void CancelResult(string ResultMsg)
        {
            if (!string.IsNullOrEmpty(ResultMsg))
            {
                LoggerManager.GetLogger().Info("收到回调数据:" + ResultMsg);
                var xml = new XmlDocument();
                xml.LoadXml(ResultMsg);
                //处理返回的值
                DataSet ds = new DataSet();
                StringReader stram = new StringReader(ResultMsg);
                XmlTextReader reader = new XmlTextReader(stram);
                ds.ReadXml(reader);
                string return_code = ds.Tables[0].Rows[0]["return_code"].ToString();
                if (return_code.ToUpper() == "SUCCESS")
                {
                    //通信成功  
                    string appid = ds.Tables[0].Rows[0]["appid"].ToString();
                    //string attach = ds.Tables[0].Rows[0]["attach"].ToString();
                    string mch_id = ds.Tables[0].Rows[0]["mch_id"].ToString();
                    string reqInfo = ds.Tables[0].Rows[0]["req_info"].ToString();
                    //
                    var tenant = this.GetEntity<T_OP_TENANT>(x => x.MCH_ID == mch_id);//查找运营商
                    //解密reqInfo
                    string dReqInfo = DecodeReqInfoByTenant(reqInfo, tenant.WXPAYKEY);
                    if (dReqInfo == null)
                    {
                        LoggerManager.GetLogger().Error("解密失败");
                        return;
                    }
                    LoggerManager.GetLogger().Info(reqInfo);
                    DataSet dsReq = new DataSet();
                    StringReader stramReq = new StringReader(dReqInfo);
                    XmlTextReader readerReq = new XmlTextReader(stramReq);
                    dsReq.ReadXml(readerReq);

                    string orderid = dsReq.Tables[0].Rows[0]["out_trade_no"].ToString();
                    string refundCode = dsReq.Tables[0].Rows[0]["out_refund_no"].ToString();
                    Int32 total_fee = Convert.ToInt32(dsReq.Tables[0].Rows[0]["total_fee"].ToString());
                    Int32 refund_fee = Convert.ToInt32(dsReq.Tables[0].Rows[0]["refund_fee"].ToString());
                    string transaction_id = dsReq.Tables[0].Rows[0]["transaction_id"].ToString();
                    LoggerManager.GetLogger().Info("退款成功:小程序appID:" + appid + ",商户号:" + mch_id +
                         ",订单金额：" + total_fee + ",退款金额:" + refund_fee + ",商户交易号:" + transaction_id);

                    var orderAry = orderid.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                    var refundCodeAry = refundCode.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
                    if (orderAry[3] == "DK")//电卡订单
                    {
                        BaseFilter filter = new BaseFilter();
                        filter.IgnoreOrgRule = true;
                        filter.IsMultipleDb = true;
                        var refundOrder = this.GetEntity<T_SO_REFUND_ORDER>(i => i.CODE == refundCodeAry[0], filter);
                        if (refundOrder == null)
                            LoggerManager.GetLogger().Error("订单不存在:" + refundOrder);
                        refundOrder.REFUND_STATUS = (int)SORefundOrderStatus.退款成功;
                        var order = this.GetEntity<T_SO_RECHARGE_ORDER>(i => i.CODE == orderAry[0], filter, "Nav_RechargeCard");
                        if (order.Nav_RechargeCard != null)
                        {
                            var rechargeCard = order.Nav_RechargeCard;
                            rechargeCard.BALANCE -= refundOrder.REFUND_AMOUNT;//扣除电卡金额
                            this.UpdateEntityByConn(refundOrder, refundOrder.DbConn, "REFUND_STATUS");
                            this.UpdateEntityByConn(rechargeCard, refundOrder.DbConn, "BALANCE");
                            LoggerManager.GetLogger().Info("退款成功" + order.CODE);
                        }
                        else
                        {
                            refundOrder.REFUND_STATUS = (int)SORefundOrderStatus.退款失败;
                            this.UpdateEntityByConn(refundOrder, refundOrder.DbConn, "REFUND_STATUS");
                            LoggerManager.GetLogger().Error("微信退款成功,电卡金额未更新:" + ResultMsg);
                        }
                    }
                    else//微信直接支付
                    {
                        BaseFilter filter = new BaseFilter();
                        filter.IgnoreOrgRule = true;
                        filter.IsMultipleDb = true;
                        var refundOrder = this.GetEntity<T_SO_REFUND_ORDER>(i => i.CODE == refundCodeAry[0], filter);
                        if (refundOrder == null)
                            LoggerManager.GetLogger().Error("订单不存在:" + refundOrder);
                        refundOrder.REFUND_STATUS = (int)SORefundOrderStatus.退款成功;                    
                        this.UpdateEntityByConn(refundOrder, refundOrder.DbConn, "REFUND_STATUS");//更新订单状态
                    }
                }
                else
                {
                    LoggerManager.GetLogger().Error("退款成功:" + ResultMsg);
                }
            }
        }
        public static string DecodeReqInfo(string s)
        {
            string r = null;
            string key = GenerateMD5(LibUtils.ToString(ConfigurationManager.AppSettings["WxPayKey"])).ToLower();
            r = DecodeAES256ECB(s, key);
            return r;
        }
        public static string DecodeReqInfoByTenant(string s,string key)
        {
            string r = null;
            //string key = GenerateMD5(LibUtils.ToString(ConfigurationManager.AppSettings["WxPayKey"])).ToLower();
            r = DecodeAES256ECB(s, key);
            return r;
        }
        public static string DecodeAES256ECB(string s, string key)
        {
            string r = null;
            try
            {
                byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
                byte[] toEncryptArray = Convert.FromBase64String(s);
                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = rDel.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                r = UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception e)
            {
                LoggerManager.GetLogger().Error("解密异常:" + e.Message);
            }
            return r;
        }
        public static string GenerateMD5(string txt)
        {
            using (MD5 mi = MD5.Create())
            {
                byte[] buffer = Encoding.Default.GetBytes(txt);
                //开始加密
                byte[] newBuffer = mi.ComputeHash(buffer);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }

    }
}
