using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RFrameGenerate.BLL;
using RFrameGenerate.Common;
using RFrameGenerate.Model;
using RFramework.SQLServer;

namespace jiouosdp.Areas.Distribution.Controllers
{
    public class MemberController : Controller
    {
        //
        // GET: /Distribution/Member/

        [PF(PCode.DistributionManage.DistributionMember)]
        public ActionResult Index()
        {
            return View();
        }

        //public ActionResult Manage(string pwd)
        //{
        //    if (pwd != "jioukeji804")
        //        return Content("密码错了");
        //    return View();
        //}

        #region JsonResult GetDistributionPropPageList

        /// <summary>
        /// get distributionprop list
        /// </summary>
        /// <returns></returns>
        public JsonResult GetDistributionPropPageList(GridModel gridModel, Guid? merchantguid, string name, int? isEnable)
        {
            List<T_BAS_DistributionProp> dlist = null;
            switch (isEnable)
            {
                case 0:
                    dlist = DistributionManage.GetDistributionPropPageList(gridModel, merchantguid, name, 0);
                    break;
                case 1:
                default:
                    dlist = DistributionManage.GetDistributionPropPageList(gridModel, merchantguid, name, 1);
                    break;
            }
            gridModel.datarows = dlist.Select(c => new
            {
                id = c.DistributionPropGuid,
                cell = new object[]
                {
                    c.DistributionName,
                    c.StoreTitle,
                    c.DistributionTelphone,
                    c.JoinDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    c.SuperiorName,
                    c.DistributionAmount,
                    c.DistributionCommissions,
                    c.SubMemberNum,
                    c.WithdrawalAmount,
                    c.IsEnable == true ? "启用" : "关闭",
                    Convert.ToInt16(c.IsEnable),
                    "",
                    c.RQCode,
                    c.MemberGuid

                }
            }).ToArray();
            return Json(gridModel.PackagePageModel());
        }

        public JsonResult UpdateStoreTitle(Guid did, string title)
        {
            var result = DistributionManage.UpdateTitle(did, title);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            else
            {
                return Json(new { Result = "NO", Msg = result.Msg });
            }
        }
        #endregion

        #region JsonResult ChangeStateByStateCode

