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_Income :PageBase
{
    private static int currentPageNum = 1;//当前页数
    private static int pageCount = 1;//总页数
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            OfficeManage.BindDdlIncomeType(ddlIncomeType);//绑定收入类型
            OfficeManage.BindDdlProject(ddlProject);//绑定项目
            OfficeManage.BindDdlSeller(ddlSeller);//绑定商家
            BindRptDetailIncome();
            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 incomeCount = 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++)
            {
                incomeCount += ConvertHelper.GetDouble(ds.Tables[0].Rows[i]["RIncomeMoney"]);
            }
        }
        spanIncomeCount.InnerHtml = ConvertHelper.GetString(incomeCount);
    }
    #endregion
    #region 绑定收入明细
    /// <summary>
    ///绑定收入明细
    /// </summary>
    public void BindRptDetailIncome()
    {
        pageCount = GetPageCount();//总页数
        spanPageCount.InnerHtml = ConvertHelper.GetString(pageCount);//总页数
        //SetStrWhere();
        ControlHelper.BindRepeater(this.rptDetailIncome, "constring", StrWhere + "AND Row BETWEEN (" + currentPageNum + "-1)*15+1 AND " + currentPageNum + "*15 ");
     }
    #endregion
    protected void rptDetailIncome_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int recordIncomeId = ConvertHelper.GetInteger((e.Item.FindControl("hfRecordIncomeId") as HiddenField).Value);//收入记录id
        if (e.CommandName == "edit")//编辑收入记录
        {
            Response.Redirect("IncomeInfo.aspx?riid="+recordIncomeId+"");
        }
        else if(e.CommandName=="delete")//删除收入记录
        {
            #region 删除收入记录
            int flag = SqlHelper.Operation("UPDATE dbo.V_Detail_Income SET State=0 WHERE RecordIncomeId="+recordIncomeId+"", "constring");//删除收入记录操作
            if (flag > 0)//删除收入记录成功
            {
                int accountTypeId = ConvertHelper.GetInteger((e.Item.FindControl("hfRIAccountTypeId") as HiddenField).Value);//账户类型
                int accountId = ConvertHelper.GetInteger((e.Item.FindControl("hfRIAccountId") as HiddenField).Value);//账户id
                double incomeMoney = ConvertHelper.GetDouble((e.Item.FindControl("hfRIncomeMoney") as HiddenField).Value);//收入金额
                int flagAccount = 0;//账户余额修改是否成功标志
                if (accountTypeId == 1)//现金账户
                {
                    flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder+" + ConvertHelper.GetDecimal(incomeMoney) + " WHERE CashAccountId=" + accountId + "", "constring");
                }
                else if (accountTypeId == 2)//信用卡（CardArrears:欠款金额）
                {
                    flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears-" + ConvertHelper.GetDecimal(incomeMoney) + " WHERE CreditCardId=" + accountId + "", "constring");
                }
                else if (accountTypeId == 3)//储蓄卡
                {
                    flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder+" + ConvertHelper.GetDecimal(incomeMoney) + " WHERE SavingsCardId=" + accountId + "", "constring");
                }
                else if (accountTypeId == 4)//网上银行
                {
                    flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder+" + ConvertHelper.GetDecimal(incomeMoney) + " WHERE OnlinePayId=" + accountId + "", "constring");
                }
                if (flagAccount > 0)//账户余额修改成功
                {
                    BindRptDetailIncome();
                }
                else//账户余额修改失败
                {
                    SqlHelper.Operation("UPDATE dbo.V_Detail_Income SET State=1 WHERE RecordIncomeId=" + recordIncomeId + "", "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;
        BindRptDetailIncome();
        spanPageCurrent.InnerHtml = "1";//当前页为1
    }
    #endregion
    #region 上页
    protected void lbtnPageUp_Click(object sender, EventArgs e)//上页
    {
        if (spanPageCurrent.InnerHtml != "1")//不是首页时
        {
            currentPageNum = ConvertHelper.GetInteger(spanPageCurrent.InnerHtml) - 1;
            BindRptDetailIncome();
            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;
            BindRptDetailIncome();
            spanPageCurrent.InnerHtml = ConvertHelper.GetString(currentPageNum);//当前页spanPageCurrent赋值
        }
    }
    #endregion
    #region 末页
    protected void lbtnPageLast_Click(object sender, EventArgs e)//末页
    {
        currentPageNum = GetPageCount();
        BindRptDetailIncome();
        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();
        //dbo.V_Detail_Income视图:收入明细视图
        strb.Append("SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY RIncomeDateTime DESC) AS Row,RecordIncomeId,RIAccountTypeId,RIAccountId,RIAccountName,RIncomeTypeId,IncomeTypeName,RIncomeSellerId,SellerName,RIncomeMoney,RIncomeDateTime,RIncomeProjectId,ProjectTypeName,RIncomeRemarks FROM dbo.V_Detail_Income WHERE State=1) AS temptable  WHERE 1=1 ");
        if (ConvertHelper.GetDateTime(txtStateTime) < ConvertHelper.GetDateTime(txtEndTime.Text.Trim()))//如果开始时间小于最后时间(即正常情况)
        {
            strb.Append(" AND (RIncomeDateTime>='" + ConvertHelper.GetDateTime(txtStateTime.Text.Trim()) + "' AND RIncomeDateTime<='" + 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 RIncomeDateTime BETWEEN '" + ConvertHelper.GetDateTime(txtStateTime.Text.Trim()) + "' AND '" + ConvertHelper.GetDateTime(txtEndTime.Text.Trim()) + "' ");
        }
        if (uclAccount.AccountTypeID != 0)//账户类型不为空
        {
            if (uclAccount.CashAccountID != 0)//现金账户不为空
            {
                strb.Append(" AND RIAccountTypeId=" + uclAccount.AccountTypeID + " AND RIAccountId=" + uclAccount.CashAccountID + " ");
            }
            else if (uclAccount.CreditCardID != 0)//信用卡不为空
            {
                strb.Append(" AND RIAccountTypeId=" + uclAccount.AccountTypeID + " AND RIAccountId=" + uclAccount.CreditCardID + " ");
            }
            else if (uclAccount.SavingsCardID != 0)//储蓄卡不为空
            {
                strb.Append(" AND RIAccountTypeId=" + uclAccount.AccountTypeID + " AND RIAccountId=" + uclAccount.CreditCardID + " ");
            }
            else if (uclAccount.OnlinePayID != 0)//网上支付不为空
            {
                strb.Append(" AND RIAccountTypeId=" + uclAccount.AccountTypeID + " AND RIAccountId=" + uclAccount.CreditCardID + " ");
            }
        }
        if(ddlIncomeType.SelectedValue!="0")//支出类型不为空
        {
            strb.Append(" AND RIncomeTypeId=" + ConvertHelper.GetInteger(ddlIncomeType.SelectedValue) + " ");
        }
        if (ddlProject.SelectedValue != "0")//项目不为空
        {
            strb.Append(" AND RIncomeProjectId=" + ConvertHelper.GetInteger(ddlProject.SelectedValue) + " ");
        }
        if (ddlSeller.SelectedValue != "0")//商家不为空
        {
            strb.Append(" AND RIncomeSellerId=" + 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
    #region 查询事件
    protected void btnSelect_Click(object sender, EventArgs e)//查询事件
    {
        BindRptDetailIncome();
        BindSelectIncomeCount();
    }
    #endregion
}