/*
 * 分仓额度担保记录
 */

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 StoreHouseAmountPromissController : BaseController
    {
        public StoreHouseAmountPromissController(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(StoreHouseAmountPromiss data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询分仓额度担保记录列表

        /// <summary>
        /// 分仓额度担保记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(StoreHouseAmountPromiss data, string FromUserIdMakerCode, string FromUserIdRealName, string ToUserIdMakerCode, string ToUserIdRealName, int page = 1, int limit = 30)
        {

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

            Fields.Add("CreateDate", "3"); //时间


            string condition = " and Status>-1";
            //担保人创客编号
            if (!string.IsNullOrEmpty(FromUserIdMakerCode))
            {
                condition += " and FromUserId in (select UserId from UserForMakerCode where MakerCode='" + FromUserIdMakerCode + "')";
            }
            //担保人真实姓名
            if (!string.IsNullOrEmpty(FromUserIdRealName))
            {
                condition += " and FromUserId in (select UserId from UserForRealName where RealName='" + FromUserIdRealName + "')";
            }
            //担保对象创客编号
            if (!string.IsNullOrEmpty(ToUserIdMakerCode))
            {
                condition += " and ToUserId in (select UserId from UserForMakerCode where MakerCode='" + ToUserIdMakerCode + "')";
            }
            //担保对象真实姓名
            if (!string.IsNullOrEmpty(ToUserIdRealName))
            {
                condition += " and ToUserId in (select UserId from UserForRealName where RealName='" + ToUserIdRealName + "')";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreHouseAmountPromiss", 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)
            {
                //担保人
                int FromUserId = int.Parse(function.CheckInt(dic["FromUserId"].ToString()));
                Users fromuserid_Users = db.Users.FirstOrDefault(m => m.Id == FromUserId) ?? new Users();
                dic["FromUserIdMakerCode"] = fromuserid_Users.MakerCode;
                dic["FromUserIdRealName"] = fromuserid_Users.RealName;
                dic.Remove("FromUserId");
                //担保对象
                int ToUserId = int.Parse(function.CheckInt(dic["ToUserId"].ToString()));
                Users touserid_Users = db.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();
                dic["ToUserIdMakerCode"] = touserid_Users.MakerCode;
                dic["ToUserIdRealName"] = touserid_Users.RealName;
                dic.Remove("ToUserId");

                //是否使用
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["StatusName"] = "确认中";
                if (Status == 1) dic["StatusName"] = "成功";
                if (Status == 2) dic["StatusName"] = "失败";

            }
            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(string FromUserId, string ToUserId, decimal PromissAmount, string SeoDescription)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            var FromUserIdInfo = db.Users.FirstOrDefault(m => m.MakerCode == FromUserId);
            var ToUserIdInfo = db.Users.FirstOrDefault(m => m.MakerCode == ToUserId);

            db.StoreHouseAmountPromiss.Add(new StoreHouseAmountPromiss()
            {
                CreateDate = DateTime.Now,
                FromUserId = FromUserIdInfo.Id,
                ToUserId = ToUserIdInfo.Id,
                PromissAmount = PromissAmount,
                SeoDescription = SeoDescription
            });
            db.SaveChanges();

            return "success";
        }


        public string Adds(StoreHouseAmountPromiss data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            var FromUserId = db.Users.FirstOrDefault(m => m.MakerCode == data.FromUserId.ToString());
            var ToUserId = db.Users.FirstOrDefault(m => m.MakerCode == data.ToUserId.ToString());

            Fields.Add("FromUserId", FromUserId); //担保人
            Fields.Add("ToUserId", ToUserId); //担保对象
            Fields.Add("PromissAmount", data.PromissAmount); //担保金额
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("StoreHouseAmountPromiss", Fields, 0);
            AddSysLog(data.Id.ToString(), "StoreHouseAmountPromiss", "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;


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

        #endregion

        #region 修改分仓额度担保记录

        /// <summary>
        /// 增加或修改分仓额度担保记录信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(StoreHouseAmountPromiss data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            StoreHouseAmountPromiss storeHouseAmountPromiss = db.StoreHouseAmountPromiss.FirstOrDefault(m => m.Id == data.Id);
            Fields.Add("FromUserId", storeHouseAmountPromiss.FromUserId); //担保人
            Fields.Add("ToUserId", storeHouseAmountPromiss.ToUserId); //担保对象
            if (data.PromissAmount > storeHouseAmountPromiss.PromissAmount)
            {
                return "修改保证金不可高于原保证金额度！";
            }
            else
            {
                Fields.Add("PromissAmount", data.PromissAmount); //担保金额
            }

            Fields.Add("SeoTitle", storeHouseAmountPromiss.SeoTitle);
            Fields.Add("SeoKeyword", storeHouseAmountPromiss.SeoKeyword);
            Fields.Add("SeoDescription", storeHouseAmountPromiss.SeoDescription);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("StoreHouseAmountPromiss", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "StoreHouseAmountPromiss", "update");
            UserAccount userAccount = db.UserAccount.FirstOrDefault(m => m.Id == data.ToUserId) ?? new UserAccount();
            userAccount.ValidAmount = userAccount.ValidAmount - (storeHouseAmountPromiss.PromissAmount - data.PromissAmount);//减去担保金调整差额
            db.SaveChanges();
            var storeA = db.StoreHouseAmountPromiss.FirstOrDefault(m => m.Id == data.Id);
            var ToUserId = db.Users.FirstOrDefault(m => m.Id == storeHouseAmountPromiss.ToUserId);
            RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
            {
                UserId = storeHouseAmountPromiss.FromUserId, //接收创客
                Title = "仓库担保调低", //标题
                Content = "<div class='f16'>已经为创客 <br/>" + ToUserId.RealName + ' ' + ToUserId.MakerCode + "进行分仓额度担保调低<br/>担保金额：" + storeA.PromissAmount + " </div>", //内容
                Summary = "已经为创客" + ToUserId.RealName + ' ' + ToUserId.MakerCode + "进行分仓额度担保调低，担保金额：" + storeA.PromissAmount,
                CreateDate = DateTime.Now,
            }));

            return "success";
        }

        #endregion

        #region 删除分仓额度担保记录信息

        /// <summary>
        /// 删除分仓额度担保记录信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "StoreHouseAmountPromiss", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                StoreHouseAmountPromiss storeHouseAmountPromiss = db.StoreHouseAmountPromiss.FirstOrDefault(m => m.Id == id);
                Fields.Add("Status", -1);
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == storeHouseAmountPromiss.ToUserId);
                userAccount.ValidAmount -= storeHouseAmountPromiss.PromissAmount;//减除保证金
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("StoreHouseAmountPromiss", Fields, id);
            }
            db.SaveChanges();
            StoreHouseAmountPromiss storep = db.StoreHouseAmountPromiss.FirstOrDefault(m => m.Id == Convert.ToInt32(Id));
            var ToUserInfo = db.Users.FirstOrDefault(m => m.Id == storep.ToUserId);
            RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
            {
                UserId = storep.FromUserId, //接收创客
                Title = "取消仓库担保", //标题
                Content = "<div class='f16'>已取消为创客 <br/>" + ToUserInfo.RealName + ' ' + ToUserInfo.MakerCode + "的仓库担保金额 " + storep.PromissAmount + "元</div>", //内容
                Summary = "已取消为创客 " + ToUserInfo.RealName + ' ' + ToUserInfo.MakerCode + "的仓库担保金额 " + storep.PromissAmount + "元",
                CreateDate = DateTime.Now,
            }));

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "StoreHouseAmountPromiss", "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("StoreHouseAmountPromiss", 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, "StoreHouseAmountPromiss", "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("StoreHouseAmountPromiss", 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("StoreHouseAmountPromiss", Sort, Id);

            AddSysLog(Id.ToString(), "StoreHouseAmountPromiss", "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.StoreHouseAmountPromiss.Add(new StoreHouseAmountPromiss()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(StoreHouseAmountPromiss data, string FromUserIdMakerCode, string FromUserIdRealName, string ToUserIdMakerCode, string ToUserIdRealName)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间


            string condition = " and Status>-1";
            //担保人创客编号
            if (!string.IsNullOrEmpty(FromUserIdMakerCode))
            {
                condition += " and FromUserId in (select UserId from UserForMakerCode where MakerCode='" + FromUserIdMakerCode + "')";
            }
            //担保人真实姓名
            if (!string.IsNullOrEmpty(FromUserIdRealName))
            {
                condition += " and FromUserId in (select UserId from UserForRealName where RealName='" + FromUserIdRealName + "')";
            }
            //担保对象创客编号
            if (!string.IsNullOrEmpty(ToUserIdMakerCode))
            {
                condition += " and ToUserId in (select UserId from UserForMakerCode where MakerCode='" + ToUserIdMakerCode + "')";
            }
            //担保对象真实姓名
            if (!string.IsNullOrEmpty(ToUserIdRealName))
            {
                condition += " and ToUserId in (select UserId from UserForRealName where RealName='" + ToUserIdRealName + "')";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreHouseAmountPromiss", Fields, "Id desc", "0", 1, 20000, condition, "FromUserId,ToUserId,PromissAmount", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //担保人
                int FromUserId = int.Parse(function.CheckInt(dic["FromUserId"].ToString()));
                Users fromuserid_Users = db.Users.FirstOrDefault(m => m.Id == FromUserId) ?? new Users();
                dic["FromUserIdMakerCode"] = fromuserid_Users.MakerCode;
                dic["FromUserIdRealName"] = fromuserid_Users.RealName;
                dic.Remove("FromUserId");
                //担保对象
                int ToUserId = int.Parse(function.CheckInt(dic["ToUserId"].ToString()));
                Users touserid_Users = db.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();
                dic["ToUserIdMakerCode"] = touserid_Users.MakerCode;
                dic["ToUserIdRealName"] = touserid_Users.RealName;
                dic.Remove("ToUserId");

            }

            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("FromUserIdMakerCode", "担保人创客编号");
            ReturnFields.Add("FromUserIdRealName", "担保人真实姓名");
            ReturnFields.Add("ToUserIdMakerCode", "担保对象创客编号");
            ReturnFields.Add("ToUserIdRealName", "担保对象真实姓名");
            ReturnFields.Add("PromissAmount", "担保金额");

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

        #endregion

    }
}
