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

public partial class A_Detail_ExpenditureInfo : PageBase
{
    private static int expenditureTypeId = 0;//修改后支出类型id
    private static int sellerId = 0;//修改后商家id
    private static int accountTypeId = 0;//修改后账户类型id（1-现金账户，2-信用卡账户，3-储蓄卡账户，4-网上支付账户）；
    private static int accountId = 0;//修改后账户id
    private static int projectId = 0;//修改后项目id
    private static int accountTypeIdBefore = 0;//修改前账户类型id（1-现金账户，2-信用卡账户，3-储蓄卡账户，4-网上支付账户）；
    private static int accountIdBefore=0;//修改前账户id
    private static double expenditureMoneyBefore = 0.00;//修改前的支出金额
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!this.Page.IsPostBack)
        {
            OfficeManage.BindDdlExpenditureType(ddlExpenditureType);//绑定支出类型
            OfficeManage.BindDdlSeller(ddlSeller);//绑定商家
            OfficeManage.BindDdlProject(ddlProject);//绑定项目
            BindPage();
        }
    }
    #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 BindPage()
    {
        if (!string.IsNullOrEmpty(Request["deiid"]))
        {
            //V_Detail_Expenditure视图：支出明细视图
            DataSet ds = SqlHelper.GetDataSet("SELECT RExpenditureMoney,RExpenditureTypeId,ExpenditureTypeName,ExpenditureTypeState,RExpenditureSellerId,SellerName,SellerState,REAccountTypeId,REAccountId,RExpenditureDateTime,REProjectId,ProjectTypeName,ProjectState,RExpenditureRemarks FROM dbo.V_Detail_Expenditure WHERE State=1 AND RecordExpenditureId=" + ConvertHelper.GetInteger(Request["deiid"]) + "", "constring");
            if(ds.Tables[0].Rows.Count>0)
            {
                #region 修改前账户类型id，账户id，支出金额
                accountTypeIdBefore = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountTypeId"]);//修改前账户类型id
                accountIdBefore = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]);//修改前账户id
                expenditureMoneyBefore = ConvertHelper.GetDouble(ds.Tables[0].Rows[0]["RExpenditureMoney"]);//修改前支出金额
                #endregion
                txtExpenditureMoney.Text = ConvertHelper.GetString(ds.Tables[0].Rows[0]["RExpenditureMoney"]);//支出金额
                #region 支出类型
                if (ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["ExpenditureTypeState"]) == 0)//支出类型已删除(0-已删除，1-未删除)
                {
                    spanOriginalEType.InnerHtml = "现支出类型：" + ConvertHelper.GetString(ds.Tables[0].Rows[0]["ExpenditureTypeName"]);//已删除的支出类型名
                    expenditureTypeId = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["RExpenditureTypeId"]);//支出类型id
                }
                else//支出类型未删除
                {
                    ddlExpenditureType.SelectedValue = ConvertHelper.GetString(ds.Tables[0].Rows[0]["RExpenditureTypeId"]);//支出类型
                }
                #endregion
                #region 商家
                if (ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["SellerState"]) == 0)//商家已删除（0-已删除，1-未删除）
                {
                    spanOriginalSeller.InnerHtml = "现商家：" + ConvertHelper.GetString(ds.Tables[0].Rows[0]["SellerName"]);//已删除的商家名
                    sellerId = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["RExpenditureSellerId"]);//商家id
                }
                else//商家未删除
                {
                    ddlSeller.SelectedValue = ConvertHelper.GetString(ds.Tables[0].Rows[0]["RExpenditureSellerId"]);//商家
                }
                #endregion
                #region 支出账户
                uclAccount.AccountTypeID = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountTypeId"]);//账户类型id
                accountTypeId = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountTypeId"]);//账户类型id
                if(uclAccount.AccountTypeID==1)//现金账户
                {
                    #region 现金账户
                    DataSet dsCashAccount = SqlHelper.GetDataSet("SELECT CashAccountName,State FROM dbo.tabA_Account_Cash WHERE CashAccountId=" + ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]) + "", "constring");
                    if (dsCashAccount.Tables[0].Rows.Count > 0)
                    {
                        if (ConvertHelper.GetInteger(dsCashAccount.Tables[0].Rows[0]["State"]) == 0)//现金账户已删除（0-已删除，1-未删除）
                        {
                            spanOriginalAccount.InnerHtml = "现账户：" + ConvertHelper.GetString(dsCashAccount.Tables[0].Rows[0]["CashAccountName"]);//已删除的现金账户
                            accountId = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]);//账户id
                        }
                        else//现金账户未删除
                        {
                            uclAccount.CashAccountID = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]);//现金账户
                        }
                    }
                    #endregion
                }
                else if (uclAccount.AccountTypeID == 2)//信用卡
                {
                    #region 信用卡
                    DataSet dsCreditCard = SqlHelper.GetDataSet("SELECT CreditCardName,State FROM dbo.tabA_Account_CreditCard WHERE CreditCardId=" + ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]) + "", "constring");
                    if (dsCreditCard.Tables[0].Rows.Count > 0)
                    {
                        if (ConvertHelper.GetInteger(dsCreditCard.Tables[0].Rows[0]["State"]) == 0)//信用卡已删除（0-已删除，1-未删除）
                        {
                            spanOriginalAccount.InnerHtml = "现账户：" + ConvertHelper.GetString(dsCreditCard.Tables[0].Rows[0]["CreditCardName"]);//已删除的信用卡
                            accountId = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]);//账户id
                        }
                        else//信用卡未删除
                        {
                            uclAccount.CreditCardID = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]);//信用卡
                        }
                    }
                    #endregion
                }
                else if (uclAccount.AccountTypeID == 3)//储蓄卡
                {
                    #region 储蓄卡
                    DataSet dsSavingsCard = SqlHelper.GetDataSet("SELECT SavingsCardName,State FROM dbo.tabA_Account_SavingsCard WHERE SavingsCardId=" + ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]) + "", "constring");
                    if (dsSavingsCard.Tables[0].Rows.Count > 0)
                    {
                        if (ConvertHelper.GetInteger(dsSavingsCard.Tables[0].Rows[0]["State"]) == 0)//储蓄卡已删除（0-已删除，1-未删除）
                        {
                            spanOriginalAccount.InnerHtml = "现账户：" + ConvertHelper.GetString(dsSavingsCard.Tables[0].Rows[0]["SavingsCardName"]);//已删除储蓄卡名
                            accountId = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]);//账户id
                        }
                        else//储蓄卡未删除
                        {
                            uclAccount.SavingsCardID = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]);//储蓄卡
                        }
                    }
                    #endregion
                }
                else if(uclAccount.AccountTypeID==4)//网上支付
                {
                    #region 网上支付
                    DataSet dsOnlinePay = SqlHelper.GetDataSet("SELECT OnlinePayName,State FROM dbo.tabA_Account_OnlinePay WHERE OnlinePayId=" + ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]) + "", "constring");
                    if (dsOnlinePay.Tables[0].Rows.Count > 0)
                    {
                        if (ConvertHelper.GetInteger(dsOnlinePay.Tables[0].Rows[0]["State"]) == 0)//网上支付已删除（0-已删除，1-未删除）
                        {
                            spanOriginalAccount.InnerHtml = "现账户：" + ConvertHelper.GetString(dsOnlinePay.Tables[0].Rows[0]["OnlinePayName"]);//已删除网上支付名
                            accountId = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]);//账户id
                        }
                        else//网上支付未删除
                        {
                            uclAccount.OnlinePayID = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REAccountId"]);//网上支付
                        }
                    }
                    #endregion
                }
                #endregion
                txtExpenditureDateTime.Text = ConvertHelper.GetString(ds.Tables[0].Rows[0]["RExpenditureDateTime"]);//支出时间
                #region 项目
                if (ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["ProjectState"]) == 0)//项目已删除（0-已删除，1-未删除）
                {
                    spanOriginalProject.InnerHtml = "现项目：" + ConvertHelper.GetString(ds.Tables[0].Rows[0]["ProjectTypeName"]);//已删除项目名
                    projectId = ConvertHelper.GetInteger(ds.Tables[0].Rows[0]["REProjectId"]);//项目id
                }
                else//项目未删除
                {
                    ddlProject.SelectedValue = ConvertHelper.GetString(ds.Tables[0].Rows[0]["REProjectId"]);//项目
                }
                #endregion
            }
        }
    }
    #endregion

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request["deiid"]))
        {
            #region 修改支出类型id
            if (spanOriginalEType.InnerHtml == "")//现支出类型未删除
            {
                expenditureTypeId = ConvertHelper.GetInteger(ddlExpenditureType.SelectedValue);
            }
            else//支出类型已删除
            {
                if (ddlExpenditureType.SelectedValue != "0")//重新修改了支出类型
                {
                    expenditureTypeId = ConvertHelper.GetInteger(ddlExpenditureType.SelectedValue);
                }
            }
            #endregion
            #region 修改商家id
            if (spanOriginalSeller.InnerHtml == "")//现商家未删除
            {
                sellerId = ConvertHelper.GetInteger(ddlSeller.SelectedValue);
            }
            else//商家已删除
            {
                if (ddlSeller.SelectedValue != "0")
                {
                    sellerId = ConvertHelper.GetInteger(ddlSeller.SelectedValue);
                }
            }
            #endregion
            #region 修改账户类型id及账户id
            if (spanOriginalAccount.InnerHtml == "")//现账户未删除
            {
                accountTypeId = ConvertHelper.GetInteger(uclAccount.AccountTypeID);//账户类型id
                if (accountTypeId == 1)//现金账户
                {
                    accountId = ConvertHelper.GetInteger(uclAccount.CashAccountID);
                }
                else if (accountTypeId == 2)//信用卡
                {
                    accountId = ConvertHelper.GetInteger(uclAccount.CreditCardID);
                }
                else if (accountTypeId == 3)//储蓄卡
                {
                    accountId = ConvertHelper.GetInteger(uclAccount.SavingsCardID);
                }
                else if (accountTypeId == 4)//网上支付
                {
                    accountId = ConvertHelper.GetInteger(uclAccount.OnlinePayID);
                }
            }
            else//账户已删除
            {
                if (!(uclAccount.CashAccountID == 0 && uclAccount.CreditCardID == 0 && uclAccount.SavingsCardID == 0 && uclAccount.OnlinePayID == 0))
                {
                    accountTypeId = ConvertHelper.GetInteger(uclAccount.AccountTypeID);//账户类型id
                    if (accountTypeId == 1)//现金账户
                    {
                        accountId = ConvertHelper.GetInteger(uclAccount.CashAccountID);
                    }
                    else if (accountTypeId == 2)//信用卡
                    {
                        accountId = ConvertHelper.GetInteger(uclAccount.CreditCardID);
                    }
                    else if (accountTypeId == 3)//储蓄卡
                    {
                        accountId = ConvertHelper.GetInteger(uclAccount.SavingsCardID);
                    }
                    else if (accountTypeId == 4)//网上支付
                    {
                        accountId = ConvertHelper.GetInteger(uclAccount.OnlinePayID);
                    }
                }
            }
            #endregion
            #region 修改项目id
            if (spanOriginalProject.InnerHtml == "")//项目未删除
            {
                projectId = ConvertHelper.GetInteger(ddlProject.SelectedValue);
            }
            else//项目已删除
            {
                if (ddlProject.SelectedValue != "0")
                {
                    projectId = ConvertHelper.GetInteger(ddlProject.SelectedValue);
                }
            }
            #endregion
            int flag = SqlHelper.Operation("UPDATE dbo.tabA_Record_Expenditure SET RExpenditureMoney=" + ConvertHelper.GetDecimal(txtExpenditureMoney.Text.Trim()) + ",RExpenditureTypeId=" + expenditureTypeId + ",RExpenditureSellerId=" + sellerId + ",REAccountTypeId=" + accountTypeId + ",REAccountId=" + accountId + ",RExpenditureDateTime='" + ConvertHelper.GetDateTime(txtExpenditureDateTime.Text.Trim()) + "',REProjectId=" + projectId + ",RExpenditureRemarks='" + txtExpenditureRemarks.Text.Trim() + "',UpdateTime='" + System.DateTime.Now + "' WHERE RecordExpenditureId=" + ConvertHelper.GetInteger(Request["deiid"]) + "", "constring");
            if (flag > 0)//记账支出修改成功
            {
                if (accountTypeId == accountTypeIdBefore && accountId == accountIdBefore)//修改前后账户类型相同，账户相同
                {
                    if (ConvertHelper.GetDouble(txtExpenditureMoney.Text.Trim()) != expenditureMoneyBefore)//支出金额不同
                    {
                        int flags = 0;//修改前后账户类型相同，账户相同，支出金额不同的余额修改是否成功的标志
                        if (accountTypeId == 1)//现金账户
                        {
                            flags = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder+" + ConvertHelper.GetDecimal(expenditureMoneyBefore) + "-" + ConvertHelper.GetDecimal(txtExpenditureMoney.Text.Trim()) + " WHERE CashAccountId=" + accountId + "", "constring");
                        }
                        else if (accountTypeId == 2)//信用卡(CardArrears:欠款金额，所以支出是“+”，收入是“-”)
                        {
                            flags = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears-" + ConvertHelper.GetDecimal(expenditureMoneyBefore) + "+" + ConvertHelper.GetDecimal(txtExpenditureMoney.Text.Trim()) + " WHERE CreditCardId=" + accountId + "", "constring");
                        }
                        else if (accountTypeId == 3)//储蓄卡
                        {
                            flags = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder+" + ConvertHelper.GetDecimal(expenditureMoneyBefore) + "-" + ConvertHelper.GetDecimal(txtExpenditureMoney.Text.Trim()) + " WHERE SavingsCardId=" + accountId + "", "constring");
                        }
                        else if (accountTypeId == 4)//网上支付
                        {
                            flags = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder+" + ConvertHelper.GetDecimal(expenditureMoneyBefore) + "-" + ConvertHelper.GetDecimal(txtExpenditureMoney.Text.Trim()) + " WHERE OnlinePayId=" + accountId + "", "constring");
                        }
                        if (flags > 0)//修改前后账户类型相同，账户相同，支出金额不同的余额修改成功
                        {
                            Response.Redirect("Detail_Expenditure.aspx");
                        }
                        else//修改前后账户类型相同，账户相同，支出金额不同的余额修改失败
                        {
                            ScriptHelper.AlertMessage(this.Page, "修改失败，请联系管理员！");
                        }
                    }
                    else//修改前后账户类型，账户id，支出金额相同时，账户表不做任何操作，直接跳转到支出明细页
                    {
                        Response.Redirect("Detail_Expenditure.aspx");
                    }
                }
                else
                {
                    int flagBefore = 0;//修改前后账户类型相同，账户不同的修改前账户余额修改是否成功的标志
                    if (accountTypeIdBefore == 1)//修改前账户类型为现金账户
                    {
                        flagBefore = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder+" + ConvertHelper.GetDecimal(expenditureMoneyBefore) + " WHERE CashAccountId=" + accountIdBefore + "", "constring");
                    }
                    else if (accountTypeIdBefore == 2)//修改前账户类型为信用卡(CardArrears:欠款金额，所以支出是“+”，收入是“-”)
                    {
                        flagBefore = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears-" + ConvertHelper.GetDecimal(expenditureMoneyBefore) + " WHERE CreditCardId=" + accountIdBefore + "", "constring");
                    }
                    else if (accountTypeIdBefore == 3)//修改前账户类型为储蓄卡
                    {
                        flagBefore = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder+" + ConvertHelper.GetDecimal(expenditureMoneyBefore) + " WHERE SavingsCardId=" + accountIdBefore + "", "constring");
                    }
                    else if (accountTypeIdBefore == 4)//修改前账户类型为网上支付
                    {
                        flagBefore = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder+" + ConvertHelper.GetDecimal(expenditureMoneyBefore) + " WHERE OnlinePayId=" + accountIdBefore + "", "constring");
                    }
                    if (flagBefore > 0)//修改前的账户余额修改成功
                    {
                        int flagAfter = 0;//修改前后账户类型相同，账户不同的修改后账户余额修改是否成功的标志
                        if (accountTypeId == 1)//修改后现金账户
                        {
                            flagAfter = SqlHelper.Operation("UPDATE dbo.tabA_Account_Cash SET CashRemainder=CashRemainder-" + ConvertHelper.GetDecimal(txtExpenditureMoney.Text.Trim()) + " WHERE CashAccountId=" + accountId + "", "constring");
                        }
                        else if (accountTypeId == 2)//修改后信用卡(CardArrears:欠款金额，所以支出是“+”，收入是“-”)
                        {
                            flagAfter = SqlHelper.Operation("UPDATE dbo.tabA_Account_CreditCard SET CardArrears=CardArrears+" + ConvertHelper.GetDecimal(txtExpenditureMoney.Text.Trim()) + " WHERE CreditCardId=" + accountId + "", "constring");
                        }
                        else if (accountTypeId == 3)//修改后储蓄卡
                        {
                            flagAfter = SqlHelper.Operation("UPDATE dbo.tabA_Account_SavingsCard SET SavingsCardRemainder=SavingsCardRemainder-" + ConvertHelper.GetDecimal(txtExpenditureMoney.Text.Trim()) + " WHERE SavingsCardId=" + accountId + "", "constring");
                        }
                        else if (accountTypeId == 4)//修改后网上支付
                        {
                            flagAfter = SqlHelper.Operation("UPDATE dbo.tabA_Account_OnlinePay SET OnlinePayRemainder=OnlinePayRemainder-" + ConvertHelper.GetDecimal(txtExpenditureMoney.Text.Trim()) + " WHERE OnlinePayId=" + accountId + "", "constring");
                        }
                        if (flagAfter > 0)//修改后的账户余额修改成功
                        {
                            Response.Redirect("Detail_Expenditure.aspx");
                        }
                        else//修改后的账户余额修改失败
                        {
                            ScriptHelper.AlertMessage(this.Page, "修改失败，请联系管理员！");
                        }
                    }
                    else//修改前的账户余额修改失败
                    {
                        ScriptHelper.AlertMessage(this.Page, "修改失败，请联系管理员！");
                    }
                }
            }
            else//记账支出修改失败
            {
                ScriptHelper.AlertMessage(this.Page,"修改失败，请联系管理员！");
            }
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)//取消事件
    {
        Response.Redirect("Detail_Expenditure.aspx");
    }
}