using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
using System.Web;
using MySystem.Models.Main;
using LitJson;
using Library;
using System.Data;
using MySystem.Service.Main;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class ConsumerOrdersController : BaseController
    {
        public ConsumerOrdersController(IHttpContextAccessor accessor) : base(accessor)
        {
        }

        #region 消费者-支付接口
        // [Authorize]
        public JsonResult Pay(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(Request.Body);
                value = sr.ReadToEnd();
                value = value.Split('=')[1];
            }
            // value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            JsonData data = JsonMapper.ToObject(value);
            string SnNo = data.getItem("Sn").ToString(); //商户
            string Machine = data.getItem("Machine").ToString();
            int PayMode = int.Parse(function.CheckInt(data.getItem("PayMode").ToString())); //支付方式(1 支付宝 2 微信)
            decimal PayMoney = decimal.Parse(function.CheckNum(data.getItem("PayMoney").ToString())); //支付金额
            string Code = data.getItem("Code").ToString();
            if (string.IsNullOrEmpty(data["PayMode"].ToString()))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "请填写支付方式" });
            }
            if (string.IsNullOrEmpty(data["PayMoney"].ToString()))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "请填写支付金额" });
            }
            if (!function.IsNum(data["PayMoney"].ToString()))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "请填写正确的支付金额" });
            }
            if (SnNo.Length > 20)
            {
                // SnNo = System.Web.HttpUtility.UrlDecode(SnNo);
                if (!SnNo.EndsWith("="))
                {
                    SnNo += "=";
                }
                SnNo = dbconn.Decrypt3DES(SnNo, "l2k0b2#3");
                SnNo = SnNo.TrimEnd('\0');
                SnNo = SnNo.Substring(0, 20);
            }
            if (!string.IsNullOrEmpty(Machine))
            {
                if (Machine.Length > 20)
                {
                    // Machine = System.Web.HttpUtility.UrlDecode(Machine);
                    if (!Machine.EndsWith("="))
                    {
                        Machine += "=";
                    }
                    Machine = dbconn.Decrypt3DES(Machine, "l2k0b2#3");
                    Machine = Machine.TrimEnd('\0');
                    Machine = Machine.Substring(0, 20);
                }
            }
            int MerchantId = 0;
            if (Machine == SnNo)
            {
                var qrcode = MerchantQrCodeService.Query(" SnNo='" + SnNo + "'");
                MerchantId = qrcode.MerchantId;
            }
            else
            {
                var machine = PosMachinesService.Query(" PosSn='" + SnNo + "'");
                MerchantId = machine.BindMerchantId;
            }
            var merchant = MerchantInfoService.Query(MerchantId);
            var merchantAdd = MerchantAddInfoService.Query(MerchantId);
            var merchantset = MerchantParamSetService.Query(MerchantId);
            string openid = "";
            //商户未激活也能支付(365服务费)
            // if (merchant.IsAct == 0)
            // {
            //     return Json(new AppResultJson() { Status = "-1", Info = "支付失败，商户尚未激活，请前往来客吧商户版激活后使用" });
            // }
            if (PayMode == 1)
            {
                openid = new AlipayFunction(_accessor.HttpContext).GetAlipayUserId(Code);
                if (openid.Contains("|"))
                {
                    openid = openid.Split('|')[0];
                }
            }
            else
            {
                string result = function.GetWebRequest("https://api.weixin.qq.com/sns/jscode2session?appid=" + new WeChatFunction().AppId + "&secret=" + new WeChatFunction().AppSecret + "&js_code=" + Code + "&grant_type=authorization_code");
                function.WriteLog(DateTime.Now.ToString() + "\n" + result, "微信小程序获取openid");
                JsonData jsonObj = JsonMapper.ToObject(result);
                openid = jsonObj["openid"].ToString();
            }
            int ConsumerId = 0;
            // var check = ConsumerOpenIdsService.Exist(openid);
            var check = ConsumersService.Exist(openid);
            if (check == false)
            {
                var info = ConsumersUtil.AddConsumers(ConsumerId, openid);
                ConsumerId = int.Parse(info.Data.ToString());
                // ConsumerOpenIdsUtil.AddConsumerOpenIds(ConsumerId, openid);
            }
            else
            {
                // var info = ConsumerOpenIdsService.Query(" OpenId='" + openid + "'");
                // ConsumerId = info.ConsumerId;
                var info = ConsumersService.Query(" WechatOpenId='" + openid + "'");
                ConsumerId = info.Id;
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
            bool ActFlag = merchantset.IsAll == 1 ? false : true;
            if (PayMoney < merchantset.MinPayMoney) //支付金额小于活动最小金额，则不分账
            {
                ActFlag = false;
            }
            if (merchant.IsAct == 0) ActFlag = false;
            var ledgerModel = ActFlag ? "5" : "1";

            var infos = ConsumerOrdersUtil.AddConsumerOrders(MerchantId, ConsumerId, merchant.UserId, PayMode, PayMoney, SnNo, OrderNo, ActFlag ? (PayMoney * 0.99M) * merchantset.DiviPercent / 100 : 0, ActFlag ? 1u : 0u, ActFlag ? PayMoney * merchantset.GetPercent / 100 : PayMoney, Newtonsoft.Json.JsonConvert.SerializeObject(merchantset), merchantset.Version);
            ConsumerOrderForNoUtil.AddConsumerOrderForNo(OrderNo, int.Parse(infos.Data.ToString()));
            if (PayMode == 1)
            {
                string backString = HaoDaHelper.Instance.Alipay(merchantAdd.OutMchtNo, merchantAdd.StoreNo, OrderNo, PayMoney, SpHost + "/api/alipay/hdnotice", openid, function.get_Random(4), ledgerModel, merchant.BrandId);
                JsonData obj = JsonMapper.ToObject(backString);
                if (obj["resultCode"].ToString() == "1")
                {
                    string tradeNo = obj["prePayId"].ToString();
                    Obj.Add("respCode", obj["resultCode"].ToString());
                    Obj.Add("tradeNo", tradeNo);
                }
                else if (obj["resultCode"].ToString() == "0" && obj["errorCode"].ToString().Contains("OL-6"))
                {
                    return Json(new AppResultJson() { Status = "-1", Info = "错误码：FK011", Data = Obj });
                }
                else
                {
                    Obj.Add("respCode", obj["resultCode"].ToString());
                    Obj.Add("tradeNo", "");
                    return Json(new AppResultJson() { Status = "-1", Info = obj["errorDesc"].ToString(), Data = Obj });
                }
            }
            else if (PayMode == 2)
            {
                var dic = JsonMapper.ToObject(HaoDaHelper.Instance.WeChatPay(merchantAdd.OutMchtNo, merchantAdd.StoreNo, OrderNo, PayMoney, SpHost + "/api/wechat/hdnotice", openid, function.get_Random(4), AppConfig.WeChat.AppId, "MINI_PROGRAM", ledgerModel, merchant.BrandId));
                if (dic["resultCode"].ToString() == "1")
                {
                    Obj.Add("appId", dic["payInfo"]["appId"].ToString()); //微信小程序appid
                    Obj.Add("timeStamp", dic["payInfo"]["timeStamp"].ToString()); //时间戳
                    Obj.Add("nonceStr", dic["payInfo"]["nonceStr"].ToString()); //随机字符串
                    Obj.Add("package", dic["payInfo"]["wxPackage"].ToString()); //统一支付接口返回的prepayid参数值
                    Obj.Add("paySign", dic["payInfo"]["paySign"].ToString()); //支付签名
                    Obj.Add("ConsumerId", ConsumerId);
                }
                else if (dic["resultCode"].ToString() == "0" && dic["errorCode"].ToString().Contains("OL-6"))
                {
                    return Json(new AppResultJson() { Status = "-1", Info = "错误码：FK011", Data = Obj });
                }
                else
                {
                    Obj.Add("respCode", dic["resultCode"].ToString());
                    Obj.Add("tradeNo", "");
                    return Json(new AppResultJson() { Status = "-1", Info = dic["errorDesc"].ToString(), Data = Obj });
                }
            }
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion



        #region 经营数据-统计数据-经营详情-取消返现
        // [Authorize]
        public JsonResult CancelDivi(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = CancelDiviDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson CancelDiviDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["id"].ToString()));
            ConsumerOrders order = maindb.ConsumerOrders.FirstOrDefault(m => m.Id == Id) ?? new ConsumerOrders();
            if (order.Id > 0)
            {
                List<ConsumerOrders> suborders = RedisDbconn.Instance.GetList<ConsumerOrders>("ConsumerOrdersHd:Divi:" + order.PayMode + ":" + order.MerchantId, 1, 999999);
                if (suborders.Count > 0)
                {
                    ConsumerOrders suborder = suborders.FirstOrDefault(m => m.Id == Id);
                    if (suborder != null)
                    {
                        order.CurDivi = suborder.CurDivi;
                        maindb.SaveChanges();
                        RedisDbconn.Instance.RemoveFromList("ConsumerOrdersHd:Divi:" + order.PayMode + ":" + order.MerchantId, suborder);
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + "订单Id：" + suborder.Id + "\r\n\r\n", "银联订单取消返现");
                        order.ReturnFlag = 0;
                        maindb.SaveChanges();
                        return new AppResultJson() { Status = "1", Info = "", Data = Obj };
                    }
                }
            }
            else
            {
                return new AppResultJson() { Status = "-1", Info = "取消失败", Data = Obj };
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion

        #region 经营数据-统计数据-经营详情-恢复返现
        // [Authorize]
        public JsonResult RestoreDivi(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = RestoreDiviDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson RestoreDiviDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["id"].ToString()));
            ConsumerOrders order = maindb.ConsumerOrders.FirstOrDefault(m => m.Id == Id) ?? new ConsumerOrders();
            if (order.Id > 0)
            {
                JsonData ProfitInfo = JsonMapper.ToObject(order.SeoDescription);
                int ProfitDays = int.Parse(function.CheckInt(ProfitInfo["ProfitDays"].ToString())); //活动有效时间
                if (order.IsAct == 0) return new AppResultJson() { Status = "-1", Info = "恢复失败，非活动订单不能进行该操作", Data = Obj };
                if (DateTime.Parse(order.UpdateDate.ToString()).AddMinutes(10) >= DateTime.Now) return new AppResultJson() { Status = "-1", Info = "恢复失败，订单完成支付10分钟内不能进行该操作", Data = Obj };
                if (order.MaxDivi == order.CurDivi) return new AppResultJson() { Status = "-1", Info = "恢复失败，订单已完成所有返现", Data = Obj };
                if (DateTime.Parse(order.UpdateDate.ToString()).AddDays(ProfitDays) < DateTime.Now) return new AppResultJson() { Status = "-1", Info = "恢复失败，非活动订单不能进行该操作", Data = Obj };
                List<ConsumerOrders> suborders = RedisDbconn.Instance.GetList<ConsumerOrders>("ConsumerOrdersHd:Divi:" + order.PayMode + ":" + order.MerchantId);
                if (suborders.Count > 0)
                {
                    ConsumerOrders suborder = suborders.FirstOrDefault(m => m.Id == Id);
                    if (suborder == null)
                    {
                        RedisDbconn.Instance.AddRightList("ConsumerOrdersHd:Divi:" + order.PayMode + ":" + order.MerchantId, order);
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + "订单Id：" + Id + "\r\n\r\n", "银联订单恢复返现");
                        order.ReturnFlag = 1;
                        maindb.SaveChanges();
                    }
                    return new AppResultJson() { Status = "1", Info = "", Data = Obj };
                }
            }
            else
            {
                return new AppResultJson() { Status = "-1", Info = "恢复失败", Data = Obj };
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion

    }
}
