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

namespace jiouosdp.Areas.Distribution.Controllers
{
    public class WithdrawalMgeController : Controller
    {
        //
        // GET: /Distribution/WithdrawalMge/

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

        #region JsonResult ChangeWithdrawalMgeSetting
        /// <summary>
        /// updata (or add)withdrawal parameter setting
        /// </summary>
        /// <param name="parameterGuid"></param>
        /// <param name="parameterName"></param>
        /// <param name="parameterValue"></param>
        /// <param name="hasPar"></param>
        /// <returns></returns>
        public JsonResult ChangeWithdrawalMgeSetting(string parameterGuid, string parameterName, string parameterValue, int hasPar)
        {
            var length = parameterName.Split(',').Length;

            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)
            {
                return Json(new { Result = "OK", Data = plist });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        #endregion

        #region JsonResult GetWithdrawalMgeParameter
        /// <summary>
        /// get withdrawal setting parameter
        /// </summary>
        /// <returns></returns>
        public JsonResult GetWithdrawalMgeParameter()
        {
            var allParList = ParameterManage.GetSettingParameters(RFrameGenerate.BLL.ParameterName.Distribution.WithdrawalAmountLimits);

            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 GetWithdrawalMgePageList

        /// <summary>
        /// get distributionprop list
        /// </summary>
        /// <returns></returns>
        public JsonResult GetWithdrawalMgePageList(GridModel gridModel, string name)
        {
            var wlist = WithdrawsComManage.GetWithdrawalMgePageList(gridModel, name);
            gridModel.datarows = wlist.Select(c => c.State != null ? new
            {
                id = c.WithdrawsCommissionGuid,
                cell = new object[]
                {
                    c.DistributionName,
                    c.DistributionTelphone,
                    c.ApplyDateTime.ToString("yyyy-MM-dd"),
                    c.ApplyAmount,
                    RFrameGenerate.BLL.DictionaryConst.WithdriwalCom.GetText(c.State.Value),
                    c.State,
                    c.DistributionPropGuid,
                    ""

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

        #endregion

        #region JsonResult CheckPass

        /// <summary>
        /// pass check（1/-1）
        /// </summary>
        /// <param name="withdrawsCommissionGuid"></param>
        /// <param name="stateCode"></param>
        /// <param name="applyAmount"></param>
        /// <param name="distributionPropGuid"></param>
        /// <returns></returns>
        public JsonResult CheckPass(Guid withdrawsCommissionGuid, int stateCode, Guid distributionPropGuid)
        {
            var lockitem = CrowdPeriodLock.GetLock(withdrawsCommissionGuid);
            lock (lockitem)
            {
                try
                {
                    var didProp = DistributionManage.GetList(distributionPropGuid);
                    var apply = WithdrawsComManage.GetWithdrawsApplyAmount(withdrawsCommissionGuid);

                    if (apply.State == 0)
                    {
                        var applyAmount = apply.ApplyAmount ?? 0;
                        var withdrawalAmount = didProp.WithdrawalAmount.Value;
                        var amountFrozen = didProp.AmountFrozen.Value;
                        amountFrozen = amountFrozen - applyAmount;
                        if (stateCode == 1)//同意
                        {
                            withdrawalAmount = withdrawalAmount + applyAmount;
                            DistributionManage.UpdateAmount(distributionPropGuid, amountFrozen, withdrawalAmount);

                            var memberGuid = DistributionManage.GetList(distributionPropGuid).MemberGuid.Value;

                            if (memberGuid != null && stateCode != -1)
                                VisitantManager.Update2(applyAmount, withdrawsCommissionGuid, Guid.Parse(memberGuid.ToString()));
                        }
                        else if (stateCode == -1)//拒绝
                        {
                            DistributionManage.UpdateAmount(distributionPropGuid, amountFrozen, withdrawalAmount);
                        }
                        Result result = WithdrawsComManage.UpdateWithdrawsComState(withdrawsCommissionGuid, stateCode);

                        return Json(result.State ? new { Result = "OK", Msg = result.Msg } : new { Result = "NO", Msg = result.Msg });
                    }
                    else
                    {
                        return Json(new { Result = "NO", Msg = "您已同意,请勿再次同意." });
                    }
                }
                finally
                {
                    lockitem.IsUse = false;
                }
            }
        }

        #endregion
    }
}
