using jiouosdp.Controllers;
using RFrameGenerate.BLL;
using RFrameGenerate.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RFrameGenerate.Common;

namespace jiouosdp.Areas.HeadOffice.Controllers
{
    public class HeadController : BaseController
    {
        #region 商家
        //
        // GET: /HeadOffice/Head/

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult LoadMerchantListdata(GridModel gridModel, string agent, string userid, string title, string type)
        {
            Guid? guid = null;

            if (!string.IsNullOrEmpty(agent))
            {
                guid = new Guid(agent);
            }

            gridModel.datarows = (from s in MerchantManage.GetMerchantPageList(gridModel, guid, userid, title, type)
                                  select new
                                  {
                                      id = s.MerchantGuid,//定义当前行数据的一个传输识别名称，一般以主键为名称，可以省略()
                                      cell = new object[]
                                                     {
                                                         s.MerchantGuid,
                                                         s.StoreTitle,
                                                         s.UserID,
                                                         s.Telephone,
                                                         s.EMail,
                                                         s.UserType == null ? "" : DictionaryConst.Versionb.GetText(s.UserType.Value),
                                                         GetPackName(s.UserType,s.MerchantGuid),
                                                         s.CreateDate != null ? s.CreateDate.Value.ToString("yyyy-MM-dd"):"",
                                                         s.ExpireDate !=null ? s.ExpireDate.Value.ToString("yyyy-MM-dd"):"",
                                                         s.IsEnable,
                                                         GetYear(s.CreateDate,s.ExpireDate)
                                                      }
                                  }).ToArray();
            return Json(gridModel.PackagePageModel());
        }

        private int GetYear(DateTime? CreateDate, DateTime? ExpireDate)
        {
            if (CreateDate == null || ExpireDate == null)
                return 0;
            return ExpireDate.Value.Year - CreateDate.Value.Year;
        }
        public JsonResult SetMerEnable(Guid id, bool enable)
        {
            var result = MerchantManage.SetEnabel(id, enable);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        bool IsLegal(string str)
        {
            if (str.Length < 3 || str.Length > 18)
            {
                return false;
            }
            for (int i = 0; i < str.Length; i++)
            {
                if (!(('a' <= str[i] && str[i] <= 'z') || ('0' <= str[i] && str[i] <= '9') || str[i] == '-'))
                {
                    return false;
                }

            }
            return true;
        }
        public JsonResult AddMerchantsPar(T_BAS_Merchants entity, int year, string packGuid, int? day)
        {

            if (entity.UserID.Length < 3)
            {
                return Json(new { Result = "NO", Msg = "userid最少长度3个字符" });
            }

            if (IsLegal(entity.UserID.ToLower()) != true)
            {
                return Json(new { Result = "NO", Msg = "ID只能包含英文字段,数字,\"-\",长度3-12位" });
            }

            //补充：测试版默认为5天，增加测试版判断即可 Bing 20160114 
            if (year <= 0 && (day ?? 0) <= 0)
            {
                return Json(new { Result = "NO", Msg = "开通年数必须大于或等于1" });
            }

            var merGuid = Guid.NewGuid();
            var oldmerGuid = RFrameGenerate.Common.CurrentManage.MerchantGuid;

            RFrameGenerate.Common.CurrentUser.SetMerchantGuid(merGuid);
            RFrameGenerate.Common.CurrentUser.SetSMerchantGuid(merGuid);
            Result result;
            try
            {
                entity.StoreUrl = RFrameGenerate.Common.CurrentManage.Domain.Replace("http://", entity.UserID + ".");
                entity.Password = Utils.Md5(entity.Password);
                entity.AgentGuid = RFrameGenerate.Common.CurrentUser.GetCurrUserGuid();
                entity.MerchantGuid = merGuid;
                entity.StoreState = true;
                entity.CloseReason = "";
                entity.CreateDate = DateTime.Now;
                if ((day ?? 0) <= 0)
                {
                    entity.ExpireDate = entity.CreateDate.Value.AddYears(year);
                }
                else
                {
                    entity.ExpireDate = entity.CreateDate.Value.AddDays(day.Value);//a)	试用版（5天），所有功能
                }

                entity.TotalDistributionOrders = 0;
                entity.TotalDistributor = 0;
                entity.HomePageProductNum = 4;
                entity.MentionedAmount = 0;
                entity.DistributionOrdersAmount = 0;
                entity.CumulativeDistributionAmount = 0;
                entity.IsEnable = true;
                entity.IsCustomerServices = false;

                #region 添加参数
                if ((day ?? 0) <= 0)
                {
                    result = MerchantManage.AddMerchantsPar(entity, year, packGuid, entity.UserType.Value);
                }
                else
                {
                    result = MerchantManage.AddMerchantTemp(entity);
                }


                if (result.State)
                {
                    List<T_SYS_Parameter> plist = new List<T_SYS_Parameter>();
                    var parameterName = "extendedReceipt,refundService_paid,distributionchart,secondCommission,firstCommission,thirdCommission,withdrawalNumberLimits,refundService_validity,refundService_delivery,refundService_completed,amountLimit,autoExpirationTime,extNumber,payments,withdrawalAmountLimits,commissionSettlementTime,distributorRelations,topNumber,auditApproach,minAmount,openRefundService,automaticWrite,distributionVisible";
                    var parameterValue = "3,2,1,15,20,10,10,7,3,5,20,0,1,微信钱包,10,6,分销商购买获得一级佣金 ,20,0,1,1,7,2";
                    var pn = parameterName.Split(',');
                    var pv = parameterValue.Split(',');
                    var length = pn.Length;

                    for (int i = 0; i < length; i++)
                    {
                        T_SYS_Parameter parameterObj = new T_SYS_Parameter()
                        {
                            ParameterGuid = Guid.NewGuid(),
                            MerchantGuid = merGuid,
                            ParameterName = pn[i],
                            ParameterValue = pv[i]
                        };
                        plist.Add(parameterObj);
                    }
                    result = ParameterManage.AddExtSettingParameters(plist);
                }
                #endregion
            }
            catch (Exception ex)
            {
                return Json(new { Result = "NO", Msg = ex.Message });
            }
            RFrameGenerate.Common.CurrentUser.SetMerchantGuid(oldmerGuid);
            RFrameGenerate.Common.CurrentUser.SetSMerchantGuid(oldmerGuid);
            if (result.State)
            {
                return Json(new { Result = "OK", Data = entity });
            }

            return Json(new { Result = "NO", Msg = result.Msg });
        }

        public JsonResult EditMerchantsPar(Guid merchantGuid, int userType, string packGuid, bool isEditTempTest, int years)
        {
            Result result;
            try
            {
                if (!isEditTempTest)
                {
                    result = MerchantManage.EditMerchantsPar(merchantGuid, userType, packGuid);
                }
                else
                {   //补充：测试版升级创业/旗舰 Bing 20160114 
                    result = MerchantManage.EditMerchantsParTempTest(merchantGuid, userType, packGuid, years);
                }

            }
            catch (Exception ex)
            {
                return Json(new { Result = "NO", Msg = ex.Message });
            }
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }

            return Json(new { Result = "NO", Msg = result.Msg });
        }

