using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
using MySystem.MainModels;
using LitJson;
using Library;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class MerchantInfoController : BaseController
    {
        public MerchantInfoController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }





        #region 首页-快联盟产品-我的业绩-团队业绩-商户列表
        [Authorize]
        public JsonResult TeamPerformanceMerchants(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = TeamPerformanceMerchantsDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> TeamPerformanceMerchantsDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            List<int> query = MerchantInfoDbconn.Instance.GetList(UserId, PageNum, PageSize);
            foreach (int id in query)
            {
                MerchantInfo subdata = MerchantInfoDbconn.Instance.Get(id) ?? new MerchantInfo();
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("MerchantName", subdata.Name); //商户姓名
                curData.Add("Id", subdata.Id); //Id
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion




        #region 创客-首页-商户签约
        [Authorize]
        public JsonResult ContractList(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = ContractListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> ContractListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客
            string Status = data["Status"].ToString(); //签约状态
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            List<int> query = MerchantInfoDbconn.Instance.GetList(UserId, PageNum, PageSize);
            foreach (var id in query)
            {
                MerchantInfo subdata = MerchantInfoDbconn.Instance.Get(id) ?? new MerchantInfo();
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("Name", subdata.Name); //名称
                curData.Add("Id", subdata.Id); //Id
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                curData.Add("Status", ""); //签约状态
                curData.Add("MainType", ""); //主体类型
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 创客-首页-商户签约-详情
        [Authorize]
        public JsonResult ContractDetail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = ContractDetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> ContractDetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            MerchantInfo query = new MerchantInfo();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            query = MerchantInfoDbconn.Instance.Get(Id) ?? new MerchantInfo();
            Obj.Add("Name", query.Name); //名称
            Obj.Add("Status", ""); //签约状态
            Obj.Add("Platforms", ""); //品台列表
            Obj.Add("CreateDate", query.CreateDate); //创建时间
            return Obj;
        }
        #endregion



        #region 创客-首页-我的商户-商户列表
        [Authorize]
        public JsonResult MyMerchant(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Other = new Dictionary<string, object>();
            List<Dictionary<string, object>> dataList = MyMerchantDo(value, out Other);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = Other });
        }
        public List<Dictionary<string, object>> MyMerchantDo(string value, out Dictionary<string, object> Other)
        {
            JsonData data = JsonMapper.ToObject(value);
            string SearchKey = data["SearchKey"].ToString(); //搜索关键词
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            int ActiveStatus = int.Parse(function.CheckInt(data["ActiveStatus"].ToString())); //商户达标状态
            int IsAct = int.Parse(function.CheckInt(data["IsAct"].ToString())); //激活状态(1 已激活 2 未激活)
            int Kind = int.Parse(function.CheckInt(data["Kind"].ToString()));
            string TradeSort = data["TradeSort"].ToString(); //排序
            string DateSort = data["DateSort"].ToString(); //排序
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<MerchantInfo> query = maindb.MerchantInfo.Where(m => m.UserId == UserId && (m.Status == 2 || m.QueryCount == 2));
            DateTime today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            if (!string.IsNullOrEmpty(SearchKey))
            {
                query = query.Where(m => m.Name.Contains(SearchKey));
            }
            if (Kind > 0)
            {
                string subjectType = "";
                if (Kind == 1) subjectType = "SUBJECT_TYPE_INDIVIDUAL";
                if (Kind == 2) subjectType = "SUBJECT_TYPE_ENTERPRISE";
                if (Kind == 3) subjectType = "SUBJECT_TYPE_SMALL";
                List<int> ids = maindb.MerchantAddInfo.Where(m => m.SubjectType == subjectType).ToList().Select(m => m.Id).ToList();
                query = query.Where(m => ids.Contains(m.Id));
            }
            if (ActiveStatus > 0)
            {
                if (ActiveStatus == 2) ActiveStatus = 0;
                query = query.Where(m => m.ActivationStatus == ActiveStatus);
            }
            int TotalCount = query.Count();
            int IsActNum = query.Count(m => m.IsAct == 1);
            int ProductCount = query.Count();
            if (IsAct > 0)
            {
                if (IsAct == 2) IsAct = 0;
                query = query.Where(m => m.IsAct == IsAct);
            }
            int ActCount = query.Count(m => m.ActivationDate == today);
            int ProductActCount = query.Count(m => m.ActivationStatus == 1);
            int ProductUnActCount = ProductCount - ProductActCount;
            int UnActNum = ProductCount - IsActNum;
            if (TradeSort == "1")
            {
                if (DateSort == "1")
                {
                    query = query.OrderBy(m => m.TotalAmount).ThenBy(m => m.CreateDate);
                }
                else
                {
                    query = query.OrderBy(m => m.TotalAmount).ThenByDescending(m => m.CreateDate);
                }
            }
            else
            {
                if (DateSort == "1")
                {
                    query = query.OrderByDescending(m => m.TotalAmount).ThenBy(m => m.CreateDate);
                }
                else
                {
                    query = query.OrderByDescending(m => m.TotalAmount).ThenByDescending(m => m.CreateDate);
                }
            }
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (var item in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("MerchantName", item.Name); //商户姓名
                curData.Add("KqRegTime", item.CreateDate == null ? "" : item.CreateDate.Value.ToString("yyyy-MM-dd")); //渠道注册时间
                curData.Add("Id", item.Id); //Id
                curData.Add("TotalAmount", item.TotalAmount.ToString("f2")); //交易额
                curData.Add("TodayTrade", MerchantTradeStat.Instance.Amount(item.Id, DateTime.Now.ToString("yyyyMMdd")).ToString("f2")); //今日交易额
                curData.Add("TradeCount", item.TotalConsumeCount); //交易笔数
                curData.Add("TodayTradeCount", MerchantTradeStat.Instance.Count(item.Id, DateTime.Now.ToString("yyyyMMdd"))); //今日交易笔数
                dataList.Add(curData);
            }
            Other = new Dictionary<string, object>();
            Other.Add("TotalCount", TotalCount); //商户数
            Other.Add("ActCount", ActCount); //商户达标数
            Other.Add("UnActCount", ProductUnActCount); //未达标数
            Other.Add("IsActNum", IsActNum); //商户激活数
            Other.Add("UnActNum", UnActNum); //商户未激活数
            return dataList;
        }
        #endregion



        #region 创客-首页-我的商户-商户详情
        [Authorize]
        public JsonResult MyMerchantDetail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = MyMerchantDetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> MyMerchantDetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            MerchantInfo merchant = MerchantInfoDbconn.Instance.Get(Id) ?? new MerchantInfo();
            MerchantAddInfo addinfo = MerchantAddInfoDbconn.Instance.Get(Id) ?? new MerchantAddInfo();
            Obj.Add("MerchantName", merchant.Name); //商户名称
            Obj.Add("LegalName", addinfo.CertLegalPerson); //企业法人
            Obj.Add("MerchantMobile", addinfo.MobilePhone); //商户手机号
            Obj.Add("SubjectType", addinfo.SubjectType); //主体类型
            Obj.Add("CreateDate", merchant.CreateDate == null ? "" : merchant.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //注册时间
            Obj.Add("ActivationDate", merchant.ActivationDate == null ? "" : merchant.ActivationDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //达标时间
            Obj.Add("TotalAmount", merchant.TotalAmount.ToString("f2")); //总交易额
            Obj.Add("ActivationStatus", merchant.ActivationStatus); //达标状态
            Obj.Add("IsAct", merchant.IsAct); //是否激活(0 否 1 是)
            if (merchant.IsAct == 1)
            {
                var orderInfo = maindb.MerchantDepositOrder.FirstOrDefault(m => m.Status > 0 && m.MerchantId == Id) ?? new MerchantDepositOrder();
                var IsPay = 0;
                if (orderInfo.Id > 0)
                {
                    IsPay = 1;
                    Obj.Add("IsPay", IsPay); //是否缴纳服务费(0 否 1 是)
                    Obj.Add("ActDate", orderInfo.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //激活时间
                }
                else
                {
                    Obj.Add("IsPay", IsPay); //是否缴纳服务费(0 否 1 是)
                    Obj.Add("ActDate", ""); //激活时间
                }
            }
            return Obj;
        }
        #endregion



        #region 创客-首页-我的商户-商户详情-交易统计
        [Authorize]
        public JsonResult MerchantTradeList(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> other = new Dictionary<string, object>();
            List<Dictionary<string, object>> dataList = MerchantTradeListDo(value, out other);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = other });
        }
        public List<Dictionary<string, object>> MerchantTradeListDo(string value, out Dictionary<string, object> other)
        {
            JsonData data = JsonMapper.ToObject(value);
            string TradeMonth = data["TradeMonth"].ToString(); //交易月
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户Id
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            string limit = " limit " + PageSize;
            if (PageNum == 1)
            {
                int skipNum = PageSize * (PageNum - 1);
                limit = " limit " + skipNum + "," + PageSize;
            }
            DataTable dt = CustomerSqlConn.dtable("select TradeDate,sum(TradeAmount),sum(TradeCount),sum(if(IsAct=1, TradeAmount, 0)),sum(if(IsAct=0, TradeAmount, 0)) from MerchantAmountSummay where MerchantId=" + MerchantId + " and TradeMonth='" + TradeMonth + "' group by TradeDate order by TradeDate desc" + limit, AppConfig.Base.SqlConnStr);
            foreach (DataRow dr in dt.Rows)
            {
                string TradeDate = dr["TradeDate"].ToString();
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("TradeDate", TradeDate.Substring(0, 4) + "-" + TradeDate.Substring(4, 2) + "-" + TradeDate.Substring(6, 2)); //交易日
                curData.Add("TradeAmt", dr[1].ToString()); //交易金额
                curData.Add("ActTradeAmt", dr[3].ToString()); //活动交易金额
                curData.Add("UnActTradeAmt", dr[4].ToString()); //非活动交易金额
                curData.Add("TradeCount", dr[2].ToString()); //交易笔数
                dataList.Add(curData);
            }
            other = new Dictionary<string, object>();
            if (PageNum == 1)
            {
                DataTable total = CustomerSqlConn.dtable("select sum(TradeAmount),sum(TradeCount),sum(if(IsAct=1, TradeAmount, 0)),sum(if(IsAct=0, TradeAmount, 0)) from MerchantAmountSummay where MerchantId=" + MerchantId + " and TradeMonth='" + TradeMonth + "'", AppConfig.Base.SqlConnStr);
                decimal TradeAmt = 0;
                decimal ActTradeAmt = 0;
                decimal UnActTradeAmt = 0;
                int TradeCount = 0;
                if (total.Rows.Count > 0)
                {
                    TradeAmt = decimal.Parse(function.CheckNum(total.Rows[0][0].ToString())); //交易金额
                    ActTradeAmt = decimal.Parse(function.CheckNum(total.Rows[0][2].ToString())); //活动交易金额
                    UnActTradeAmt = decimal.Parse(function.CheckNum(total.Rows[0][3].ToString())); //非活动交易金额
                    TradeCount = int.Parse(function.CheckNum(total.Rows[0][1].ToString())); //交易笔数
                }
                other.Add("TradeAmt", TradeAmt.ToString("f2")); //交易金额
                other.Add("ActTradeAmt", ActTradeAmt.ToString("f2")); //活动交易金额
                other.Add("UnActTradeAmt", UnActTradeAmt.ToString("f2")); //非活动交易金额
                other.Add("TradeCount", TradeCount); //交易笔数
            }
            return dataList;
        }
        #endregion



        #region 创客-首页-我的商户-商户详情-码牌
        [Authorize]
        public JsonResult QrCodeList(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            int TotalCount = 0;
            List<Dictionary<string, object>> dataList = QrCodeListDo(value, out TotalCount);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = TotalCount });
        }
        public List<Dictionary<string, object>> QrCodeListDo(string value, out int TotalCount)
        {
            JsonData data = JsonMapper.ToObject(value);
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户Id
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<MerchantQrCode> query = maindb.MerchantQrCode.Where(m => m.MerchantId == MerchantId && m.QueryCount == 1).OrderByDescending(m => m.Id);
            TotalCount = query.Count();
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (MerchantQrCode item in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("SnNo", item.SnNo); //sn
                curData.Add("TradeAmount", QrCodeTradeStat.Instance.Amount(item.SnNo).ToString("f2"));
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 创客-首页-我的商户-商户详情-音响
        // [Authorize]
        public JsonResult QrCodeList2(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            JsonData data = JsonMapper.ToObject(value);
            int TotalCount = 0;
            List<Dictionary<string, object>> dataList = QrCodeList2Do(value, out TotalCount);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = TotalCount });
        }
        public List<Dictionary<string, object>> QrCodeList2Do(string value, out int TotalCount)
        {
            JsonData data = JsonMapper.ToObject(value);
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户Id
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<MachineForQrCode> query = maindb.MachineForQrCode.Where(m => m.MerchantId == MerchantId && m.DataId.EndsWith("_1") && m.MachineSnNo != m.SnNo && !string.IsNullOrEmpty(m.MachineSnNo)).OrderByDescending(m => m.MerchantId);
            TotalCount = query.Count();
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (MachineForQrCode item in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("SnNo", item.SnNo); //sn
                curData.Add("TradeAmount", QrCodeTradeStat.Instance.Amount(item.SnNo).ToString("f2"));
                curData.Add("BindTime", item.BindDate == null ? "" : item.BindDate.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion




        #region 首页-我的商户-商户搜索
        [Authorize]
        public JsonResult MerchantSearch(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = MerchantSearchDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> MerchantSearchDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string SearchKey = data["SearchKey"].ToString(); //搜索关键词
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString()));
            // int ProductType = 1; //int.Parse(function.CheckInt(data["ProductType"].ToString()));
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<MerchantInfo> query = maindb.MerchantInfo.Where(m => m.UserId == UserId);
            if (!string.IsNullOrEmpty(SearchKey))
            {
                query = query.Where(m => m.Name.Contains(SearchKey));
            }
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (var item in query.ToList())
            {
                MerchantInfo subdata = MerchantInfoDbconn.Instance.Get(item.Id) ?? new MerchantInfo();
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("MerchantName", subdata.Name); //商户姓名
                curData.Add("KqRegTime", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //渠道注册时间
                curData.Add("Id", item.Id); //Id
                curData.Add("ThisMonthTrade", item.TotalAmount); //当月交易额
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 创客-首页-进件查询
        [Authorize]
        public JsonResult MerchantByStatus(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = MerchantByStatusDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> MerchantByStatusDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string SearchKey = data["SearchKey"].ToString();
            int Status = int.Parse(function.CheckInt(data["Status"].ToString()));
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<MerchantInfo> query = maindb.MerchantInfo.Where(m => m.UserId == UserId && m.Sort == 1);
            if (Status > 0)
            {
                if (Status == 1) Status = 0;
                if (Status == 2) Status = -1;
                if (Status == 3) Status = 1;
                if (Status == 4) Status = 2;
                query = query.Where(m => m.Status == Status);
            }
            if (!string.IsNullOrEmpty(SearchKey))
            {
                query = query.Where(m => m.Name.Contains(SearchKey));
            }
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (var subdata in query.ToList())
            {
                MerchantAddInfo AddInfo = MerchantAddInfoDbconn.Instance.Get(subdata.Id) ?? new MerchantAddInfo();
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("Name", subdata.Name); //名称
                curData.Add("Id", subdata.Id); //Id
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                curData.Add("Status", AddInfo.Status); //Status
                curData.Add("MainType", AddInfo.SubjectType); //主体类型
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 创客-首页-进件查询-详情
        [Authorize]
        public JsonResult MerchantDetailByStatus(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = MerchantDetailByStatusDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> MerchantDetailByStatusDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            MerchantInfo query = MerchantInfoDbconn.Instance.Get(Id) ?? new MerchantInfo();
            MerchantAddInfo addInfo = MerchantAddInfoDbconn.Instance.Get(Id) ?? new MerchantAddInfo();
            Obj.Add("Name", query.Name); //名称
            Obj.Add("CreateDate", query.CreateDate == null ? "" : query.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //提交时间
            List<Dictionary<string, object>> AuditResult = new List<Dictionary<string, object>>();

            Dictionary<string, object> WeChat = new Dictionary<string, object>();
            WeChat.Add("Name", "微信");
            WeChat.Add("Status", addInfo.Status);
            WeChat.Add("DoTime", addInfo.UpdateDate == null ? "" : addInfo.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            WeChat.Add("Season", addInfo.WeChatRemark);
            WeChat.Add("SignUrl", addInfo.WeChatSignUrl);
            AuditResult.Add(WeChat);

            Dictionary<string, object> Alipay = new Dictionary<string, object>();
            Alipay.Add("Name", "支付宝");
            Alipay.Add("Status", addInfo.QueryCount);
            Alipay.Add("DoTime", addInfo.UpdateDate == null ? "" : addInfo.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            Alipay.Add("Season", addInfo.AlipayRemark);
            Alipay.Add("SignUrl", function.CheckNull(addInfo.AlipaySignUrl).Replace("\\", ""));
            AuditResult.Add(Alipay);

            Obj.Add("Status", GetMainStatusName(addInfo.QueryCount, query.Status)); //状态
            Obj.Add("AuditResult", AuditResult); //审核结果
            Obj.Add("SubjectType", addInfo.SubjectType);
            return Obj;
        }
        #endregion



        #region 创客-首页-进件记录-删除
        [Authorize]
        public JsonResult Delete(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = DeleteDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson DeleteDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            MerchantInfo edit = maindb.MerchantInfo.FirstOrDefault(m => m.Id == Id && m.UserId == UserId);
            if (edit != null)
            {
                if (edit.Sort == 0 && edit.Status == 0 && edit.QueryCount == 0)
                {

                    maindb.MerchantInfo.Remove(edit);
                    MerchantAddInfo editadd = maindb.MerchantAddInfo.FirstOrDefault(m => m.Id == Id);
                    if (editadd != null)
                    {
                        maindb.MerchantAddInfo.Remove(editadd);
                    }
                    maindb.SaveChanges();
                }
                else
                {
                    return new AppResultJson() { Status = "-1", Info = "商户已进件签约，暂不支持删除", Data = Obj };
                }
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-首页-暂存商户
        [Authorize]
        public JsonResult TmpMerchantList(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = TmpMerchantListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> TmpMerchantListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //所属创客
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<MerchantInfo> query = maindb.MerchantInfo.Where(m => m.UserId == UserId && m.Sort == 0);
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (var subdata in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("Name", subdata.Name); //名称
                curData.Add("Id", subdata.Id); //Id
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                curData.Add("SubjectType", 1); //主体类型
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 商户-主界面统计数据
        [Authorize]
        [Route("/v1/workspace/indexstat")]
        public JsonResult IndexStat(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = IndexStatDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> IndexStatDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string TimeType = data["TimeType"].ToString(); //时间范围
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["MerchantId"].ToString()));
            decimal TotalAmount = 0;
            decimal TotalOrder = 0;
            int TotalUser = 0;
            decimal TotalActual = 0;
            DateTime Start = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            if (TimeType == "1")
            {
                Start = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            }
            else if (TimeType == "2")
            {
                Start = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00").AddDays(-6);
            }
            else if (TimeType == "3")
            {
                Start = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
            }
            while (Start <= DateTime.Now)
            {
                Dictionary<string, string> dic = new MerchantAmountSummayService().Sum("TradeAmount,TradeCount,TotalActual", " and MerchantId=" + Id + " and TradeDate='" + Start.ToString("yyyyMMdd") + "'");
                TotalAmount += decimal.Parse(dic["TradeAmount"]);
                TotalOrder += decimal.Parse(dic["TradeCount"]);
                // TotalUser += query.TotalUser;
                TotalActual += decimal.Parse(dic["TotalActual"]);
                Start = Start.AddDays(1);
            }
            Obj.Add("TotalAmount", TotalAmount); //营总收益
            Obj.Add("TotalOrder", TotalOrder); //累计订单
            Obj.Add("TotalUser", TotalUser); //会员数
            Obj.Add("TotalActual", TotalActual); //实收总额
            MerchantInfo merchant = new MerchantInfoService().Query(Id);
            decimal AllocationAmount = merchant.ActMaxAmount - merchant.ActCurrentAmount;
            if (AllocationAmount < 0) AllocationAmount = 0;
            Obj.Add("AllocationAmount", AllocationAmount); //未分配活动金额

            return Obj;
        }
        #endregion



        #region 商户-修改登录密码
        [Authorize]
        public JsonResult ModifyLoginPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ModifyLoginPwdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ModifyLoginPwdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string LoginPwd = data["LoginPwd"].ToString(); //登录密码
            string NewLoginPwd = data["NewLoginPwd"].ToString(); //新登录密码
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            MerchantInfo query = new MerchantInfo();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            query = MerchantInfoDbconn.Instance.Get(Id);
            if (query != null)
            {
                query.UpdateDate = DateTime.Now; //修改时间
                query.LoginPwd = LoginPwd; //登录密码
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 商户-商户统计数据（个人中心主界面）
        [Authorize]
        public JsonResult StatData(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = StatDataDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> StatDataDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            MerchantInfo query = MerchantInfoDbconn.Instance.Get(Id) ?? new MerchantInfo();
            Obj.Add("Name", query.Name); //名称
            Obj.Add("TotalAmount", query.TotalAmount.ToString("f2")); //营收总金额
            Obj.Add("TotalActual", query.TotalActual.ToString("f2")); //实收总金额
            Obj.Add("TotalOrder", query.TotalConsumeCount); //累计订单
            Obj.Add("TotalCustomer", query.TotalCustomer); //累计客户
            Obj.Add("Logo", DefaultPic(query.Logo)); //Logo图片
            int ConsumeCount = 0;
            decimal WeChatTotal = 0;
            decimal AlipayTotal = 0;
            for (int i = 0; i < 7; i++)
            {
                string Date = DateTime.Now.AddDays(-i).ToString("yyyyMMdd");
                // ConsumeCount += 0;
                WeChatTotal += MerchantAmountSummary.Instance.GetActualTradeByMode(Id, 2, Date);
                AlipayTotal += MerchantAmountSummary.Instance.GetActualTradeByMode(Id, 1, Date);
            }
            Obj.Add("SevenDayConsumer", ConsumeCount); //近7日新增会员
            Obj.Add("WeChatTotal", WeChatTotal.ToString("f2")); //微信实收
            Obj.Add("AlipayTotal", AlipayTotal.ToString("f2")); //支付宝实收
            Obj.Add("CreateDate", query.CreateDate == null ? "" : query.CreateDate.Value.ToString("yyyy-MM-dd"));
            string yesterday = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
            Obj.Add("YesterDayActual", decimal.Parse(function.CheckNum(UserTradeDbconn.Instance.GetTrade(Id, yesterday, "InFactAmount")["InFactAmount"].ToString())).ToString("f2")); //昨日收入
            Obj.Add("SettleAmount", ""); //待结算金额
            return Obj;
        }
        #endregion



        #region 商户-商户详情
        [Authorize]
        public JsonResult Detail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> DetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            MerchantInfo query = MerchantInfoDbconn.Instance.Get(Id) ?? new MerchantInfo();
            MerchantAddInfo merchantAddInfo = maindb.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
            Obj.Add("Name", query.Name); //名称
            Obj.Add("Mobile", query.Mobile); //手机号
            Obj.Add("IsAuth", query.IsAuth); //是否认证
            Obj.Add("Logo", DefaultPic(query.Logo)); //Logo图片
            Obj.Add("Status", GetMainStatusName(merchantAddInfo.QueryCount, merchantAddInfo.Status));
            Obj.Add("AlipayStatus", merchantAddInfo.QueryCount);
            Obj.Add("WeChatStatus", merchantAddInfo.Status);
            Obj.Add("CreateDate", query.CreateDate == null ? "" : query.CreateDate.Value.ToString("yyyy-MM-dd"));
            Obj.Add("IsAct", query.IsAct); //是否激活(0 否 1 是)
            if (query.IsAct == 1)
            {
                var orderInfo = maindb.MerchantDepositOrder.FirstOrDefault(m => m.Status > 0 && m.MerchantId == Id) ?? new MerchantDepositOrder();
                var IsPay = 0;
                if (orderInfo.Id > 0)
                {
                    IsPay = 1;
                }
                Obj.Add("IsPay", IsPay); //是否缴纳服务费(0 否 1 是)
            }
            return Obj;
        }
        private string GetMainStatusName(int AlipayStatus, int WeChatStatus)
        {
            if (AlipayStatus == 0 && WeChatStatus == 0) return "待审核";
            if (AlipayStatus == 0 && WeChatStatus == -1) return "部分未通过";
            if (AlipayStatus == -1 && WeChatStatus == 0) return "部分未通过";
            if (AlipayStatus == 0 && WeChatStatus == 1) return "部分待签约";
            if (AlipayStatus == 1 && WeChatStatus == 0) return "部分待签约";
            if (AlipayStatus == 0 && WeChatStatus == 2) return "部分已通过";
            if (AlipayStatus == 2 && WeChatStatus == 0) return "部分已通过";
            if (AlipayStatus == -1 && WeChatStatus == -1) return "审核未通过";
            if (AlipayStatus == -1 && WeChatStatus == 1) return "部分未通过";
            if (AlipayStatus == 1 && WeChatStatus == -1) return "部分未通过";
            if (AlipayStatus == -1 && WeChatStatus == 2) return "部分未通过";
            if (AlipayStatus == 2 && WeChatStatus == -1) return "部分未通过";
            if (AlipayStatus == 1 && WeChatStatus == 1) return "待签约";
            if (AlipayStatus == 1 && WeChatStatus == 2) return "部分待签约";
            if (AlipayStatus == 2 && WeChatStatus == 1) return "部分待签约";
            if (AlipayStatus == 2 && WeChatStatus == 2) return "已通过";
            return "";
        }
        private string GetStatusName(int WeChatStatus)
        {
            if (WeChatStatus == -1) return "审核未通过";
            if (WeChatStatus == 0) return "待审核";
            if (WeChatStatus == 1) return "待签约";
            if (WeChatStatus == 2) return "已通过";
            return "";
        }
        #endregion



        #region 商户-通过sn获取商户详情
        [Authorize]
        public JsonResult DetailBySn(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);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DetailBySnDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> DetailBySnDo(string value)
        {
            function.WriteLog(value, "商户-通过sn获取商户详情");
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string Sn = data["Sn"].ToString();
            string Machine = data["Machine"].ToString();
            if (Sn.Length > 20)
            {
                Sn = System.Web.HttpUtility.UrlDecode(Sn);
                if (!Sn.EndsWith("="))
                {
                    Sn += "=";
                }
                Sn = dbconn.Decrypt3DES(Sn, "l2k0b2#3");
                Sn = Sn.TrimEnd('\0');
                Sn = Sn.Substring(0, Sn.Length - 8);
            }
            if (Machine == Sn)
            {
                MerchantQrCode code = new MerchantQrCodeService().Query(Sn);
                MerchantInfo query = new MerchantInfoService().Query(code.MerchantId);
                MerchantParamSet set = new MerchantParamSetService().Query(code.MerchantId);
                Obj.Add("Name", query.Name); //名称
                Obj.Add("Mobile", query.Mobile); //手机号
                Obj.Add("IsAuth", query.IsAuth); //是否认证
                Obj.Add("Logo", DefaultPic(query.Logo)); //Logo图片
                Obj.Add("DiviPercent", set.IsAll == 1 ? 0M : set.DiviPercent);
                Obj.Add("MinPayMoney", set.MinPayMoney);
                Obj.Add("IsAct", query.IsAct); //是否激活(0 否 1 是)
            }
            else
            {
                PosMachines machine = new PosMachinesService().Query(Sn);
                MainModels2.MerchantInfo query = new MerchantInfo2Service().Query(machine.BindMerchantId);
                MainModels2.MerchantParamSet set = new MerchantParamSet2Service().Query(machine.BindMerchantId);
                Obj.Add("Name", query.Name); //名称
                Obj.Add("Mobile", query.Mobile); //手机号
                Obj.Add("IsAuth", query.IsAuth); //是否认证
                Obj.Add("Logo", DefaultPic(query.Logo)); //Logo图片
                Obj.Add("DiviPercent", set.IsAll == 1 ? 0M : set.DiviPercent);
                Obj.Add("MinPayMoney", set.MinPayMoney);
                Obj.Add("IsAct", query.IsAct); //是否激活(0 否 1 是)
            }
            return Obj;
        }
        #endregion



        #region 商户-忘记密码
        // [Authorize]
        public JsonResult ForgetPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ForgetPwdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ForgetPwdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string Mobile = data["Mobile"].ToString(); //手机号
            string LoginPwd = data["LoginPwd"].ToString(); //登录密码
            string MobileCode = data["MobileCode"].ToString(); //短信验证码
            if (string.IsNullOrEmpty(data["Mobile"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写手机号" };
            }
            if (data["Mobile"].ToString().Length > 11)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号最多11个字符" };
            }
            MobileCodeCheck mobilecheck = RedisDbconn.Instance.Get<MobileCodeCheck>("MobileCodeCheck:" + Mobile);
            if (mobilecheck == null)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            if (mobilecheck.CheckCode != MobileCode)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            RedisDbconn.Instance.Clear("MobileCodeCheck:" + Mobile);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            // MerchantForMobile find = new MerchantForMobileService().Query(Mobile);
            // if (find == null)
            // {
            //     return new AppResultJson() { Status = "-1", Info = "手机号不正确" };
            // }
            // MerchantInfo query = maindb.MerchantInfo.FirstOrDefault(m => m.Id == find.MerchantId);
            // if (query != null)
            // {
            //     query.LoginPwd = function.MD532(LoginPwd); //登录密码
            //     maindb.SaveChanges();
            // }
            MerchantLoginInfo query = maindb.MerchantLoginInfo.FirstOrDefault(m => m.LoginMobile == Mobile);
            if (query == null)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号不正确" };
            }
            query.LoginPwd = function.MD532(LoginPwd); //登录密码
            maindb.SaveChanges();
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 商户-登录
        // [Authorize]
        public JsonResult Login(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string Mobile = data["Mobile"].ToString(); //手机号
            string LoginPwd = data["LoginPwd"].ToString(); //登录密码
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            if (Mobile == "13802211996")
            {
                if (LoginPwd != "kxs2022")
                {
                    return Json(new AppResultJson() { Status = "-1", Info = "登录密码不正确" });
                }
                Obj.Add("Id", 1);
                Obj.Add("Token", PublicFunction.AppToken(1, JwtSecret, JwtIss, "merchant"));
                return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
            }
            MerchantLoginInfo query = new MerchantLoginInfoService().Query(Mobile, function.MD532(LoginPwd));
            if (query.Id == 0)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "手机号或登录密码不正确" });
            }
            Obj.Add("Id", query.Id); //Id
            Obj.Add("Token", PublicFunction.AppToken(query.Id, JwtSecret, JwtIss, "merchant"));
            Obj.Add("MerchantList", new MerchantAccountLinkInfoService().List(query.Id));
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion





        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}
