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 LitJson;
using Library;
using MySystem.Service.Main;
using MySystem.Models.Main;
using System.Text;

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


        #region 创客-首页-进件查询
        // [Authorize]
        public JsonResult MerchantByStatus(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            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.getItem("SearchKey").ToString();
            int Status = int.Parse(function.CheckInt(data.getItem("Status").ToString()));
            int UserId = int.Parse(function.CheckInt(data.getItem("UserId").ToString())); //所属创客
            int BrandId = 0; //品牌(0 银联 1 好哒)
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("PageNum").ToString()));
            StringBuilder condition = new StringBuilder();
            if (!string.IsNullOrEmpty(data.getItem("BrandId").ToString()))
            {
                BrandId = int.Parse(function.CheckInt(data.getItem("BrandId").ToString())); //品牌(0 银联 1 好哒)
            }
            condition.Condition("BrandId", BrandId);
            condition.Condition("UserId", UserId);
            condition.Condition("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; // 已签约
                condition.Condition("Status", Status);
            }
            if (!string.IsNullOrEmpty(SearchKey))
            {
                condition.ConditionLike("Name", SearchKey);
            }
            List<Dictionary<string, object>> list = MerchantInfoService.List(new List<RelationData>(), condition.ToString(), PageNum, PageSize);
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            foreach (Dictionary<string, object> subdata in list)
            {
                MerchantAddInfo AddInfo = MerchantAddInfoService.Query(int.Parse(subdata["Id"].ToString()));
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("Name", subdata["Name"]); //名称
                curData.Add("Id", subdata["Id"]); //Id
                curData.Add("BrandId", subdata["BrandId"]); //品牌(0 银联 1 好哒)
                curData.Add("CreateDate", subdata["CreateDate"]); //CreateDate
                curData.Add("Status", subdata["Status"]); //Status
                curData.Add("SubjectType", AddInfo.SubjectType); //主体类型
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 创客-首页-进件查询-详情
        // [Authorize]
        public JsonResult MerchantDetailByStatus(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            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.getItem("Id").ToString()));
            MerchantInfo query = MerchantInfoService.Query(Id);
            MerchantAddInfo addInfo = MerchantAddInfoService.Query(Id);
            // Obj.Add("Name", query.Name); //名称
            // Obj.Add("CreateDate", query.CreateDate == null ? "" : query.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //提交时间

            // Obj.Add("Status", addInfo.Status);
            // Obj.Add("DoTime", addInfo.UpdateDate == null ? "" : addInfo.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            // Obj.Add("Season", addInfo.WeChatRemark);
            // Obj.Add("SignUrl", addInfo.WeChatSignUrl);

            // Obj.Add("SubjectType", addInfo.SubjectType);
            Obj.Add("Kind", 2); //通道(1 直连 2 银联)
            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);

            if (addInfo.HdStatus > 0)
            {
                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", addInfo.Status);
            Obj.Add("AuditResult", AuditResult); //审核结果
            Obj.Add("SubjectType", addInfo.SubjectType);
            return Obj;
        }
        #endregion


        //new
        #region 首页-快联盟产品-我的业绩-团队业绩-商户列表
        // [Authorize]
        public JsonResult TeamPerformanceMerchants(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            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.getItem("UserId").ToString())); //创客
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("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);
            value = value.Replace("null", "\"\"");
            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.getItem("UserId").ToString())); //所属创客
            string Status = data.getItem("Status").ToString(); //签约状态
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("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);
            value = value.Replace("null", "\"\"");
            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.getItem("Id").ToString()));
            query = MerchantInfoDbconn.Instance.Get(Id) ?? new MerchantInfo();
            Obj.Add("Kind", 2); //通道(1 直连 2 银联)
            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);
            value = value.Replace("null", "\"\"");
            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.getItem("SearchKey").ToString(); //搜索关键词
            int UserId = int.Parse(function.CheckInt(data.getItem("UserId").ToString())); //创客
            int ActiveStatus = int.Parse(function.CheckInt(data.getItem("ActiveStatus").ToString())); //达标状态(1 已达标 2 未达标)
            int IsAct = int.Parse(function.CheckInt(data.getItem("IsAct").ToString())); //激活状态(1 已激活 2 未激活)
            int Kind = int.Parse(function.CheckInt(data.getItem("Kind").ToString()));
            string TradeSort = data.getItem("TradeSort").ToString(); //排序
            string DateSort = data.getItem("DateSort").ToString(); //排序
            int BrandId = 0; //品牌(0 银联 1 好哒)
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("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(data.getItem("BrandId").ToString()))
            {
                BrandId = int.Parse(function.CheckInt(data.getItem("BrandId").ToString())); //品牌(0 银联 1 好哒)
            }
            query = query.Where(m => m.BrandId == BrandId);
            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("BrandId", item.BrandId); //品牌(0 银联 1 好哒)
                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);
            value = value.Replace("null", "\"\"");
            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.getItem("Id").ToString()));
            MerchantInfo merchant = MerchantInfoService.Query(Id);
            MerchantAddInfo addinfo = MerchantAddInfoService.Query(Id);
            Obj.Add("Kind", 2); //通道(1 直连 2 银联)
            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 = MerchantDepositOrderService.Query(" 1=1 and Status>0 and MerchantId=" + Id + "");
                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);
            value = value.Replace("null", "\"\"");
            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.getItem("TradeMonth").ToString(); //交易月
            int MerchantId = int.Parse(function.CheckInt(data.getItem("MerchantId").ToString())); //商户Id
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("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);
            value = value.Replace("null", "\"\"");
            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.getItem("MerchantId").ToString())); //商户Id
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("PageNum").ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<MerchantQrCode> query = maindb.MerchantQrCode.Where(m => m.MerchantId == MerchantId && m.QueryCount == 2).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"));
                curData.Add("BindTime", item.CreateDate == null ? "" : item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                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.getItem("MerchantId").ToString())); //商户Id
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("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("_2") && 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);
            value = value.Replace("null", "\"\"");
            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.getItem("SearchKey").ToString(); //搜索关键词
            int UserId = int.Parse(function.CheckInt(data.getItem("UserId").ToString()));
            // int ProductType = 1; //int.Parse(function.CheckInt(data.getItem("ProductType").ToString()));
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("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 Delete(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            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.getItem("Id").ToString()));
            int UserId = int.Parse(function.CheckInt(data.getItem("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);
            value = value.Replace("null", "\"\"");
            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 BrandId = 0; //品牌(0 银联 1 好哒)
            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 (!string.IsNullOrEmpty(data["BrandId"].ToString()))
            {
                BrandId = int.Parse(function.CheckInt(data["BrandId"].ToString())); //品牌(0 银联 1 好哒)
            }
            query = query.Where(m => m.BrandId == BrandId);
            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("BrandId", subdata.BrandId); //品牌(0 银联 1 好哒)
                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]
        public JsonResult ModifyLoginPwd(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            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 Detail(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            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("Kind", 2); //通道(1 直连 2 银联)
            Obj.Add("Name", query.Name); //名称
            Obj.Add("Mobile", query.Mobile); //手机号
            Obj.Add("IsAuth", query.IsAuth); //是否认证
            Obj.Add("MchtNo", merchantAddInfo.MchtNo); //商户号
            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 = MerchantDepositOrderService.Query(" 1=1 and Status>0 and MerchantId=" + Id + "");
                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);
            value = value.Replace("null", "\"\"");
            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();
            MerchantQrCode code = MerchantQrCodeService.Query(Sn);
            MerchantInfo query = MerchantInfoService.Query(code.MerchantId);
            MerchantParamSet set = MerchantParamSetService.Query(code.MerchantId);
            Obj.Add("Kind", 2); //通道(1 直连 2 银联)
            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);
            value = value.Replace("null", "\"\"");
            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 = 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();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion

        #region 我的-商户统计数据（个人中心主界面）
        // [Authorize]
        public JsonResult StatData(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            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);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            var Info = MySelfUtil.StatData(Id);
            return Info;
        }
        #endregion


        #region 首页-查询该商户是否已存在
        // [Authorize]
        public JsonResult CheckMerchant(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            JsonData data = JsonMapper.ToObject(value);
            bool Obj = CheckMerchantDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public bool CheckMerchantDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string CertMerchantName = data["CertMerchantName"].ToString();
            var Info = MerchantAddInfoService.Query(" CertMerchantName='" + CertMerchantName + "'");
            if (Info.Id > 0)
            {
                return true;
            }
            return false;
        }
        #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

    }
}
