/*
 * 交易记录
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.SpModels;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class SpTradeRecordController : BaseController
    {
        public SpTradeRecordController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["SpSqlConnStr"].ToString();
        }

        #region 交易记录列表

        /// <summary>
        /// 根据条件查询交易记录列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(TradeRecord data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 根据条件查询交易记录列表

        /// <summary>
        /// 交易记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(TradeRecord data, string TradeStatusSelect, string ProductTypeSelect, string CreateDateData, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("MerNo", "1"); //商户编号
            Fields.Add("TradeSnNo", "1"); //机具号
            Fields.Add("ChannelSerial", "1"); //渠道流水号


            string condition = " and Status>-1";
            //交易状态
            if (!string.IsNullOrEmpty(TradeStatusSelect))
            {
                condition += " and TradeStatus=" + TradeStatusSelect;
            }
            //产品类型
            if (!string.IsNullOrEmpty(ProductTypeSelect))
            {
                condition += " and ProductType=" + ProductTypeSelect;
            }
            
            //创建时间
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.SpTables).IndexData("TradeRecord", Fields, "Id desc", "0", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //状态
                string Status = dic["Status"].ToString();
                if (Status == "1") dic["Status"] = "待同步";
                if (Status == "2") dic["Status"] = "已同步";
                if (Status == "") dic["Status"] = "";
                //交易状态
                string TradeStatus = dic["TradeStatus"].ToString();
                if (TradeStatus == "1") dic["TradeStatus"] = "成功";
                if (TradeStatus == "2") dic["TradeStatus"] = "失败";
                if (TradeStatus == "") dic["TradeStatus"] = "";
                //银行卡类型
                string BankCardType = dic["BankCardType"].ToString();
                if (BankCardType == "0001") dic["BankCardType"] = "贷记卡";
                if (BankCardType == "0002") dic["BankCardType"] = "借记卡";
                if (BankCardType == "") dic["BankCardType"] = "";
                //产品类型
                dic["ProductType"] = RelationClass.GetKqProductBrandList(dic["ProductType"].ToString());

            }
            return Json(obj);
        }

        #endregion

        #region 增加交易记录

        /// <summary>
        /// 增加或修改交易记录信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 增加交易记录

        /// <summary>
        /// 增加或修改交易记录信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(TradeRecord data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.SpTables).Add("TradeRecord", Fields, 0);
            AddSysLog(data.Id.ToString(), "TradeRecord", "add");
            spdb.SaveChanges();

            return "success";
        }

        #endregion

        #region 修改交易记录

        /// <summary>
        /// 增加或修改交易记录信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            TradeRecord editData = spdb.TradeRecord.FirstOrDefault(m => m.Id == Id) ?? new TradeRecord();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改交易记录

        /// <summary>
        /// 增加或修改交易记录信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(TradeRecord data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.SpTables).Edit("TradeRecord", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "TradeRecord", "update");
            spdb.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除交易记录信息

        /// <summary>
        /// 删除交易记录信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "TradeRecord", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.SpTables).Edit("TradeRecord", Fields, id);
            }
            spdb.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "TradeRecord", "open");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.SpTables).Edit("TradeRecord", Fields, id);
            }
            spdb.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "TradeRecord", "close");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 0);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.SpTables).Edit("TradeRecord", Fields, id);
            }
            spdb.SaveChanges();
            return "success";
        }

        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id"></param>
        public string Sort(int Id, int Sort)
        {
            new AdminContentOther(_accessor.HttpContext, PublicFunction.SpTables).Sort("TradeRecord", Sort, Id);

            AddSysLog(Id.ToString(), "TradeRecord", "sort");
            return "success";
        }
        #endregion

        #region 导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Import(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];

                spdb.TradeRecord.Add(new TradeRecord()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                });
                spdb.SaveChanges();
            }
            AddSysLog("0", "TradeRecord", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(TradeRecord data, string TradeStatusSelect, string ProductTypeSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("MerNo", "1"); //商户编号
            Fields.Add("ChannelSerial", "1"); //渠道流水号


            string condition = " and Status>-1";
            //交易状态
            if (!string.IsNullOrEmpty(TradeStatusSelect))
            {
                condition += " and TradeStatus=" + TradeStatusSelect;
            }
            //产品类型
            if (!string.IsNullOrEmpty(ProductTypeSelect))
            {
                condition += " and ProductType=" + ProductTypeSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.SpTables).IndexData("TradeRecord", Fields, "Id desc", "0", 1, 20000, condition, "TradeSerialNo,MerNo,TradeAmount,TradeStatus,TradeDate,TradeTime,BankCardType,BankCardNo,SettleFee,Remark,ProductType,AgentNo,ChannelSerial", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //交易状态
                string TradeStatus = dic["TradeStatus"].ToString();
                if (TradeStatus == "1") dic["TradeStatus"] = "成功";
                if (TradeStatus == "2") dic["TradeStatus"] = "失败";
                if (TradeStatus == "") dic["TradeStatus"] = "";
                //银行卡类型
                string BankCardType = dic["BankCardType"].ToString();
                if (BankCardType == "0001") dic["BankCardType"] = "贷记卡";
                if (BankCardType == "0002") dic["BankCardType"] = "借记卡";
                if (BankCardType == "") dic["BankCardType"] = "";
                //产品类型
                string ProductType = dic["ProductType"].ToString();
                if (ProductType == "KYSPOS") dic["ProductType"] = "快益刷";
                if (ProductType == "KPOS") dic["ProductType"] = "快联盟大POS";
                if (ProductType == "SIGNPOS") dic["ProductType"] = "快联盟电签POS";
                if (ProductType == "SUPPOS") dic["ProductType"] = "超级Mpos";
                if (ProductType == "") dic["ProductType"] = "";

            }

            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();
            ReturnFields.Add("TradeSerialNo", "交易单号");
            ReturnFields.Add("MerNo", "商户编号");
            ReturnFields.Add("TradeAmount", "交易金额");
            ReturnFields.Add("TradeStatus", "交易状态");
            ReturnFields.Add("TradeDate", "交易日期");
            ReturnFields.Add("TradeTime", "交易时间");
            ReturnFields.Add("BankCardType", "银行卡类型");
            ReturnFields.Add("BankCardNo", "交易卡号");
            ReturnFields.Add("SettleFee", "出款手续费");
            ReturnFields.Add("Remark", "备注");
            ReturnFields.Add("ProductType", "产品类型");
            ReturnFields.Add("AgentNo", "代理商编号");
            ReturnFields.Add("ChannelSerial", "渠道流水号");

            result.Add("Fields", ReturnFields);
            AddSysLog("0", "TradeRecord", "ExportExcel");
            return Json(result);
        }

        #endregion

    }
}