        public JsonResult HeadChangePassword(Guid id, string password)
        {
            if (string.IsNullOrEmpty(password))
                return Json(new { Result = "OK" });

            var merGuid = id;
            var oldmerGuid = RFrameGenerate.Common.CurrentManage.MerchantGuid;

            RFrameGenerate.Common.CurrentUser.SetMerchantGuid(merGuid);
            RFrameGenerate.Common.CurrentUser.SetSMerchantGuid(merGuid);

            var result = MerchantManage.ChangePassword(merGuid, password);

            RFrameGenerate.Common.CurrentUser.SetMerchantGuid(oldmerGuid);
            RFrameGenerate.Common.CurrentUser.SetSMerchantGuid(oldmerGuid);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        //删除商家
        public JsonResult DelMerchant(Guid guid)
        {
            var result = AgentManage.DelMerchant(guid);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        //商家续费
        public JsonResult SaveRenew(Guid guid, decimal money, int years)
        {
            var result = AgentManage.Renew(guid, money, years);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        #endregion

        #region Agent

        public ActionResult Agent()
        {
            return View();
        }
        //代理商消费记录
        public ActionResult Records()
        {
            return View();
        }

        public JsonResult LoadAgentListdata(GridModel gridModel, string userid, string company)
        {
            gridModel.datarows = (from s in AgentManage.GetAgentPageList(gridModel, userid, company)
                                  select new
                                  {
                                      id = s.AgentGuid,//定义当前行数据的一个传输识别名称，一般以主键为名称，可以省略()
                                      cell = new object[]
                                                     {
                                                         s.UserID,
                                                         s.AgentName,
                                                         s.AgentCompany,
                                                         s.AgentTel,
                                                         s.CumulativeAmount,
                                                         s.DepositsAmount,
                                                         GetLevel(s.LevelGuid.Value),
                                                         s.StartDate.ToString("yyyy-MM-dd"),
                                                         s.ExpireData.ToString("yyyy-MM-dd"),
                                                         s.IsEnable
                                                      }
                                  }).ToArray();
            return Json(gridModel.PackagePageModel());
        }
        //加载代理商消费记录
        public JsonResult LoadAgentRecords(GridModel gridModel, string agentCompany, string userID)
        {
            gridModel.datarows = (from s in AgentManage.LoadAgentRecords(gridModel, agentCompany, userID).OrderByDescending(a => a.OpenDate)
                                  select new
                                  {
                                      id = s.OpenMerchantRrecordGuid,//定义当前行数据的一个传输识别名称，一般以主键为名称，可以省略()
                                      cell = new object[]
                                                     {
                                                         s.OpenMerchantRrecordGuid,
                                                         s.MerchantGuid,
                                                         s.AgentGuid,
                                                         s.AgentCompany,
                                                         s.UserID,
                                                         s.StoreTitle,
                                                         DictionaryConst.Versionb.GetText(s.OpenType==null?0:s.OpenType.Value),
                                                         s.OpenDate.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                                                         DictionaryConst.PayType.GetText(s.PayType==null?0:s.PayType.Value),
                                                         s.Amount,
                                                         s.AvailableBalance,
                                                         s.Remark
                                                      }
                                  }).ToArray();
            return Json(gridModel.PackagePageModel());
        }

        private string GetLevel(Guid levelGuid)
        {
            return LevelManage.GetLevelName(levelGuid);
        }

        public JsonResult SetEnable(Guid id, bool enable)
        {
            var result = AgentManage.SetEnabel(id, enable);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        public JsonResult AddAgentPar(T_BAS_Agents entity, int year)
        {
            if (IsLegal(entity.UserID.ToLower()) != true)
            {
                return Json(new { Result = "NO", Msg = "ID只能包含英文字段,数字,\"-\",长度3-12位" });
            }
            if (year <= 0)
                return Json(new { Result = "NO", Msg = "开通年数必须大于或等于1" });

            entity.StartDate = DateTime.Now;
            entity.ExpireData = entity.StartDate.Value.AddYears(year);
            var result = AgentManage.Add(entity);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        public JsonResult AgentChangePassword(Guid id, string password)
        {
            if (string.IsNullOrEmpty(password))
                return Json(new { Result = "OK" });

            var result = AgentManage.ChangePassword(id, password);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        public ActionResult ChangePassword()
        {
            return View();
        }

        public JsonResult Changepwd(string password)
        {
            if (string.IsNullOrEmpty(password))
                return Json(new { Result = "OK" });

            var result = AgentManage.ChangePassword(RFrameGenerate.Common.CurrentUser.GetCurrUserGuid(), password);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        //代理商充值
        public JsonResult Recharge(Guid id, decimal rech)
        {
            if (rech <= 0)
                return Json(new { Result = "NO", Msg = "充值金额不能小于或等0" });

            var result = AgentManage.Recharge(id, rech);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        public ActionResult AgentInfo()
        {
            return View();
        }

        #endregion

        private string GetPackName(int? userType, Guid guid)
        {
            if (userType == null || userType != DictionaryConst.Versionb.Flagship || guid == Guid.Empty) return string.Empty;

            var ship = AgentsFlagshipManage.GetEntityByMerchantGuid(guid);

            if (ship == null) return string.Empty;

            var pack = FlagshipPackManage.GetEntityByGuid(ship.FlagshipPackGuid.Value);

            if (pack == null) return string.Empty;

            return pack.PackName;
        }

        #region Level

        public ActionResult Level()
        {
            return View();
        }

        public JsonResult LoadLeveldata(GridModel gridModel)
        {
            gridModel.datarows = (from s in LevelManage.GetPageList(gridModel)
                                  select new
                                  {
                                      id = s.LevelGuid,//定义当前行数据的一个传输识别名称，一般以主键为名称，可以省略()
                                      cell = new object[]
                                                     {
                                                         s.LevelGuid,
                                                         s.AgentGuid,
                                                         s.LevelName,
                                                         s.Prestore,
                                                         s.SybVersion,
                                                         s.FlagshipVersion
                                                      }
                                  }).ToArray();
            return Json(gridModel.PackagePageModel());
        }

        public JsonResult AddLevel(T_BAS_Level entity)
        {
            var result = LevelManage.AddLevel(entity);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        public JsonResult DelEntity(Guid entityGuid)
        {
            var result = LevelManage.DeleteEntity(entityGuid);

            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });

        }

        #endregion

        #region 微信海

        public ActionResult ApplyWeiXinHaiRecord()
        {
            return View();
        }

        public JsonResult LoadApplydata(GridModel gridModel, string userid)
        {
            gridModel.datarows = (from s in ApplyWeiXinHaiRecordManage.GetPageList(gridModel, userid)
                                  select new
                                  {
                                      id = s.ApplyWeiXinHaiRecordsGuid,//定义当前行数据的一个传输识别名称，一般以主键为名称，可以省略()
                                      cell = new object[]
                                                     {
                                                         s.UserID,
                                                         s.StoreTitle,
                                                          DictionaryConst.Versionb.GetText(s.OpenType.Value),
                                                          s.ApplyState,
                                                          s.Year,
                                                          s.ApplyDate.ToString("yyyy/MM/dd HH:mm:ss")
                                                      }
                                  }).ToArray();
            return Json(gridModel.PackagePageModel());
        }

        public JsonResult Audit(Guid id, int state)
        {
            var result = ApplyWeiXinHaiRecordManage.Audit(id, state);

            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }


        #endregion
    }
}