        /// <summary>
        /// change userstate by statecode and distributionGuid
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="stateCode"></param>
        /// <returns></returns>
        public JsonResult ChangeStateByStateCode(Guid guid, bool stateCode)
        {
            var result = DistributionManage.ChangeStateByStateCode(guid, stateCode);

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

        #endregion

        public JsonResult DelMember(Guid guid)
        {
            var result = DistributionManage.DelMember(guid);

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

        #region JsonResult GetAreaData

        /// <summary>
        /// get area data
        /// </summary>
        /// <returns></returns>
        public JsonResult GetAreaData()
        {
            return Json(AreasManage.GetAreaData());
        }

        #endregion

        #region JsonResult GetQRcode

        /// <summary>
        /// get qrcode
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public JsonResult GetQRcode(Guid guid)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "upload\\qrcode";

            var result = DistributionManage.GetQRcode("1", "", path, guid);

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

        #endregion

        #region JsonResult GetApplyPageList

        /// <summary>
        /// get apply page list
        /// </summary>
        /// <param name="gridModel"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public JsonResult GetApplyPageList(GridModel gridModel, string name)
        {
            var list = ApplyDistributionRecordsManage.GetApplyPageList(gridModel, name);
            gridModel.datarows = list.Select(c => new
                    {
                        id = c.ApplyDistributionRecordsGuid,
                        cell = new object[]
                        {
                            c.DistributionName,
                            c.Telphone,
                            c.ApplyDateTime,
                            c.SuperiorName,
                            c.MemberMobilePhone,
                            DictionaryConst.Apply.GetText(c.State.Value),
                            c.State,
                            c.ParentMemberGuid,
                            ""
                        }
                    }).ToArray();
            return Json(gridModel.PackagePageModel());
        }

        #endregion

        #region JsonResult CheckPass

        /// <summary>
        /// pass (add applylist to distributionProp)
        /// false (change applyState)
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="applyDistributionRecordsGuid"></param>
        /// <param name="stateCode"></param>
        /// <returns></returns>
        public JsonResult CheckPass(T_BAS_DistributionProp entity, Guid applyDistributionRecordsGuid, int stateCode)
        {
            Result result;
            if (stateCode == 0)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "upload\\qrcode";
                //var memberGuid = ApplyDistributionRecordsManage.GetMemberGuid(applyDistributionRecordsGuid);

                var applyRecod = ApplyDistributionRecordsManage.GetApplyRecord(applyDistributionRecordsGuid);
                var memberGuid = applyRecod.MemberGuid.Value;// ApplyDistributionRecordsManage.GetMemberGuid(applyDistributionRecordsGuid);

                var guid = DistributionManage.AddApplyDistributionData(entity, memberGuid, applyRecod.ApplyDateTime);
                var str = "http://" + MerchantManage.GetDomain() + "/WxShop/Index?did=" + guid;
                result = ApplyDistributionRecordsManage.UpdateApplyState(applyDistributionRecordsGuid, stateCode);

                DistributionManage.UpdataTeam(entity.DistributionPropGuid);

                if (result.State)
                {
                    result = MemberManage.UpdataIsDis(memberGuid);
                }
                if (result.State)
                {
                    result = DistributionManage.GetQRcode(str, "", path, guid);
                }
            }
            else
            {
                result = ApplyDistributionRecordsManage.UpdateApplyState(applyDistributionRecordsGuid, stateCode);
            }
            return Json(result.State ? new { Result = "OK", Msg = result.Msg } : new { Result = "NO", Msg = result.Msg });
        }

        #endregion

        public JsonResult GetDistributionList()
        {
            return Json(DistributionManage.GetDistributionAllList());
        }

        #region JsonResult GetDistributionSettingParameter
        /// <summary>
        /// get distribution setting parameter
        /// </summary>
        /// <returns></returns>
        public JsonResult GetDistributionSettingParameter()
        {
            var allParList = ParameterManage.GetSettingParameters(ParameterName.DistributionMemeber.AuditApproachNew);

            var parameterList = from c in allParList
                                where c.MerchantGuid == CurrentManage.MerchantGuid
                                select new
                                {
                                    ParameterName = c.ParameterName,
                                    ParameterValue = c.ParameterValue,
                                    ParameterGuid = c.ParameterGuid
                                };
            return Json(new { Result = "OK", Data = parameterList.ToArray() });

        }
        #endregion

        #region JsonResult UpdateParameterSetting
        /// <summary>
        /// updata (or add)banlace parameter setting
        /// </summary>
        /// <param name="parameterGuid"></param>
        /// <param name="parameterName"></param>
        /// <param name="parameterValue"></param>
        /// <param name="hasPar"></param>
        /// <returns></returns>
        public JsonResult UpdateParameterSetting(string parameterGuid, string parameterName, string parameterValue, int hasPar)
        {
            var length = parameterName.Split(',').Length;
            T_SYS_Parameter parameter = new T_SYS_Parameter();
            //if guid is null  this parmeteris a new person
            if (string.IsNullOrEmpty(parameterGuid.Split(',')[length - 1]))
            {
                List<T_SYS_Parameter> baseList = new List<T_SYS_Parameter>();
                parameter = new T_SYS_Parameter()
                {
                    MerchantGuid = CurrentManage.MerchantGuid,
                    ParameterGuid = Guid.NewGuid(),
                    ParameterName = parameterName.Split(',')[length - 1],
                    ParameterValue = parameterValue.Split(',')[length - 1]
                };
                baseList.Add(parameter);
                var baseResult = ParameterManage.AddExtSettingParameters(baseList);
                if (baseResult.State)
                {
                    length -= 1;
                }
            }
            List<T_SYS_Parameter> plist = new List<T_SYS_Parameter>();

            for (int i = 0; i < length; i++)
            {
                T_SYS_Parameter parameterObj = new T_SYS_Parameter()
                {
                    MerchantGuid = CurrentManage.MerchantGuid,
                    ParameterGuid = hasPar > 0 ? Guid.Parse(parameterGuid.Split(',')[i]) : Guid.NewGuid(),
                    ParameterName = parameterName.Split(',')[i],
                    ParameterValue = parameterValue.Split(',')[i]
                };
                plist.Add(parameterObj);
            }

            var result = hasPar > 0
                ? ParameterManage.UpdateExtSettingParameters(plist)
                : ParameterManage.AddExtSettingParameters(plist);
            if (result.State)
            {
                plist.Add(parameter);
                return Json(new { Result = "OK", Data = plist });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        #endregion

        public JsonResult GetDistributionPageList(GridModel gridModel, Guid? did, string userName)
        {
            if (did == null || did == Guid.Empty) return Json(gridModel.PackagePageModel());
            var distProp = DistributionManage.GetEnalbeDistributionPropPageList(gridModel, userName, did);

            distProp.Insert(0, new T_BAS_DistributionProp() { DistributionPropGuid = Guid.Empty, DistributionName = "总部" });
            gridModel.datarows = (distProp.Select(c => new
            {
                id = c.DistributionPropGuid,
                cell = new object[]
                {
                    c.DistributionName,
                }
            })).ToArray();

            gridModel.recordCount++;

            return Json(gridModel.PackagePageModel());
        }

        public JsonResult UpdateSuperior(Guid id, Guid prentid, Guid? memguid)
        {
            var result = DistributionManage.UpdateSuperior(id, prentid, memguid);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }
    }
}
