using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Data;

public partial class A_Detail_Detail_Transfer : PageBase
{
    private static int currentPageNum = 1;//当前页数
    private static int pageCount = 1;//总页数
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            BindRptDetailTransfer();
            BindSelectIncomeCount();
        }
    }
    #region 功能栏事件（全部、支出、收入、转账、借贷按钮）
    protected void btnAllDetail_Click(object sender, EventArgs e)//全部明细
    {
        Response.Redirect("Detail.aspx");
    }
    protected void btnExpenditure_Click(object sender, EventArgs e)//支出明细
    {
        Response.Redirect("Detail_Expenditure.aspx");
    }
    protected void btnIncome_Click(object sender, EventArgs e)//收入明细
    {
        Response.Redirect("Detail_Income.aspx");
    }
    protected void btnTransfer_Click(object sender, EventArgs e)//转账明细
    {
        Response.Redirect("Detail_Transfer.aspx");
    }
    protected void btnLoan_Click(object sender, EventArgs e)//借贷明细
    {
        Response.Redirect("Detail_Loan.aspx");
    }
    #endregion
    #region 绑定查询的转账总额
    /// <summary>
    /// 绑定查询的转账总额
    /// </summary>
    public void BindSelectIncomeCount()
    {
        double transferCount = 0.00;//查询的转账总额
        DataSet ds = SqlHelper.GetDataSet(StrWhere, "constring");
        if (ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                transferCount += ConvertHelper.GetDouble(ds.Tables[0].Rows[0]["RecordTransferMoney"]);
            }
        }
        spanTransferCount.InnerHtml = ConvertHelper.GetString(transferCount);
    }
    #endregion
    #region  绑定转账明细
    /// <summary>
    /// 绑定转账明细rptDetailTtransfer
    /// </summary>
    public void BindRptDetailTransfer()
    {
        pageCount = GetPageCount();//总页数
        spanPageCount.InnerHtml = ConvertHelper.GetString(pageCount);//总页数
        //SetStrWhere();
        ControlHelper.BindRepeater(this.rptDetailTransfer, "constring", StrWhere + "AND Row BETWEEN (" + currentPageNum + "-1)*15+1 AND " + currentPageNum + "*15 ");
    }
    #endregion 
    protected void rptDetailTransfer_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int recordTransferId = ConvertHelper.GetInteger((e.Item.FindControl("hfRecordTransferId") as HiddenField).Value);//转账记录id
        if(e.CommandName=="edit")//编辑转账记录
        {
            Response.Redirect("TransferInfo.aspx?tiid="+recordTransferId+"");
        }
        else if(e.CommandName=="delete")//删除转账记录
        {
            #region 删除转账记录
            int accountTypeIdOut =ConvertHelper.GetInteger((e.Item.FindControl("hfRTOutAccountTypeId") as HiddenField).Value);//转出账户类型id
            int accountIdOut = ConvertHelper.GetInteger((e.Item.FindControl("hfRTOutAccountId") as HiddenField).Value);//转出账户id
            int accountTypeIdEnter = ConvertHelper.GetInteger((e.Item.FindControl("hfRTEnterAccountTypeId") as HiddenField).Value);//转入账户类型id
            int accountIdEnter = ConvertHelper.GetInteger((e.Item.FindControl("hfRTEnterAccountId") as HiddenField).Value);//转入账户id
            double transferMoney = ConvertHelper.GetDouble((e.Item.FindControl("hfRecordTransferMoney") as HiddenField).Value);//转账金额
            int flag = SqlHelper.Operation("UPDATE dbo.V_Detail_Transfer SET State=0 WHERE RecordTransferId="+recordTransferId+"", "constring");//删除转账记录（0-已删除，1-未删除）
            if(flag>0)
            {
                #region 转出转入账户余额还原
                int flagAccountOut = 0;//转出账户余额恢复是否成功标志（余额+转账金额）
                #region 转出账户余额还原
                if (accountTypeIdOut == 1)//转出现金账户
                {
                    flagAccountOut = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder+" + ConvertHelper.GetDecimal(transferMoney) + " WHERE CashAccountId=" + accountIdOut + "", "constring");
                }
                else if (accountTypeIdOut == 2)//转出信用卡（CardArrears:欠款金额（收入：“+”，支出：“-”））
                {
                    flagAccountOut = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears-" + ConvertHelper.GetDecimal(transferMoney) + " WHERE CreditCardId=" + accountIdOut + "", "constring");
                }
                else if (accountTypeIdOut == 3)//转出储蓄卡
                {
                    flagAccountOut = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder+" + ConvertHelper.GetDecimal(transferMoney) + " WHERE SavingsCardId=" + accountIdOut + "", "constring");
                }
                else if (accountTypeIdOut == 4)//转出网上银行
                {
                    flagAccountOut = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder+" + ConvertHelper.GetDecimal(transferMoney) + " WHERE OnlinePayId=" + accountIdOut + "", "constring");
                }
                #endregion
                if (flagAccountOut > 0)//转出账户余额恢复成功
                {
                    int flagAccountEnter = 0;//转入账户余额恢复是否成功标志（余额-转账金额）
                    #region 转入账户余额还原
                    if (accountTypeIdEnter == 1)//现金账户
                    {
                        flagAccountOut = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder-" + ConvertHelper.GetDecimal(transferMoney) + " WHERE CashAccountId=" + accountIdEnter + "", "constring");
                    }
                    else if (accountTypeIdEnter == 2)//信用卡（CardArrears:欠款金额（收入：“+”，支出：“-”））
                    {
                        flagAccountOut = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears+" + ConvertHelper.GetDecimal(transferMoney) + " WHERE CreditCardId=" + accountIdEnter + "", "constring");
                    }
                    else if (accountTypeIdEnter == 3)//储蓄卡
                    {
                        flagAccountOut = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder-" + ConvertHelper.GetDecimal(transferMoney) + " WHERE SavingsCardId=" + accountIdEnter + "", "constring");
                    }
                    else if (accountTypeIdEnter == 4)//网上银行
                    {
                        flagAccountOut = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder-" + ConvertHelper.GetDecimal(transferMoney) + " WHERE OnlinePayId=" + accountIdEnter + "", "constring");
                    }
                    #endregion
                    if (flagAccountEnter > 0)//转入账户余额恢复成功（余额-借出金额）
                    {
                        BindRptDetailTransfer();
                    }
                    else//转入账户余额恢复失败
                    {
                        ScriptHelper.AlertMessage(this.Page, "删除失败，请联系管理员！");
                    }
                }
                else//转出账户余额修改失败
                {
                    SqlHelper.Operation("UPDATE dbo.V_Detail_Transfer SET State=1 WHERE RecordTransferId=" + recordTransferId + "", "constring");//删除转账记录（0-已删除，1-未删除）
                    ScriptHelper.AlertMessage(this.Page, "删除失败，请联系管理员！");
                }
                #endregion
            }
            else
            {
                ScriptHelper.AlertMessage(this.Page,"删除失败，请联系管理员！");
            }
            #endregion
        }
    }
    #region 分页
    #region 获取分页总页数
    /// <summary>
    /// 获取分页总页数
    /// </summary>
    /// <returns></returns>
    public int GetPageCount()
    {
        int pagecount = 0;//总页数
        SetStrWhere();
        DataSet ds = SqlHelper.GetDataSet(StrWhere, "constring");
        if (ds.Tables[0].Rows.Count > 0)
        {
            int loanAccountCount = ConvertHelper.GetInteger(ds.Tables[0].Rows.Count);//借贷用户总个数
            if (loanAccountCount % 15 == 0)
            {
                pagecount = loanAccountCount / 15;
            }
            else
            {
                pagecount = loanAccountCount / 15 + 1;
            }
        }
        else
        {
            pagecount = 1;
        }
        return pagecount;
    }
    #endregion
    #region 首页
    protected void lbtnPageFirst_Click(object sender, EventArgs e)//首页
    {
        currentPageNum = 1;
        BindRptDetailTransfer();
        spanPageCurrent.InnerHtml = "1";//当前页为1
    }
    #endregion
    #region 上页
    protected void lbtnPageUp_Click(object sender, EventArgs e)//上页
    {
        if (spanPageCurrent.InnerHtml != "1")//不是首页时
        {
            currentPageNum = ConvertHelper.GetInteger(spanPageCurrent.InnerHtml) - 1;
            BindRptDetailTransfer();
            spanPageCurrent.InnerHtml = ConvertHelper.GetString(currentPageNum);//当前页spanPageCurrent赋值
        }
    }
    #endregion
    #region 下页
    protected void lbtnPageDown_Click(object sender, EventArgs e)//下页
    {
        if (spanPageCurrent.InnerHtml != ConvertHelper.GetString(pageCount))//不是尾页时
        {
            currentPageNum = ConvertHelper.GetInteger(spanPageCurrent.InnerHtml) + 1;
            BindRptDetailTransfer();
            spanPageCurrent.InnerHtml = ConvertHelper.GetString(currentPageNum);//当前页spanPageCurrent赋值
        }
    }
    #endregion
    #region 末页
    protected void lbtnPageLast_Click(object sender, EventArgs e)//末页
    {
        currentPageNum = GetPageCount();
        BindRptDetailTransfer();
        spanPageCurrent.InnerHtml = ConvertHelper.GetString(pageCount);//当前页等于总页数
    }
    #endregion
    #endregion
    #region 查询sql语句属性
    /// <summary>
    /// 查询sql语句属性
    /// </summary>
    public string StrWhere
    {
        get { return Convert.ToString(ViewState["StrWhere"]); }
        set { ViewState["StrWhere"] = value; }
    }
    /// <summary>
    /// 修改sql语句属性的方法
    /// </summary>
    public void SetStrWhere()
    {
        StringBuilder strb = new StringBuilder();
        //V_Detail_Expenditure视图：支出明细视图
        strb.Append("SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY RTransferDateTime DESC) AS Row,RecordTransferId,RTransferDateTime,RecordTransferMoney,RTOutAccountTypeId,RTOutAccountId,RTOutAccountName,RTEnterAccountTypeId,RTEnterAccountId,RTEnterAccountName,RTransferRemarks,HandlerId FROM dbo.V_Detail_Transfer WHERE State=1) AS temptable  WHERE 1=1 ");
        if (ConvertHelper.GetDateTime(txtStateTime) < ConvertHelper.GetDateTime(txtEndTime.Text.Trim()))//如果开始时间小于最后时间(即正常情况)
        {
            strb.Append(" AND (RTransferDateTime>='" + ConvertHelper.GetDateTime(txtStateTime.Text.Trim()) + "' AND RTransferDateTime<='" + ConvertHelper.GetDateTime(txtEndTime.Text.Trim()) + "') ");
        }
        else//非正常情况（则执行查询本月支出明细）
        {
            txtStateTime.Text = ConvertHelper.GetString(System.DateTime.Now.ToString("yyyy-MM") + "-01");//开始查询时间赋为本月1号
            txtEndTime.Text = ConvertHelper.GetString(System.DateTime.Now.ToString("yyyy-MM-dd"));//结束查询时间赋为查询那天
            strb.Append(" AND RTransferDateTime BETWEEN '" + ConvertHelper.GetDateTime(txtStateTime.Text.Trim()) + "' AND '" + ConvertHelper.GetDateTime(txtEndTime.Text.Trim()) + "' ");
        }
        if (uclAccount.AccountTypeID != 0)//转出账户类型不为空
        {
            if (uclAccount.CashAccountID != 0)//转出现金账户不为空
            {
                strb.Append(" AND RTOutAccountTypeId=" + uclAccount.AccountTypeID + " AND RTOutAccountId=" + uclAccount.CashAccountID + " ");
            }
            else if (uclAccount.CreditCardID != 0)//转出信用卡不为空
            {
                strb.Append(" AND RTOutAccountTypeId=" + uclAccount.AccountTypeID + " AND RTOutAccountId=" + uclAccount.CreditCardID + " ");
            }
            else if (uclAccount.SavingsCardID != 0)//转出储蓄卡不为空
            {
                strb.Append(" AND RTOutAccountTypeId=" + uclAccount.AccountTypeID + " AND RTOutAccountId=" + uclAccount.CreditCardID + " ");
            }
            else if (uclAccount.OnlinePayID != 0)//转出网上支付不为空
            {
                strb.Append(" AND RTOutAccountTypeId=" + uclAccount.AccountTypeID + " AND RTOutAccountId=" + uclAccount.CreditCardID + " ");
            }
        }
        if (uclAccountEnter.AccountTypeID != 0)//转入账户类型不为空
        {
            if (uclAccountEnter.CashAccountID != 0)//转入现金账户不为空
            {
                strb.Append(" AND RTOutAccountTypeId=" + uclAccountEnter.AccountTypeID + " AND RTOutAccountId=" + uclAccountEnter.CashAccountID + " ");
            }
            else if (uclAccountEnter.CreditCardID != 0)//转入信用卡不为空
            {
                strb.Append(" AND RTOutAccountTypeId=" + uclAccountEnter.AccountTypeID + " AND RTOutAccountId=" + uclAccountEnter.CreditCardID + " ");
            }
            else if (uclAccountEnter.SavingsCardID != 0)//转入储蓄卡不为空
            {
                strb.Append(" AND RTOutAccountTypeId=" + uclAccountEnter.AccountTypeID + " AND RTOutAccountId=" + uclAccountEnter.CreditCardID + " ");
            }
            else if (uclAccountEnter.OnlinePayID != 0)//转入网上支付不为空
            {
                strb.Append(" AND RTOutAccountTypeId=" + uclAccountEnter.AccountTypeID + " AND RTOutAccountId=" + uclAccountEnter.CreditCardID + " ");
            }
        }
        StrWhere = strb.ToString();
    }
    #endregion
    #region 查询事件
    protected void btnSelect_Click(object sender, EventArgs e)//查询事件
    {
        BindRptDetailTransfer();
        BindSelectIncomeCount();
    }
    #endregion
}