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_Expenditure:PageBase
{
    private static int currentPageNum = 1;//当前页数
    private static int pageCount = 1;//总页数
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            OfficeManage.BindDdlExpenditureType(ddlExpenditureType);//绑定支出类型
            OfficeManage.BindDdlProject(ddlProject);//绑定项目
            OfficeManage.BindDdlSeller(ddlSeller);//绑定商家
            BindRptDetailExpenditure();//绑定支出明细
            BindSelectExpenditureCount();
        }
    }
    #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 BindSelectExpenditureCount()
    {
        double expenditureCount = 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++ )
            {
                expenditureCount += ConvertHelper.GetDouble(ds.Tables[0].Rows[i]["RExpenditureMoney"]);
            }
        }
        spanExpenditureCount.InnerHtml =ConvertHelper.GetString(expenditureCount);
    }
    #endregion
    #region 绑定支出明细
    /// <summary>
    /// 绑定支出明细
    /// </summary>
    public void BindRptDetailExpenditure()
    {
        pageCount = GetPageCount();//总页数
        spanPageCount.InnerHtml = ConvertHelper.GetString(pageCount);//总页数
        SetStrWhere();
        ControlHelper.BindRepeater(this.rptDetailExpenditure, "constring", StrWhere + "AND Row BETWEEN (" + currentPageNum + "-1)*15+1 AND " + currentPageNum + "*15 ");
     }
    #endregion
    protected void rptDetailExpenditure_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int recordExpenditureId = ConvertHelper.GetInteger((e.Item.FindControl("hfRecordExpenditureId") as HiddenField).Value);//支出明细id
        if (e.CommandName == "edit")//编辑
        {
            Response.Redirect("ExpenditureInfo.aspx?deiid="+recordExpenditureId+"");
        }
        else if (e.CommandName == "delete")//删除
        {
            #region 删除支出明细
            int flag = SqlHelper.Operation("UPDATE dbo.V_Detail_Expenditure SET State=0 WHERE RecordExpenditureId="+recordExpenditureId+"", "constring");
            if (flag > 0)//删除支出记录成功
            {
                int accountTypeId = ConvertHelper.GetInteger((e.Item.FindControl("hfREAccountTypeId") as HiddenField).Value);//账户类型
                int accountId = ConvertHelper.GetInteger((e.Item.FindControl("hfREAccountId") as HiddenField).Value);//账户id
                double expenditureMoney = ConvertHelper.GetDouble((e.Item.FindControl("hfRExpenditureMoney") as HiddenField).Value);//支出金额
                int flagAccount = 0;//账户余额修改是否成功标志
                if (accountTypeId == 1)//现金账户
                {
                    flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder+" + ConvertHelper.GetDecimal(expenditureMoney) + " WHERE CashAccountId=" + accountId + "", "constring");
                }
                else if(accountTypeId==2)//信用卡
                {
                    flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears-" + ConvertHelper.GetDecimal(expenditureMoney) + " WHERE CreditCardId=" + accountId + "", "constring");
                }
                else if(accountTypeId==3)//储蓄卡
                {
                    flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder+" + ConvertHelper.GetDecimal(expenditureMoney) + " WHERE SavingsCardId=" + accountId + "", "constring");
                }
                else if(accountTypeId==4)//网上银行
                {
                    flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder+" + ConvertHelper.GetDecimal(expenditureMoney) + " WHERE OnlinePayId=" + accountId + "", "constring");
                }
                if (flagAccount > 0)//账户余额修改成功
                {
                    BindRptDetailExpenditure();
                }
                else//账户余额修改失败
                {
                    SqlHelper.Operation("UPDATE dbo.V_Detail_Expenditure SET State=1 WHERE RecordExpenditureId=" + recordExpenditureId + "", "constring");//支出记录还原为未删除（state变为1未删除（state：0-已删除，1-未删除））
                    ScriptHelper.AlertMessage(this.Page,"删除失败，请联系管理员！");
                }
            }
            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;
        BindRptDetailExpenditure();
        spanPageCurrent.InnerHtml = "1";//当前页为1
    }
    #endregion
    #region 上页
    protected void lbtnPageUp_Click(object sender, EventArgs e)//上页
    {
        if (spanPageCurrent.InnerHtml != "1")//不是首页时
        {
            currentPageNum = ConvertHelper.GetInteger(spanPageCurrent.InnerHtml) - 1;
            BindRptDetailExpenditure();
            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;
            BindRptDetailExpenditure();
            spanPageCurrent.InnerHtml = ConvertHelper.GetString(currentPageNum);//当前页spanPageCurrent赋值
        }
    }
    #endregion
    #region 末页
    protected void lbtnPageLast_Click(object sender, EventArgs e)//末页
    {
        currentPageNum = GetPageCount();
        BindRptDetailExpenditure();
        spanPageCurrent.InnerHtml = ConvertHelper.GetString(pageCount);//当前页等于总页数
    }
    #endregion
    #endregion
    #region 查询事件
    #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 RExpenditureDateTime DESC) AS Row,RecordExpenditureId,RExpenditureMoney,REAccountTypeId,REAccountId,RExpenditureTypeId,REProjectId,ExpenditureTypeName,RExpenditureSellerId,SellerName,REAccountName,RExpenditureDateTime,ProjectTypeName,RExpenditureRemarks FROM dbo.V_Detail_Expenditure WHERE State=1) AS temptable  WHERE 1=1 ");
        if (ConvertHelper.GetDateTime(txtStateTime) < ConvertHelper.GetDateTime(txtEndTime.Text.Trim()))//如果开始时间小于最后时间(即正常情况)
        {
            strb.Append(" AND (RExpenditureDateTime>='" + ConvertHelper.GetDateTime(txtStateTime.Text.Trim()) + "' AND RExpenditureDateTime<='" + 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 RExpenditureDateTime BETWEEN '" + ConvertHelper.GetDateTime(txtStateTime.Text.Trim()) + "' AND '" + ConvertHelper.GetDateTime(txtEndTime.Text.Trim()) + "' ");
        }
        if(uclAccount.AccountTypeID!=0)//账户类型不为空
        {
            if(uclAccount.CashAccountID!=0)//现金账户不为空
            {
                strb.Append(" AND REAccountTypeId=" + uclAccount.AccountTypeID + " AND REAccountId="+uclAccount.CashAccountID+" ");
            }
            else if(uclAccount.CreditCardID!=0)//信用卡不为空
            {
                strb.Append(" AND REAccountTypeId=" + uclAccount.AccountTypeID + " AND REAccountId=" + uclAccount.CreditCardID + " ");
            }
            else if(uclAccount.SavingsCardID!=0)//储蓄卡不为空
            {
                strb.Append(" AND REAccountTypeId=" + uclAccount.AccountTypeID + " AND REAccountId=" + uclAccount.CreditCardID + " ");
            }
            else if(uclAccount.OnlinePayID!=0)//网上支付不为空
            {
                strb.Append(" AND REAccountTypeId=" + uclAccount.AccountTypeID + " AND REAccountId=" + uclAccount.CreditCardID + " ");
            }
        }
        if(ddlExpenditureType.SelectedValue!="0")//支出类型不为空
        {
            strb.Append(" AND RExpenditureTypeId="+ConvertHelper.GetInteger(ddlExpenditureType.SelectedValue)+" ");
        }
        if (ddlProject.SelectedValue!="0")//项目不为空
        {
            strb.Append(" AND REProjectId="+ConvertHelper.GetInteger(ddlProject.SelectedValue)+" ");
        }
        if(ddlSeller.SelectedValue!="0")//商家不为空
        {
            strb.Append(" AND RExpenditureSellerId="+ConvertHelper.GetInteger(ddlSeller.SelectedValue)+"");
        }
        //if (uclBankCard.BankCardID != 0)//查询事件中的银行卡
        //{
        //    strb.Append("AND BankCardID=" + uclBankCard.BankCardID + " ");//银行卡id
        //}
        //else if (!string.IsNullOrEmpty(Request["BankId"]))//从银行卡列表页点击查看明细跳转到明细页面（即本页面）
        //{
        //    strb.Append("AND BankCardID=" + Request["BankId"] + " ");//银行卡id
        //}
        //if (!string.IsNullOrEmpty(txtCardNumber.Text.Trim()))
        //{
        //    strb.Append("AND BankCardNumber like '%" + txtCardNumber.Text.Trim() + "%' ");//银行卡号（模糊查询）
        //}
        //if (!string.IsNullOrEmpty(txtHeader.Text.Trim()))
        //{
        //    strb.Append("AND Header like '%" + txtHeader.Text.Trim() + "%' ");//户主名（模糊查询）
        //}
        //if (!string.IsNullOrEmpty(txtOther.Text.Trim()))
        //{
        //    strb.Append("AND OtherName like '%" + txtOther.Text.Trim() + "%'");//交易对方（模糊查询）
        //}
        //strb.Append(string.Format(timewhere.WhereString, " a.CreateTime"));
        StrWhere = strb.ToString();
    }
    #endregion
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        BindRptDetailExpenditure();
        BindSelectExpenditureCount();
    }
    #endregion
}