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_Loan : PageBase
{
    private static int currentPageNum = 1;//当前页数
    private static int pageCount = 1;//总页数
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            OfficeManage.BindLoanAccount(ddlLoanAccount);//绑定债务(权)人
            BindRptDetailLoan();
            BindLoanCount();
        }
    }
    #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 BindLoanCount()
    {
        double borrowCount = 0.00;//借入总额
        double lendCount = 0.00;//借出总额
        double receiveCount = 0.00;//收款总额
        double backCount = 0.00;//还款总额
        #region 绑定借入总额
        DataSet dsBorrow = SqlHelper.GetDataSet(StrWhere + " AND RecordLoanTypeId=1 ", "constring");//借入ds
        if(dsBorrow.Tables[0].Rows.Count>0)
        {
            for (int i = 0; i < dsBorrow.Tables[0].Rows.Count;i++ )
            {
                borrowCount += ConvertHelper.GetDouble(dsBorrow.Tables[0].Rows[i]["RecordLoanMoney"]);
            }
        }
        spanBorrowCount.InnerHtml = ConvertHelper.GetString(borrowCount);//显示借入总额
        #endregion
        #region 绑定借出总额
        DataSet dsLend = SqlHelper.GetDataSet(StrWhere + " AND RecordLoanTypeId=2 ", "constring");//借出ds
        if(dsLend.Tables[0].Rows.Count>0)
        {
            for (int i = 0; i < dsLend.Tables[0].Rows.Count;i++ )
            {
                lendCount += ConvertHelper.GetDouble(dsLend.Tables[0].Rows[i]["RecordLoanMoney"]);
            }
        }
        spanLendCount.InnerHtml = ConvertHelper.GetString(lendCount);//显示借出总额
        #endregion
        #region 绑定收款总额
        DataSet dsReceive = SqlHelper.GetDataSet(StrWhere + " AND RecordLoanTypeId=3 ", "constring");//收款ds
        if(dsReceive.Tables[0].Rows.Count>0)
        {
            for (int i = 0; i < dsReceive.Tables[0].Rows.Count;i++ )
            {
                receiveCount += ConvertHelper.GetDouble(dsReceive.Tables[0].Rows[i]["RecordLoanMoney"]);
            }
        }
        spanReceiveCount.InnerHtml = ConvertHelper.GetString(receiveCount);//显示收款总额
        #endregion
        #region 绑定还款总额
        DataSet dsBack = SqlHelper.GetDataSet(StrWhere + " AND RecordLoanTypeId=4 ", "constring");//还款ds
        if(dsBack.Tables[0].Rows.Count>0)
        {
            for (int i = 0; i < dsBack.Tables[0].Rows.Count;i++ )
            {
                backCount += ConvertHelper.GetDouble(dsBack.Tables[0].Rows[i]["RecordLoanMoney"]);
            }
        }
        spanBackCount.InnerHtml = ConvertHelper.GetString(backCount);//显示还款总额
        #endregion
    }
    #endregion
    #region 绑定借贷明细
    /// <summary>
    /// 绑定借贷明细rptDetailLoan
    /// </summary>
    public void BindRptDetailLoan()
    {
        pageCount = GetPageCount();//总页数
        spanPageCount.InnerHtml = ConvertHelper.GetString(pageCount);//总页数
        //SetStrWhere();
        ControlHelper.BindRepeater(this.rptDetailLoan, "constring", StrWhere + "AND Row BETWEEN (" + currentPageNum + "-1)*15+1 AND " + currentPageNum + "*15 ");
    }
    #endregion 
    protected void rptDetailLoan_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int recordLoanId = ConvertHelper.GetInteger((e.Item.FindControl("hfRecordLoanId") as HiddenField).Value);//借贷记录id
        if (e.CommandName == "edit")//编辑借贷记录
        {
            Response.Redirect("LoanInfo.aspx?liid="+recordLoanId+"");
        }
        else if (e.CommandName == "delete")//删除借贷记录
        {
            #region 删除借贷记录
            int flag = SqlHelper.Operation("UPDATE V_Detail_Loan SET State=0 WHERE RecordLoanId="+recordLoanId+"", "constring");
            if(flag>0)//删除借贷记录成功（金额还原）
            {
                #region 账户及借贷账户金额还原
                int accountTypeId = ConvertHelper.GetInteger((e.Item.FindControl("hfRLInsideAccountTypeId") as HiddenField).Value);//账户类型
                int accountId = ConvertHelper.GetInteger((e.Item.FindControl("hfRLInsideAccountId") as HiddenField).Value);//账户id
                int accountOutId = ConvertHelper.GetInteger((e.Item.FindControl("hfRLOutsideAccountId") as HiddenField).Value);//借贷账户id
                int loanTypeId = ConvertHelper.GetInteger((e.Item.FindControl("hfRecordLoanTypeId") as HiddenField).Value);//借贷类型(1-借入，2-借出，3-收款，4-还款)
                double loanMoney = ConvertHelper.GetDouble((e.Item.FindControl("hfRecordLoanMoney") as HiddenField).Value);//借贷金额（借出借入时只有借贷金额）
                double loanInterest = ConvertHelper.GetDouble((e.Item.FindControl("hfRLoanInterest") as HiddenField).Value);//利息（收款和还款时才有）
                if(loanTypeId==1)//借入
                {
                    #region 借入金额还原
                    int flagAccount = 0;//账户余额修改是否成功标志（余额-借入金额）
                    if (accountTypeId == 1)//现金账户
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder-" + ConvertHelper.GetDecimal(loanMoney) + " WHERE CashAccountId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 2)//信用卡（CardArrears:欠款金额（收入：“+”，支出：“-”））
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears+" + ConvertHelper.GetDecimal(loanMoney) + " WHERE CreditCardId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 3)//储蓄卡
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder-" + ConvertHelper.GetDecimal(loanMoney) + " WHERE SavingsCardId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 4)//网上银行
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder-" + ConvertHelper.GetDecimal(loanMoney) + " WHERE OnlinePayId=" + accountId + "", "constring");
                    }
                    if (flagAccount > 0)//账户余额修改成功
                    {
                        //LoanRemainder:借贷账户余额（正数-借贷方欠账户的，0-没有借贷关系，负数-账户欠借贷方的）(借贷类型为1-借入--（借贷账户余额-借贷金额），2-借出--（余额+借贷金额），3-收款--（借贷账户余额-借贷金额），4-还款--（借贷账户余额+借贷金额）)
                        int flagLoanAccount = SqlHelper.Operation("UPDATE tabA_Account_Loan SET LoanRemainder=LoanRemainder+" + ConvertHelper.GetDecimal(loanMoney) + "","constring");
                        if (flagLoanAccount > 0)//借贷账户余额还原成功（余额+借入金额）
                        {
                            BindRptDetailLoan();
                        }
                        else//借贷账户余额修改失败
                        {
                            ScriptHelper.AlertMessage(this.Page,"删除失败，请联系管理员！");
                        }
                    }
                    else//账户余额修改失败
                    {
                        SqlHelper.Operation("UPDATE V_Detail_Loan SET State=1 WHERE RecordLoanId=" + recordLoanId + "", "constring");//借贷记录还原为未删除（state变为1未删除（state：0-已删除，1-未删除））
                        ScriptHelper.AlertMessage(this.Page, "删除失败，请联系管理员！");
                    }
                    #endregion
                }
                else if(loanTypeId==2)//借出
                {
                    #region 借出金额还原
                    int flagAccount = 0;//账户余额修改是否成功标志（余额+借出金额）
                    if (accountTypeId == 1)//现金账户
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder+" + ConvertHelper.GetDecimal(loanMoney) + " WHERE CashAccountId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 2)//信用卡（CardArrears:欠款金额（收入：“+”，支出：“-”））
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears-" + ConvertHelper.GetDecimal(loanMoney) + " WHERE CreditCardId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 3)//储蓄卡
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder+" + ConvertHelper.GetDecimal(loanMoney) + " WHERE SavingsCardId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 4)//网上银行
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder+" + ConvertHelper.GetDecimal(loanMoney) + " WHERE OnlinePayId=" + accountId + "", "constring");
                    }
                    if (flagAccount > 0)//账户余额修改成功
                    {
                        //LoanRemainder:借贷账户余额（正数-借贷方欠账户的，0-没有借贷关系，负数-账户欠借贷方的）(借贷类型为1-借入--（借贷账户余额-借贷金额），2-借出--（余额+借贷金额），3-收款--（借贷账户余额-借贷金额），4-还款--（借贷账户余额+借贷金额）)
                        int flagLoanAccount = SqlHelper.Operation("UPDATE tabA_Account_Loan SET LoanRemainder=LoanRemainder-" + ConvertHelper.GetDecimal(loanMoney) + "", "constring");
                        if (flagLoanAccount > 0)//借贷账户余额修改成功（余额-借出金额）
                        {
                            BindRptDetailLoan();
                        }
                        else//借贷账户余额修改失败
                        {
                            ScriptHelper.AlertMessage(this.Page, "删除失败，请联系管理员！");
                        }
                    }
                    else//账户余额修改失败
                    {
                        SqlHelper.Operation("UPDATE V_Detail_Loan SET State=1 WHERE RecordLoanId=" + recordLoanId + "", "constring");//借贷记录还原为未删除（state变为1未删除（state：0-已删除，1-未删除））
                        ScriptHelper.AlertMessage(this.Page, "删除失败，请联系管理员！");
                    }
                    #endregion
                }
                else if(loanTypeId==3)//收款
                {
                    #region 收款金额还原
                    int flagAccount = 0;//账户余额修改是否成功标志（余额-借入金额-利息）
                    if (accountTypeId == 1)//现金账户
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder-" + ConvertHelper.GetDecimal(loanMoney) + "-"+ConvertHelper.GetDecimal(loanInterest)+" WHERE CashAccountId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 2)//信用卡（CardArrears:欠款金额（收入：“+”，支出：“-”））
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears+" + ConvertHelper.GetDecimal(loanMoney) + "+"+ConvertHelper.GetDecimal(loanInterest)+" WHERE CreditCardId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 3)//储蓄卡
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder-" + ConvertHelper.GetDecimal(loanMoney) + "-" + ConvertHelper.GetDecimal(loanInterest) + " WHERE SavingsCardId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 4)//网上银行
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder-" + ConvertHelper.GetDecimal(loanMoney) + "-" + ConvertHelper.GetDecimal(loanInterest) + " WHERE OnlinePayId=" + accountId + "", "constring");
                    }
                    if (flagAccount > 0)//账户余额修改成功
                    {
                        //LoanRemainder:借贷账户余额（正数-借贷方欠账户的，0-没有借贷关系，负数-账户欠借贷方的）(借贷类型为1-借入--（借贷账户余额-借贷金额），2-借出--（余额+借贷金额），3-收款--（借贷账户余额-借贷金额），4-还款--（借贷账户余额+借贷金额）)
                        int flagLoanAccount = SqlHelper.Operation("UPDATE tabA_Account_Loan SET LoanRemainder=LoanRemainder+" + ConvertHelper.GetDecimal(loanMoney) + "", "constring");
                        if (flagLoanAccount > 0)//借贷账户余额修改成功（余额+借出金额）
                        {
                            BindRptDetailLoan();
                        }
                        else//借贷账户余额修改失败
                        {
                            ScriptHelper.AlertMessage(this.Page, "删除失败，请联系管理员！");
                        }
                    }
                    else//账户余额修改失败
                    {
                        SqlHelper.Operation("UPDATE V_Detail_Loan SET State=1 WHERE RecordLoanId=" + recordLoanId + "", "constring");//借贷记录还原为未删除（state变为1未删除（state：0-已删除，1-未删除））
                        ScriptHelper.AlertMessage(this.Page, "删除失败，请联系管理员！");
                    }
                    #endregion
                }
                else if(loanTypeId==4)//还款
                {
                    #region 还款金额还原
                    int flagAccount = 0;//账户余额修改是否成功标志（余额+借出金额）
                    if (accountTypeId == 1)//现金账户
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder+" + ConvertHelper.GetDecimal(loanMoney) + "+"+ConvertHelper.GetDecimal(loanInterest)+" WHERE CashAccountId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 2)//信用卡（CardArrears:欠款金额（收入：“+”，支出：“-”））
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears-" + ConvertHelper.GetDecimal(loanMoney) + "-"+ConvertHelper.GetDecimal(loanInterest)+" WHERE CreditCardId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 3)//储蓄卡
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder+" + ConvertHelper.GetDecimal(loanMoney) + "+"+ConvertHelper.GetDecimal(loanInterest)+" WHERE SavingsCardId=" + accountId + "", "constring");
                    }
                    else if (accountTypeId == 4)//网上银行
                    {
                        flagAccount = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder+" + ConvertHelper.GetDecimal(loanMoney) + "+"+ConvertHelper.GetDecimal(loanInterest)+" WHERE OnlinePayId=" + accountId + "", "constring");
                    }
                    if (flagAccount > 0)//账户余额修改成功
                    {
                        //LoanRemainder:借贷账户余额（正数-借贷方欠账户的，0-没有借贷关系，负数-账户欠借贷方的）(借贷类型为1-借入--（借贷账户余额-借贷金额），2-借出--（余额+借贷金额），3-收款--（借贷账户余额-借贷金额），4-还款--（借贷账户余额+借贷金额）)
                        int flagLoanAccount = SqlHelper.Operation("UPDATE tabA_Account_Loan SET LoanRemainder=LoanRemainder-" + ConvertHelper.GetDecimal(loanMoney) + "", "constring");
                        if (flagLoanAccount > 0)//借贷账户余额修改成功（余额-借出金额）
                        {
                            BindRptDetailLoan();
                        }
                        else//借贷账户余额修改失败
                        {
                            ScriptHelper.AlertMessage(this.Page, "删除失败，请联系管理员！");
                        }
                    }
                    else//账户余额修改失败
                    {
                        SqlHelper.Operation("UPDATE V_Detail_Loan SET State=1 WHERE RecordLoanId=" + recordLoanId + "", "constring");//借贷记录还原为未删除（state变为1未删除（state：0-已删除，1-未删除））
                        ScriptHelper.AlertMessage(this.Page, "删除失败，请联系管理员！");
                    }
                    #endregion
                }
                #endregion
            }
            else//删除借贷记录失败
            {
                ScriptHelper.AlertMessage(this.Page,"删除失败，请联系管理员！");
            }
            #endregion
        }
    }
    #region 获取借贷类型名
    /// <summary>
    /// 获取借贷类型名
    /// </summary>
    /// <param name="loanTypeId">借贷类型id</param>
    /// <returns></returns>
    public string GetLoanTypeName(object loanTypeId)
    {
        string loanTypeName = "";//借贷类型名
        int LoanTypeId = ConvertHelper.GetInteger(loanTypeId);
        if(LoanTypeId==1)//借入
        {
            loanTypeName = "借入";
        }
        else if(LoanTypeId==2)//借出
        {
            loanTypeName = "借出";
        }
        else if(LoanTypeId==3)//收款
        {
            loanTypeName = "收款";
        }
        else if(LoanTypeId==4)//还款
        {
            loanTypeName = "还款";
        }
        return loanTypeName;
    }
    #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;
        BindRptDetailLoan();
        spanPageCurrent.InnerHtml = "1";//当前页为1
    }
    #endregion
    #region 上页
    protected void lbtnPageUp_Click(object sender, EventArgs e)//上页
    {
        if (spanPageCurrent.InnerHtml != "1")//不是首页时
        {
            currentPageNum = ConvertHelper.GetInteger(spanPageCurrent.InnerHtml) - 1;
            BindRptDetailLoan();
            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;
            BindRptDetailLoan();
            spanPageCurrent.InnerHtml = ConvertHelper.GetString(currentPageNum);//当前页spanPageCurrent赋值
        }
    }
    #endregion
    #region 末页
    protected void lbtnPageLast_Click(object sender, EventArgs e)//末页
    {
        currentPageNum = GetPageCount();
        BindRptDetailLoan();
        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 RLoanDateTime DESC) AS Row,RecordLoanId,RecordLoanMoney,RLoanInterest,RecordLoanTypeId,RLOutsideAccountId,LoanAccountName,RLInsideAccountTypeId,RLInsideAccountId,AccountName,RLoanDateTime,RecordLoanRemarks,HandlerId FROM V_Detail_Loan WHERE State=1) AS temptable  WHERE 1=1 ");
        if (ConvertHelper.GetDateTime(txtStateTime) < ConvertHelper.GetDateTime(txtEndTime.Text.Trim()))//如果开始时间小于最后时间(即正常情况)
        {
            strb.Append(" AND (RLoanDateTime>='" + ConvertHelper.GetDateTime(txtStateTime.Text.Trim()) + "' AND RLoanDateTime<='" + 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 RLoanDateTime BETWEEN '" + ConvertHelper.GetDateTime(txtStateTime.Text.Trim()) + "' AND '" + ConvertHelper.GetDateTime(txtEndTime.Text.Trim()) + "' ");
        }
        if(ddlLoanType.SelectedValue!="0")//借贷类型不为空
        {
            strb.Append(" AND RecordLoanTypeId="+ConvertHelper.GetInteger(ddlLoanType.SelectedValue)+" ");
        }
        if(ddlLoanAccount.SelectedValue!="0")//债务(权)人
        {
            strb.Append(" AND RLOutsideAccountId="+ConvertHelper.GetInteger(ddlLoanAccount.SelectedValue)+" ");
        }
        StrWhere = strb.ToString();
    }
    #endregion
    #region 查询事件
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        BindRptDetailLoan();
        BindLoanCount();
    }
    #endregion
}