/*
 * 商家
 */

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.Models;
using Library;
using LitJson;
using MySystemLib;

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

        #region 商家列表

        /// <summary>
        /// 根据条件查询商家列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(Merchants data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            string Condition = "";
            Condition += "Name:\"" + data.Name + "\",";
            Condition += "Principal:\"" + data.Principal + "\",";
            Condition += "Phone:\"" + data.Phone + "\",";
            Condition += "IsAuth:\"" + data.IsAuth + "\",";

            if (!string.IsNullOrEmpty(Condition))
            {
                Condition = Condition.TrimEnd(',');
                Condition = ", where: {" + Condition + "}";
            }
            ViewBag.Condition = Condition;
            return View();
        }

        #endregion

        #region 根据条件查询商家列表

        /// <summary>
        /// 商家列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(Merchants data, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("Name", "2"); //名称
            Fields.Add("Principal", "2"); //负责人
            Fields.Add("Phone", "2"); //联系电话
            Fields.Add("IsAuth", "1"); //是否认证

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Merchants", Fields, "Id desc", "False", page, limit);
            
            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(Merchants data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("Name", data.Name); //名称
            Fields.Add("Logo", data.Logo); //Logo图片
            Fields.Add("Areas", data.Areas); //所在地区
            Fields.Add("Principal", data.Principal); //负责人
            Fields.Add("Phone", data.Phone); //联系电话
            Fields.Add("BusinessLicense", data.BusinessLicense); //营业执照
            Fields.Add("StarNum1", data.StarNum1); //快递包装评分
            Fields.Add("FollowCount", data.FollowCount); //关注数
            Fields.Add("IsAuth", data.IsAuth); //是否认证
            Fields.Add("CommentCount", data.CommentCount); //评论数
            Fields.Add("Address", data.Address); //详细地址
            Fields.Add("StarNum2", data.StarNum2); //送货速度评分
            Fields.Add("StarNum3", data.StarNum3); //服务态度评分
            Fields.Add("UserName", data.UserName); //账号
            if (!string.IsNullOrEmpty(data.LoginPwd)) //密码不为空就修改密码，否则不操作
            {
                Fields.Add("LoginPwd", function.MD532(data.LoginPwd)); //登录密码
            }
            if (!string.IsNullOrEmpty(data.PayPwd)) //密码不为空就修改密码，否则不操作
            {
                Fields.Add("PayPwd", function.MD532(data.PayPwd)); //支付密码
            }
            Fields.Add("IsRecommend", data.IsRecommend); //推荐
            Fields.Add("Title", data.Title);
            Fields.Add("Title2", data.Title2);
            Fields.Add("Status", 1);

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

            return "success";
        }

        #endregion

        #region 修改商家

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

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

        #endregion

        #region 修改商家

        /// <summary>
        /// 增加或修改商家信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(Merchants data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("Name", data.Name); //名称
            Fields.Add("Logo", data.Logo); //Logo图片
            Fields.Add("Areas", data.Areas); //所在地区
            Fields.Add("Principal", data.Principal); //负责人
            Fields.Add("Phone", data.Phone); //联系电话
            Fields.Add("BusinessLicense", data.BusinessLicense); //营业执照
            Fields.Add("StarNum1", data.StarNum1); //快递包装评分
            Fields.Add("FollowCount", data.FollowCount); //关注数
            Fields.Add("IsAuth", data.IsAuth); //是否认证
            Fields.Add("CommentCount", data.CommentCount); //评论数
            Fields.Add("Address", data.Address); //详细地址
            Fields.Add("StarNum2", data.StarNum2); //送货速度评分
            Fields.Add("StarNum3", data.StarNum3); //服务态度评分
            Fields.Add("UserName", data.UserName); //账号
            if (!string.IsNullOrEmpty(data.LoginPwd)) //密码不为空就修改密码，否则不操作
            {
                Fields.Add("LoginPwd", function.MD532(data.LoginPwd)); //登录密码
            }
            if (!string.IsNullOrEmpty(data.PayPwd)) //密码不为空就修改密码，否则不操作
            {
                Fields.Add("PayPwd", function.MD532(data.PayPwd)); //支付密码
            }
            Fields.Add("IsRecommend", data.IsRecommend); //推荐
            Fields.Add("Title", data.Title);
            Fields.Add("Title2", data.Title2);

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Merchants", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "Merchants", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除商家信息

        /// <summary>
        /// 删除商家信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Merchants", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Delete("Merchants", id);
            }
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Merchants", "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.MainTables).Edit("Merchants", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Merchants", "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.MainTables).Edit("Merchants", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

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

            AddSysLog(Id.ToString(), "Merchants", "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];

                db.Merchants.Add(new Merchants()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                });
                db.SaveChanges();
            }
            AddSysLog("0", "Merchants", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(Merchants data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("Name", "2"); //名称
            Fields.Add("Principal", "2"); //负责人
            Fields.Add("Phone", "2"); //联系电话
            Fields.Add("IsAuth", "1"); //是否认证

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Merchants", Fields, "Id desc", "False", 1, 20000, "", "", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;

            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>();

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

        #endregion
                
    }
}
