using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MySystem.Models;
using Library;

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 IActionResult Error()
        {
            string isapi = Request.Headers["Api"].ToString();
            if (isapi != "1")
            {
                if (Response.StatusCode == 500)
                {
                    return Redirect("/public/errpage/pc/500.html");
                }
                else if (Response.StatusCode == 502)
                {
                    return Redirect("/public/errpage/pc/502.html");
                }
                else if (Response.StatusCode == 404)
                {
                    return Redirect("/public/errpage/pc/404.html");
                }
            }
            return View();
        }



        // 推荐王奖励
        public string InvitePrize666(string month)
        {
            DateTime start = DateTime.Parse(month + "-01 00:00:00");
            DateTime end = start.AddMonths(1);
            string TradeMonth = start.ToString("yyyyMM");
            WebCMSEntities db = new WebCMSEntities();
            //判断当月是否下单
            bool checkOrder = db.Orders.Any(m => m.PayDate >= start && m.PayDate < end && m.Status > 0 && m.TotalPrice == 66);
            if(checkOrder)
            {
                //统计当月下单名单
                List<int> uids = db.Orders.Where(m => m.PayDate >= start && m.PayDate < end && m.Status > 0 && m.TotalPrice == 66).ToList().Select(m => m.UserId).Distinct().ToList();
                foreach(int uid in uids)
                {
                    decimal tradeAmt = 0; //机具总交易额
                    int actPosCount = 0; //激活机具数量
                    //查询当前创客所属机具
                    var posList = db.PosMachinesTwo.Select(m => new { m.ActivationState, m.ActivationTime, m.BuyUserId, m.BindMerchantId }).Where(m => m.BuyUserId == uid && m.ActivationState == 1 && m.ActivationTime >= start && m.ActivationTime < end).ToList();
                    if(posList.Count > 0)
                    {
                        actPosCount = posList.Count;
                        foreach(var pos in posList)
                        {
                            //查询机具交易额
                            bool checkTrade = db.PosMerchantTradeSummay.Any(m => m.MerchantId == pos.BindMerchantId && m.TradeMonth == TradeMonth);
                            if(checkTrade)
                            {
                                tradeAmt = db.PosMerchantTradeSummay.Where(m => m.MerchantId == pos.BindMerchantId && m.TradeMonth == TradeMonth).Sum(m => m.TradeAmount);                     
                            }
                        }
                    }
                }
            }
            db.Dispose();
            return "";
        }

        // 创客达标返600
        public string shopOrder()
        {
            string html = "<table>";
            WebCMSEntities db = new WebCMSEntities();
            OtherMySqlConn.connstr = "server=47.108.231.170;port=3306;user=KxsMain;password=mzeqjriUWore0dwT;database=KxsMainServer;charset=utf8;ConnectionTimeout=600;DefaultCommandTimeout=600;";
            DataTable pos = OtherMySqlConn.dtable("select");
            // DataTable dt = OtherMySqlConn.dtable("select BuyUserId,count(Id) from PosMachinesTwo where BuyUserId in (select DISTINCT UserId from Orders where TotalPrice=600 and `Status`>0 and CreateDate<'2022-07-01 00:00:00') and ActivationState=1 and ActivationTime<'2022-07-01 00:00:00' group by BuyUserId HAVING count(Id)>=20");
            DataTable dt = OtherMySqlConn.dtable("select BuyUserId,count(Id) from PosMachinesTwo where ActivationState=1 and ActivationTime<'2022-07-01 00:00:00' and BuyUserId in (69542,124745) group by BuyUserId HAVING count(Id)>=20");
            foreach(DataRow dr in dt.Rows)
            {
                int BuyUserId = int.Parse(dr["BuyUserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == BuyUserId) ?? new Users();
                int ActCount = int.Parse(dr[1].ToString());
                decimal TradeAmount = 0;
                DataTable dtTrade = OtherMySqlConn.dtable("select sum(TradeAmount) from PosMerchantTradeSummay where TradeMonth='202206' and MerchantId in (select DISTINCT BindMerchantId from PosMachinesTwo where BuyUserId=" + BuyUserId + " and ActivationState=1 and ActivationTime<'2022-07-01 00:00:00')");
                if(dtTrade.Rows.Count > 0)
                {
                    TradeAmount = decimal.Parse(function.CheckNum(dtTrade.Rows[0][0].ToString()));
                }
                decimal AvgTradeAmount = TradeAmount / ActCount;
                string Result = "未达标";
                if(AvgTradeAmount >= 30000)
                {
                    Result = "达标";
                }
                html += "<tr>";
                html += "<td>" + user.MakerCode + "</td>";
                html += "<td>" + user.RealName + "</td>";
                html += "<td>" + ActCount + "</td>";
                html += "<td>" + TradeAmount + "</td>";
                html += "<td>" + AvgTradeAmount.ToString("f2") + "</td>";
                html += "<td>" + Result + "</td>";
                html += "</tr>";
            }
            html += "</table>";
            db.Dispose();
            return html;
        }
    
    

        
    }
}