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.Main1;
using MySystem.Service.Main1;
using LitJson;
using Library;
using MySystem.Service.KxsMain;

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

        #region 进件管理-直连商户列表
        [Authorize]
        public JsonResult DirectList(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Other = new Dictionary<string, object>();
            List<Dictionary<string, object>> dataList = DirectListDo(value, out Other);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = Other });
        }
        private List<Dictionary<string, object>> DirectListDo(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 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"; //个体工商户
                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["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 status = int.Parse(subdata["Status"].ToString());
                var queryCount = int.Parse(subdata["QueryCount"].ToString());

                //商户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; //个体工商户

                curData.Add("Id", subdata["Id"].ToString()); //Id
                curData.Add("SubjectType", subjectType); //主体类型(1 企业 2 个体)
                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("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 DirectQueryFailReason(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DirectQueryFailReasonDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        private Dictionary<string, object> DirectQueryFailReasonDo(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 DirectDetail(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DirectDetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        private Dictionary<string, object> DirectDetailDo(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 DirectSubmit(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = DirectSubmitDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson DirectSubmitDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MerchantId = data["MerchantId"].ToString(); //商户Id
            var info = MerchantAddInfoUtil.DirectSubmitDo(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 DirectQueryMerchantTradeInfo(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Other = new Dictionary<string, object>();
            List<Dictionary<string, object>> dataList = DirectQueryMerchantTradeInfoDo(value, out Other);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = Other });
        }
        private List<Dictionary<string, object>> DirectQueryMerchantTradeInfoDo(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 AliPID = data["AliPID"].ToString(); //支付宝PID
            string WeChatNo = data["WeChatNo"].ToString(); //微信商户号
            string SubjectType = data["SubjectType"].ToString(); //主体类型(1 企业 2 个体)
            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(AliPID))
            {
                condition += " and AlipayPid='" + AliPID + "'";
            }
            if (!string.IsNullOrEmpty(WeChatNo))
            {
                condition += " and SubMchid='" + WeChatNo + "'";
            }
            if (!string.IsNullOrEmpty(SubjectType))
            {
                if (SubjectType == "1") SubjectType = "SUBJECT_TYPE_ENTERPRISE"; //企业公司
                if (SubjectType == "2") SubjectType = "SUBJECT_TYPE_INDIVIDUAL"; //个体工商户
                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; //个体工商户
                curData.Add("AliPID", subdata["AlipayPid"].ToString()); //支付宝PID
                curData.Add("AliPayToken", subdata["AlipayAuthToken"].ToString()); //支付宝token
                curData.Add("WeChatNo", subdata["SubMchid"].ToString()); //微信商户号
                curData.Add("SubjectType", subjectType); //主体类型(1 企业 2 个体 3 小微)
                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 商户管理-直连添加支付宝PID和微信商户号
        [Authorize]
        public JsonResult DirectAddPIDOrWeChatNo(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = DirectAddPIDOrWeChatNoDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson DirectAddPIDOrWeChatNoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MerchantId = data["MerchantId"].ToString(); //商户Id
            string AliPPID = data["AliPPID"].ToString(); //支付宝PID
            string AliPayToken = data["AliPayToken"].ToString(); //支付宝token
            string WeChatNo = data["WeChatNo"].ToString(); //微信商户号
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            // var query = MerchantAddInfoService.Query(int.Parse(MerchantId));
            var Id = int.Parse(MerchantId);
            var query = main1db.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
            Dictionary<string, object> fields = new Dictionary<string, object>();
            if (query.Id > 0)
            {
                if (string.IsNullOrEmpty(query.AlipayPid))
                {
                    // fields.Add("AlipayPid", AliPPID); //支付宝PID
                    query.AlipayPid = AliPPID;
                }
                if (!string.IsNullOrEmpty(AliPayToken))
                {
                    // fields.Add("AlipayAuthToken", AliPayToken); //支付宝token
                    query.AlipayAuthToken = AliPayToken;
                }
                if (string.IsNullOrEmpty(query.SubMchid))
                {
                    // fields.Add("SubMchid", WeChatNo); //微信商户号
                    query.SubMchid = WeChatNo;
                }
            }
            main1db.SaveChanges();
            // AppResultJson resultJson = MerchantAddInfoService.Edit(fields, int.Parse(MerchantId), false);
            return new AppResultJson() { Status = "1", Info = "添加成功", Data = Obj };
        }
        #endregion


        #region 商户管理-直连查询商户交易信息导出
        [Authorize]
        public JsonResult ExportDirectQueryMerchantTradeInfo(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ExportDirectQueryMerchantTradeInfoDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson ExportDirectQueryMerchantTradeInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MerchantName = data["MerchantName"].ToString(); //商户名称
            string Mobile = data["Mobile"].ToString(); //手机号码
            string MakerCode = data["MakerCode"].ToString(); //所属创客
            string AliPID = data["AliPID"].ToString(); //支付宝PID
            string WeChatNo = data["WeChatNo"].ToString(); //微信商户号
            string SubjectType = data["SubjectType"].ToString(); //主体类型(1 企业 2 个体)
            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(AliPID))
            {
                condition += " and AlipayPid='" + AliPID + "'";
            }
            if (!string.IsNullOrEmpty(WeChatNo))
            {
                condition += " and SubMchid='" + WeChatNo + "'";
            }
            if (!string.IsNullOrEmpty(SubjectType))
            {
                if (SubjectType == "1") SubjectType = "SUBJECT_TYPE_ENTERPRISE"; //企业公司
                if (SubjectType == "2") SubjectType = "SUBJECT_TYPE_INDIVIDUAL"; //个体工商户
                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

    }
}
