using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Library;
using LitJson;
using System.Data;
using MySystem.Models.Main;
using System.Text.RegularExpressions;
using Aop.Api.Domain;
using MySystem.Models;
using Microsoft.Extensions.Localization;

namespace MySystem.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public string getHdOrder()
        {
            GetHaoDaFTPInfoService.Instance.GetFTPDataInfoYesterday();
            return "ok";
        }

        public string partorder()
        {
            List<string> hdorders = new List<string>();
            WebCMSEntities db = new WebCMSEntities();
            var list = db.ConsumerOrders.Select(m => new { m.Id, m.SettleAmount, m.IsAct, m.SeoTitle }).Where(m => hdorders.Contains(m.SeoTitle) && m.IsAct == 1 && m.SettleAmount == 0).OrderBy(m => m.Id).ToList();
            foreach (var sub in list)
            {
                ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == sub.Id);
                if (order != null)
                {
                    int Status = 2;
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantInfo();
                    MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
                    if (order.IsAct == 1 && order.PayMoney >= set.MinPayMoney)
                    {
                        MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
                        
                        //获取结算金额
                        if(order.SettleAmount == 0)
                        {
                            string settleString = HaoDaHelper.Instance.QueryOrderDivideDetail(merchantAdd.OutMchtNo, order.SeoTitle);
                            JsonData jsonData = JsonMapper.ToObject(settleString);
                            if(jsonData["resultCode"].ToString() == "1")
                            {
                                string settleAmountString = jsonData["data"]["settleAmount"].ToString();
                                order.SettleAmount = int.Parse(settleAmountString);
                            }
                        }

                        //发起分账
                        decimal fee = order.PayMoney;
                        if (fee >= 1 && order.SettleAmount > 0)
                        {
                            string applyNo = "FZ" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8); //批次号
                            string mchtNo = merchantAdd.OutMchtNo; //慧掌柜商户号
                            string orderNo = order.SeoTitle; //交易订单号（好哒平台订单号，G开头）
                            string acctNo = AppConfig.Haoda.AcctNo; //账户号，分账接收方账户号
                            string sacctNo = merchantAdd.MchtNo; //账户号，收款商户号
                            string acctType = "0"; //账户类型（0：商户收款账户（大B），1：分账接收方账户（小B））

                            decimal settleAmount = (decimal)order.SettleAmount / 100M;
                            decimal divideAmt = (1 - 0.0038M) * order.PayMoney;
                            divideAmt = decimal.Parse(divideAmt.ToString("f2"));
                            decimal hdfee = 0.0038M * order.PayMoney * (1 - set.GetPercent / 100 - 0.01M);
                            hdfee = decimal.Parse(hdfee.ToString("f2"));
                            decimal servicefee = 0.01M * order.PayMoney - hdfee;
                            servicefee = decimal.Parse(servicefee.ToString("f2"));
                            decimal amount = order.PayMoney * (1 - 0.0038M) - servicefee;
                            amount = decimal.Parse(amount.ToString("f2"));
                            decimal otherAmt = settleAmount - servicefee - amount;
                            if (otherAmt != 0)
                            {
                                amount += otherAmt;
                            }

                            amount = amount * 100; //金额（分）
                            servicefee = servicefee * 100;
                            string seviceAmount = servicefee.ToString("f0"); //服务费
                            string amountAmount = amount.ToString("f0");
                            string result = HaoDaHelper.Instance.OrderDivideAccounts(OrderDivideAccountsUtil.AddValue(applyNo, mchtNo, orderNo, acctNo, sacctNo, acctType, amountAmount, seviceAmount), merchantAdd.BrandId);
                            order.DivideLog = "请求分账日志：" + result;
                            order.TradePayNo = applyNo;
                            if (result.Contains("\"resultCode\":\"0\"") && (result.Contains("分账金额不足") || result.Contains("不存在")))
                            {
                                Status = 1;
                            }
                        }
                    }
                    order.Status = Status;
                    if (Status == 2)
                    {
                        order.DivideFlag = 1;
                        order.DivideDate = DateTime.Now;
                    }
                }
            }
            db.SaveChanges();
            db.Dispose();

            return "ok";
        }

        public string addreturn()
        {
            List<int> ids = new List<int>();
            foreach(int id in ids)
            {
                RedisDbconn.Instance.AddList("ConsumerOrdersHd:Divi:2:List", id.ToString());
            }
            return "ok";
        }

        public string test()
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo merchantadd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == 5660) ?? new MerchantAddInfo();
            SortedList<string, string> obj = new SortedList<string, string>();
            obj.Add("bind_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            obj.Add("merch_no", merchantadd.MchtNo);
            obj.Add("name", merchantadd.CertMerchantName);
            string IdCardNumber = merchantadd.IdCardNumber;
            if(!string.IsNullOrEmpty(IdCardNumber))
            {
                IdCardNumber = IdCardNumber.Substring(0, 6) + "**********" + IdCardNumber.Substring(IdCardNumber.Length - 4);
            }
            obj.Add("supplement_info", IdCardNumber);
            obj.Add("mobile", merchantadd.MobilePhone);
            obj.Add("maker_code", "C00000001");
            PushHelper.Instance.Do(obj);
            db.Dispose();
            return "ok";
        }

    }
}