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

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

        #region 进件管理-银联商户列表
        [Authorize]
        public JsonResult UnionPayList(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Other = new Dictionary<string, object>();
            List<Dictionary<string, object>> dataList = UnionPayListDo(value, out Other);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = Other });
        }
        private List<Dictionary<string, object>> UnionPayListDo(string value, out Dictionary<string, object> Other)
        {
            JsonData data = JsonMapper.ToObject(value);
            string SubjectType = data["SubjectType"].ToString(); //主体类型(1 企业 2 个体)
            string CertMerchantName = data["CertMerchantName"].ToString(); //商户名称
            string ServicePhone = data["ServicePhone"].ToString(); //客服电话
            string MakerCode = data["MakerCode"].ToString(); //所属创客编号
            string HDStatus = data["HDStatus"].ToString(); //好哒状态(-1 审核失败 0 待审核 3 已通过)
            string WeChatStatus = data["WeChatStatus"].ToString(); //微信状态(-1 审核失败 0 待审核 1 待签约 2 已通过)
            string AliPayStatus = data["AliPayStatus"].ToString(); //支付宝状态(-1 审核失败 0 待审核 1 待签约 2 已通过)
            int pageSize = int.Parse(function.CheckInt(data["page_size"].ToString()));
            int pageNum = int.Parse(function.CheckInt(data["page_num"].ToString()));
            string condition = "";
            var merIds = MerchantInfoUtil.QuerySenedMerchantId();
            condition = " and Id in (" + merIds + ")";
            if (!string.IsNullOrEmpty(data["SubjectType"].ToString()))
            {
                if (data["SubjectType"].ToString() == "1") SubjectType = "SUBJECT_TYPE_ENTERPRISE"; //企业公司
                if (data["SubjectType"].ToString() == "2") SubjectType = "SUBJECT_TYPE_INDIVIDUAL"; //个体工商户
                if (data["SubjectType"].ToString() == "3") SubjectType = "SUBJECT_TYPE_SMALL"; //小微商户
                condition += " and SubjectType='" + SubjectType + "'";
            }
            if (!string.IsNullOrEmpty(data["CertMerchantName"].ToString()))
            {
                condition += " and CertMerchantName like '%" + CertMerchantName + "%'";
            }
            if (!string.IsNullOrEmpty(data["ServicePhone"].ToString()))
            {
                condition += " and ServicePhone='" + ServicePhone + "'";
            }
            if (!string.IsNullOrEmpty(data["MakerCode"].ToString()))
            {
                var Ids = MerchantInfoUtil.QueryMerchantIdByMakerCode(MakerCode);
                condition += " and Id in (" + Ids + ")";
            }
            if (!string.IsNullOrEmpty(data["HDStatus"].ToString()))
            {

                if (int.Parse(HDStatus) == 3)
                {
                    condition += " and HdStatus in(1,2,3)";
                }
                else
                {
                    condition += " and Status=" + HDStatus + "";
                }
            }
            if (!string.IsNullOrEmpty(data["WeChatStatus"].ToString()))
            {
                condition += " and Status=" + WeChatStatus + "";
            }
            if (!string.IsNullOrEmpty(data["AliPayStatus"].ToString()))
            {
                condition += " and QueryCount=" + AliPayStatus + "";
            }
            List<RelationData> relationData = new List<RelationData>();
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            Other = new Dictionary<string, object>();
            int count = 0;
            List<Dictionary<string, object>> source = MerchantAddInfoService.List(relationData, condition, out count, pageNum, pageSize);
            foreach (Dictionary<string, object> subdata in source)
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                var hdStatus = int.Parse(subdata["HdStatus"].ToString());
                var status = int.Parse(subdata["Status"].ToString());
                var queryCount = int.Parse(subdata["QueryCount"].ToString());
                if (hdStatus != 3)
                {
                    hdStatus = status;
                }

                //商户Id
                var MerchantId = int.Parse(subdata["Id"].ToString());
                //主体类型
                var subjectType = 0;
                if (subdata["SubjectType"].ToString() == "SUBJECT_TYPE_ENTERPRISE") subjectType = 1; //企业公司
                if (subdata["SubjectType"].ToString() == "SUBJECT_TYPE_INDIVIDUAL") subjectType = 2; //个体工商户
                if (subdata["SubjectType"].ToString() == "SUBJECT_TYPE_SMALL") subjectType = 3; //小微商户

                curData.Add("Id", subdata["Id"].ToString()); //Id
                curData.Add("SubjectType", subjectType); //主体类型(1 企业 2 个体 3 小微)
                curData.Add("CertMerchantName", subdata["CertMerchantName"].ToString()); //商户名称
                curData.Add("ServicePhone", subdata["ServicePhone"].ToString()); //客服电话
                curData.Add("BizStoreAddress", subdata["BizStoreAddress"].ToString()); //门店地址
                curData.Add("CreateDate", subdata["CreateDate"].ToString() == "" ? "" : DateTime.Parse(subdata["CreateDate"].ToString()).ToString("yyyy-MM-dd HH:mm:ss")); //进件时间
                var userInfo = UsersService.Query(MerchantInfoService.Query(MerchantId).UserId);
                curData.Add("MakerCode", userInfo.MakerCode); //所属创客编号
                curData.Add("RealName", userInfo.RealName); //所属创客姓名
                curData.Add("HDStatus", hdStatus); //好哒状态(-1 审核失败 0 待审核 3 已通过)
                curData.Add("WeChatStatus", status); //微信状态(-1 审核失败 0 待审核 1 待签约 2 已通过)
                curData.Add("AliPayStatus", queryCount); //支付宝状态(-1 审核失败 0 待审核 1 待签约 2 已通过)
                dataList.Add(curData);
            }
            Other.Add("Count", count); //总数
            return dataList;
        }
        #endregion



        #region 进件管理-银联查看失败原因
        [Authorize]
        public JsonResult UnionPayQueryFailReason(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = UnionPayQueryFailReasonDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        private Dictionary<string, object> UnionPayQueryFailReasonDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MerchantId = data["MerchantId"].ToString(); //商户Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            var query = MerchantAddInfoService.Query(int.Parse(MerchantId));
            Obj.Add("HdReason", query.WeChatRemark); //好哒原因
            Obj.Add("WeChatReason", query.WeChatRemark); //微信原因
            Obj.Add("AlipayReason", query.AlipayRemark); //支付宝原因

            return Obj;
        }
        #endregion



        #region 进件管理-银联进件详情
        [Authorize]
        public JsonResult UnionPayDetail(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = UnionPayDetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        private Dictionary<string, object> UnionPayDetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MerchantId = data["MerchantId"].ToString(); //商户Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Obj = MerchantAddInfoUtil.MerchantAddInfoDetail(int.Parse(MerchantId));
            return Obj;
        }
        #endregion



        #region 进件管理-银联提交进件
        [Authorize]
        public JsonResult UnionPaySubmit(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = UnionPaySubmitDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson UnionPaySubmitDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MerchantId = data["MerchantId"].ToString(); //商户Id
            var info = MerchantAddInfoUtil.UnionPaySubmitDo(int.Parse(MerchantId));
            if (info == "success")
            {
                return new AppResultJson() { Status = "1", Info = "成功", Data = info };
            }
            else
            {
                return new AppResultJson() { Status = "-1", Info = "失败", Data = info };
            }
        }
        #endregion



        #region 商户管理-银联查询商户交易信息
        [Authorize]
        public JsonResult UnionPayQueryMerchantTradeInfo(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Other = new Dictionary<string, object>();
            List<Dictionary<string, object>> dataList = UnionPayQueryMerchantTradeInfoDo(value, out Other);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = Other });
        }
        private List<Dictionary<string, object>> UnionPayQueryMerchantTradeInfoDo(string value, out Dictionary<string, object> Other)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MerchantName = data["MerchantName"].ToString(); //商户名称
            string Mobile = data["Mobile"].ToString(); //手机号码
            string MakerCode = data["MakerCode"].ToString(); //所属创客
            string MatchNo = data["MatchNo"].ToString(); //商户号
            string SubjectType = data["SubjectType"].ToString(); //主体类型(1 企业 2 个体 3 小微)
            string IsAct = data["IsAct"].ToString(); //激活状态(0 未激活 1 已激活)
            string ActDate = data["ActDate"].ToString(); //激活时间
            int pageSize = int.Parse(function.CheckInt(data["page_size"].ToString()));
            int pageNum = int.Parse(function.CheckInt(data["page_num"].ToString()));
            string condition = "";
            var merIds = MerchantInfoUtil.QueryAnyIsOkMerchantId();
            condition = " and Id in (" + merIds + ")";
            if (!string.IsNullOrEmpty(MerchantName))
            {
                condition += " and CertMerchantName like '%" + MerchantName + "%'";
            }
            if (!string.IsNullOrEmpty(Mobile))
            {
                condition += " and MobilePhone='" + Mobile + "'";
            }
            if (!string.IsNullOrEmpty(MakerCode))
            {
                var Ids = MerchantInfoUtil.QueryMerchantIdByMakerCode(MakerCode);
                condition += " and Id in (" + Ids + ")";
            }
            if (!string.IsNullOrEmpty(MatchNo))
            {
                condition += " and MchtNo='" + MatchNo + "'";
            }
            if (!string.IsNullOrEmpty(SubjectType))
            {
                if (SubjectType == "1") SubjectType = "SUBJECT_TYPE_ENTERPRISE"; //企业公司
                if (SubjectType == "2") SubjectType = "SUBJECT_TYPE_INDIVIDUAL"; //个体工商户
                if (SubjectType == "3") SubjectType = "SUBJECT_TYPE_SMALL"; //小微
                condition += " and SubjectType='" + SubjectType + "'";
            }
            if (!string.IsNullOrEmpty(IsAct))
            {
                var Ids = MerchantInfoUtil.QueryIsActMerchantId(int.Parse(IsAct));
                condition += " and Id in (" + Ids + ")";
            }
            if (!string.IsNullOrEmpty(data["ActDate"].ToString()))
            {
                string[] datelist = ActDate.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                var Ids = MerchantInfoUtil.QueryActDateMerchantId(start, end);
                condition += " and Id in (" + Ids + ")";
            }
            List<RelationData> relationData = new List<RelationData>();
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            Other = new Dictionary<string, object>();
            int count = 0;
            List<Dictionary<string, object>> source = MerchantAddInfoService.List(relationData, condition, out count, pageNum, pageSize);
            foreach (Dictionary<string, object> subdata in source)
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                //商户Id
                var MerchantId = int.Parse(subdata["Id"].ToString());
                var merInfo = MerchantInfoService.Query(MerchantId);
                var userInfo = UsersService.Query(merInfo.UserId);
                curData.Add("MerchantId", subdata["Id"].ToString()); //商户Id
                curData.Add("IsAct", merInfo.IsAct); //激活状态(0 未激活 1 已激活)
                var actDate = "";
                var order = MerchantDepositOrderService.Query(" and Status>0 and MerchantId=" + MerchantId + "");
                if (order.Id > 0)
                {
                    actDate = order.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
                curData.Add("ActDate", actDate); //激活时间
                curData.Add("MerchantName", subdata["CertMerchantName"].ToString()); //商户名称
                curData.Add("Mobile", subdata["MobilePhone"].ToString()); //手机号码
                curData.Add("MakerCode", userInfo.MakerCode); //所属创客
                curData.Add("RealName", userInfo.RealName); //所属创客姓名
                var subjectType = 0;
                if (subdata["SubjectType"].ToString() == "SUBJECT_TYPE_ENTERPRISE") subjectType = 1; //企业公司
                if (subdata["SubjectType"].ToString() == "SUBJECT_TYPE_INDIVIDUAL") subjectType = 2; //个体工商户
                if (subdata["SubjectType"].ToString() == "SUBJECT_TYPE_SMALL") subjectType = 3; //小微
                curData.Add("SubjectType", subjectType); //主体类型(1 企业 2 个体 3 小微)
                curData.Add("MatchNo", subdata["MchtNo"].ToString()); //商户号
                var amountInfo = MerchantAmountSummayService.Sum("TradeCount,TotalActual,TradeAmount", " and MerchantId=" + MerchantId + "");
                curData.Add("OrderCount", decimal.Parse(amountInfo["TradeCount"].ToString())); //订单总数
                curData.Add("InComeAmount", decimal.Parse(amountInfo["TotalActual"].ToString()).ToString("f2")); //实收总金额
                curData.Add("TradeAmount", decimal.Parse(amountInfo["TradeAmount"].ToString()).ToString("f2")); //营业总金额
                dataList.Add(curData);
            }
            Other.Add("Count", count); //总数
            return dataList;
        }
        #endregion


        #region 进件管理-银联修改商户名称
        [Authorize]
        public JsonResult UnionPayEditMerchantName(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = UnionPayEditMerchantNameDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson UnionPayEditMerchantNameDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MerchantId = data["MerchantId"].ToString(); //商户Id
            string MerchantName = data["MerchantName"].ToString(); //新商户名称
            string MerchantShortName = data["MerchantShortName"].ToString(); //新商户简称
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            var Id = int.Parse(MerchantId);
            var query = main2db.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
            var merInfo = main2db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
            Dictionary<string, object> fields = new Dictionary<string, object>();
            if (query.Id > 0)
            {
                if (string.IsNullOrEmpty(MerchantName))
                {
                    query.CertMerchantName = MerchantName;
                    merInfo.Name = MerchantName;
                }
                if (!string.IsNullOrEmpty(MerchantShortName))
                {
                    fields.Add("MerchantShortname", MerchantShortName);
                }
            }
            main2db.SaveChanges();

            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion


        #region 商户管理-银联查询商户交易信息导出
        [Authorize]
        public JsonResult ExportUnionPayQueryMerchantTradeInfo(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ExportUnionPayQueryMerchantTradeInfoDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson ExportUnionPayQueryMerchantTradeInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MerchantName = data["MerchantName"].ToString(); //商户名称
            string Mobile = data["Mobile"].ToString(); //手机号码
            string MakerCode = data["MakerCode"].ToString(); //所属创客
            string MatchNo = data["MatchNo"].ToString(); //商户号
            string SubjectType = data["SubjectType"].ToString(); //主体类型(1 企业 2 个体 3 小微)
            string IsAct = data["IsAct"].ToString(); //激活状态(0 未激活 1 已激活)
            string ActDate = data["ActDate"].ToString(); //激活时间
            string condition = "";
            var merIds = MerchantInfoUtil.QueryAnyIsOkMerchantId();
            condition = " and Id in (" + merIds + ")";
            if (!string.IsNullOrEmpty(MerchantName))
            {
                condition += " and CertMerchantName like '%" + MerchantName + "%'";
            }
            if (!string.IsNullOrEmpty(Mobile))
            {
                condition += " and MobilePhone='" + Mobile + "'";
            }
            if (!string.IsNullOrEmpty(MakerCode))
            {
                var Ids = MerchantInfoUtil.QueryMerchantIdByMakerCode(MakerCode);
                condition += " and Id in (" + Ids + ")";
            }
            if (!string.IsNullOrEmpty(MatchNo))
            {
                condition += " and MchtNo='" + MatchNo + "'";
            }
            if (!string.IsNullOrEmpty(SubjectType))
            {
                if (SubjectType == "1") SubjectType = "SUBJECT_TYPE_ENTERPRISE"; //企业公司
                if (SubjectType == "2") SubjectType = "SUBJECT_TYPE_INDIVIDUAL"; //个体工商户
                if (SubjectType == "3") SubjectType = "SUBJECT_TYPE_SMALL"; //小微
                condition += " and SubjectType='" + SubjectType + "'";
            }
            if (!string.IsNullOrEmpty(IsAct))
            {
                var Ids = MerchantInfoUtil.QueryIsActMerchantId(int.Parse(IsAct));
                condition += " and Id in (" + Ids + ")";
            }
            if (!string.IsNullOrEmpty(data["ActDate"].ToString()))
            {
                string[] datelist = ActDate.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                var Ids = MerchantInfoUtil.QueryActDateMerchantId(start, end);
                condition += " and Id in (" + Ids + ")";
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            // var Sql = "select StoreName '仓库名称',StoreNo '仓库编号',MakerCode '仓库所属人编码',RealName '仓库所属人名称',Mobile '仓库所属人手机号',ManageMobile '仓库管理员手机号',Address '地址',Name '品牌',LaveNum '当前库存',c1 '出库(调拨)量',c2 '出货(发货到创客)量',c3 '激活量' from (select s.StoreName,s.StoreNo,u.MakerCode,u.RealName,u.Mobile,s.ManageMobile,s.Address,k.Name,s.LaveNum,(select count(Id) from StoreStockChange where Id>=" + minId + " and Id<=" + maxId + " and CreateDate>='" + sCreateDate + "' and CreateDate<='" + eCreateDate + "' and StoreId=s.Id and TransType=1) as c1, (select count(Id) from StoreStockChange where Id>=" + minId + " and Id<=" + maxId + " and CreateDate>='" + sCreateDate + "' and CreateDate<='" + eCreateDate + "' and StoreId=s.Id and TransType in (10,11,2)) as c2, (select ActCount from KxsStatServer.StoreAct202211 where StoreId=s.Id) as c3, ua.FixedAmount, ua.ValidAmount, ua.TempAmount, (select sum(PromissAmount) from StoreHouseAmountPromiss where ToUserId=s.UserId and `Status`=1) as PromissAmount from StoreHouse s left join Users u on s.BrandId>0 and s.UserId=u.Id left join KqProducts k on s.BrandId=k.Id left join UserAccount ua on s.UserId=ua.Id) tb where (c1>0 or c2>0 or c3>0)" + condtion + "";
            // var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
            // var FileName = "仓库统计管理记录" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            // string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + Sql + "\",\"FileName\":\"" + FileName + "\",\"MaxCount\":\"0\"}";
            // RedisDbconn.Instance.AddList("ExportQueue", SendData);

            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion


    }
}
