protected void AddEmptyDetail()
    {
        SaveGrid();

        ListTable<FNA_FeeApplyDetail> _details = ViewState["Details"] as ListTable<FNA_FeeApplyDetail>;
        for (int i = 0; i < 5; i++)
        {
            ViewState["MaxID"] = (int)ViewState["MaxID"] + 1;

            FNA_FeeApplyDetail item;

            item = new FNA_FeeApplyDetail();
            item.AccountTitle = 1;
            item.ApplyCost = 0;
            item.ID = (int)ViewState["MaxID"];

            #region 获取当前会计月的开始及截止日期
            int month = (int)ViewState["AccountMonth"];
            if (month == 0) month = AC_AccountMonthBLL.GetCurrentMonth();
            AC_AccountMonth m = new AC_AccountMonthBLL(month).Model;
            item.BeginDate = m.BeginDate;
            item.EndDate = m.EndDate;
            item.BeginMonth = month;
            item.EndMonth = month;
            #endregion

            item.Flag = 1;                  //未报销
            item.Remark = "";
            _details.Add(item);             //新增科目
        }
        BindGrid();
    }
    protected void gv_List_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int id = (int)gv_List.DataKeys[e.Row.RowIndex]["ID"];
            int applydetailid = (int)gv_List.DataKeys[e.Row.RowIndex]["ApplyDetailID"];

            ListTable<FNA_FeeWriteOffDetail> _details = Session["FeeWriteOffDetails"] as ListTable<FNA_FeeWriteOffDetail>;
            FNA_FeeWriteOffDetail m = _details[id.ToString()];

            string sheetcode = "";

            FNA_FeeApplyDetail applydetail = new FNA_FeeApplyDetail();
            if (applydetailid > 0)
            {
                applydetail = new FNA_FeeApplyBLL().GetDetailModel(applydetailid);
                sheetcode = FNA_FeeApplyBLL.GetSheetCodeByDetailID(applydetailid);

            }

            HyperLink hy_ApplySheetCode = (HyperLink)e.Row.FindControl("hy_ApplySheetCode");
            hy_ApplySheetCode.Text = sheetcode;
            hy_ApplySheetCode.NavigateUrl = "~/SubModule/FNA/FeeApply/FeeApplyDetail3.aspx?ID=" + applydetail.ApplyID;

            if (applydetail.Client > 0)
            {
                HyperLink hy_Client = (HyperLink)e.Row.FindControl("hy_Client");
                hy_Client.Text = new CM_ClientBLL(applydetail.Client).Model.FullName;
                hy_Client.NavigateUrl = "~/SubModule/CM/RT/RetailerDetail.aspx?ClientID=" + m.Client;
            }

            DropDownList ddl_BalanceMode = (DropDownList)e.Row.FindControl("ddl_BalanceMode");
            if (ddl_BalanceMode != null)
            {
                ddl_BalanceMode.Enabled = m.WriteOffCost < m.ApplyCost;
                if (m.BalanceMode > 0) ddl_BalanceMode.SelectedValue = m.BalanceMode.ToString();
            }
        }
    }
    protected void bt_Generate_Click(object sender, EventArgs e)
    {
        if (ddl_Contract.SelectedValue != "" && ddl_Contract.SelectedValue != "0")
        {
            #region 本次合同费用支付的开始及截止日期
            CM_ContractBLL contractbll = new CM_ContractBLL(int.Parse(ddl_Contract.SelectedValue));

            #region 获取最早的付款截止日期,再次获取,是防止同时打开多个该页面后,分别点申请费用
            DateTime begindate = GetMinPayDate(contractbll);

            if (begindate >= contractbll.Model.EndDate)
            {
                MessageBox.Show(this, "对不起,该合同没有需要付款的明细科目!");
                bt_Generate.Enabled = false;
                return;
            }

            lb_PayDateRegion.Text = begindate.ToString("yyyy年MM月dd日");
            #endregion

            DateTime enddate = contractbll.Model.EndDate;

            DateTime monthenddate = new AC_AccountMonthBLL(int.Parse(ddl_EndMonth.SelectedValue) + 1).Model.EndDate;
            while (enddate > monthenddate)
            {
                enddate = enddate.AddMonths(-1);
            }
            if (enddate <= begindate)
            {
                MessageBox.Show(this, "该合同所有范围的款项均已支付完成!" + enddate.ToString());
                return;
            }
            #endregion

            #region 求出当前客户的直销总经销商
            CM_Client client = new CM_ClientBLL((int)ViewState["ClientID"]).Model;
            if (client == null) return;
            int supplier = 0;

            while (client != null)
            {
                client = new CM_ClientBLL(client.Supplier).Model;
                if (client == null) break;
                if (client.ClientType == 2 && client["DIClassify"] == "1")
                {
                    supplier = client.ID;
                    break;
                }
            }
            #endregion

            FNA_FeeApplyBLL bll = new FNA_FeeApplyBLL();

            bll.Model.OrganizeCity = int.Parse(tr_OrganizeCity.SelectValue);
            bll.Model.AccountMonth = int.Parse(ddl_Month.SelectedValue);
            bll.Model.Client = supplier;       //费用代垫客户
            bll.Model.State = 1;               //草稿
            bll.Model.ApproveFlag = 2;         //未审核
            bll.Model.InsertStaff = (int)Session["UserID"];
            bll.Model["Title"] = ddl_Month.SelectedItem.Text + " 合同费用提前预支付申请单" + " " + select_Client.SelectText + " " + Session["UserRealName"].ToString();

            #region 判断合同类型
            switch (contractbll.Model.Classify)
            {
                case 1:         //陈列合同
                    if (new CM_ClientBLL((int)ViewState["ClientID"]).Model["RTChannel"] == "1")
                        //NKA合同费用
                        bll.Model.FeeType = ConfigHelper.GetConfigInt("ContractFeeType-KA");
                    else
                        //非NKA合同费用
                        bll.Model.FeeType = ConfigHelper.GetConfigInt("ContractFeeType");
                    break;
                case 3:         //导购管理费
                    bll.Model.FeeType = ConfigHelper.GetConfigInt("ContractFeeType-PromotorCost");
                    break;
                case 21:        //租赁合同
                    bll.Model.FeeType = ConfigHelper.GetConfigInt("ContractFeeType-PD");
                    break;
                default:
                    MessageBox.Show(this, "对不起,该合同类型暂不支持费用申请!合同类别:" + contractbll.Model.Classify.ToString());
                    return;
            }
            if (contractbll.Model.Classify != 21)
            {
                if (contractbll.Items.Where(p => p.PayMode > 1).ToList().Count == 0)
                {
                    //非租赁费的合同,不可申请逐月支付的科目费用
                    MessageBox.Show(this, "对不起,付款方式为每月付的科目不可提前申请费用!");
                    return;
                }
            }
            #endregion

            foreach (CM_ContractDetail item in contractbll.Items)
            {
                if (contractbll.Model.Classify != 21)
                {
                    //非租赁费的合同,不可申请逐月支付的科目费用
                    if (item.PayMode == 1) continue;
                }

                DateTime d = begindate;
                while (d < enddate)
                {
                    FNA_FeeApplyDetail detail = new FNA_FeeApplyDetail();
                    detail.Client = (int)ViewState["ClientID"];
                    detail.AccountTitle = item.AccountTitle;
                    detail.BeginDate = d;

                    if (d.AddMonths(1).AddDays(-1) <= contractbll.Model.EndDate)
                    {
                        detail.EndDate = d.AddMonths(1).AddDays(-1);
                        detail.ApplyCost = item.ApplyLimit * item.BearPercent / 100;
                        detail.DICost = item.ApplyLimit * (100 - item.BearPercent) / 100;
                    }
                    else
                    {
                        #region 最后一个月不足一个月时的处理
                        detail.EndDate = contractbll.Model.EndDate;
                        int days = (detail.EndDate - detail.BeginDate).Days + 1;
                        detail.ApplyCost = Math.Round(item.ApplyLimit * days / 30, 1, MidpointRounding.AwayFromZero) * item.BearPercent / 100;
                        detail.DICost = Math.Round(item.ApplyLimit * days / 30, 1, MidpointRounding.AwayFromZero) * (100 - item.BearPercent) / 100;
                        #endregion
                    }
                    detail.BeginMonth = AC_AccountMonthBLL.GetMonthByDate(detail.BeginDate);
                    detail.EndMonth = detail.BeginMonth;
                    detail.LastWriteOffMonth = bll.Model.AccountMonth + 1;

                    #region 不可申请之前月的费用
                    if (detail.BeginMonth < bll.Model.AccountMonth)
                    {
                        d = d.AddMonths(1);
                        continue;
                    }
                    #endregion

                    #region 判断当月费用是否已申请过
                    string condition = "Client = " + detail.Client.ToString() + " AND RelateContractDetail = " + item.ID.ToString() + " AND Flag<>3";
                    if (item.PayMode != 20) condition += "AND BeginMonth=" + detail.BeginMonth.ToString();

                    if (new FNA_FeeApplyBLL().GetDetail(condition).Count > 0)
                    {
                        d = d.AddMonths(1);
                        continue;
                    }
                    #endregion

                    detail.RelateContractDetail = item.ID;
                    detail.Remark = "合同编号:" + contractbll.Model["Code"] + " 日期范围:" + detail.BeginDate.ToString("yyyy-MM-dd") + "~" + detail.EndDate.ToString("yyyy-MM-dd");
                    detail.RelateBrands = item["RelateBrand"];
                    if (string.IsNullOrEmpty(detail.RelateBrands))
                    {
                        foreach (PDT_Brand brand in PDT_BrandBLL.GetModelList("IsOpponent=1"))
                        {
                            detail.RelateBrands += brand.ID.ToString() + ",";
                        }
                    }
                    detail.Flag = 1;  //未报销
                    detail["FeeApplyType"] = (d == contractbll.Model.BeginDate ? "1" : "2");
                    bll.Items.Add(detail);

                    d = d.AddMonths(1);

                    #region 以协议里该科目付款周期为准
                    if (item.PayMode != 20)
                    {
                        DateTime maxpaydate = begindate.AddMonths(item.PayMode).AddDays(-1);
                        if (d > maxpaydate) break;
                    }
                    else
                    {
                        break;
                    }
                    #endregion
                }
            }

            bll.Model.SheetCode = FNA_FeeApplyBLL.GenerateSheetCode(bll.Model.OrganizeCity, bll.Model.AccountMonth);
            int applyid = bll.Add();

            MessageBox.ShowAndRedirect(this, "费用申请成功!", ResolveUrl("~/SubModule/FNA/FeeApply/FeeApplyDetail3.aspx?ID=" + applyid.ToString()));
        }
    }
    protected void bt_Generate_Click(object sender, EventArgs e)
    {
        if (ddl_Contract.SelectedValue != "" && ddl_Contract.SelectedValue != "0")
        {
            CM_ContractBLL contractbll = new CM_ContractBLL(int.Parse(ddl_Contract.SelectedValue));

            DateTime begindate = DateTime.Parse(tbx_BeginDate.Text);
            DateTime enddate = DateTime.Parse(tbx_EndDate.Text);
            if (enddate <= begindate)
            {
                MessageBox.Show(this, "开始日期必需小于截止日期!");
                return;
            }

            if (enddate > contractbll.Model.EndDate)
            {
                MessageBox.Show(this, "截止日期不能大于租赁合同的截止日期" + contractbll.Model.EndDate.ToString("yyyy-MM-dd") + "!");
                return;
            }

            #region 判断该合同是否已生成过费用申请
            if (FNA_FeeApplyBLL.GetModelList(string.Format("State IN (1,2,3) AND FeeType=3 AND ID IN (SELECT ApplyID FROM FNA_FeeApplyDetail WHERE Client={0} AND RelateContractDetail={1} AND BeginDate='{2:yyyy-MM-dd}')",
        contractbll.Model.Client, contractbll.Items[0].ID, begindate)).Count > 0)
            {
                MessageBox.Show(this, "该租赁合同已申请过费用了,请勿重复申请!");
                return;
            }
            #endregion

            #region 计算开始日期及截止日期间月份及天数
            enddate = enddate.AddDays(1);
            DateTime tmpdate = begindate;
            int months = 0, days = 0;

            while (tmpdate.AddMonths(1) <= enddate)
            {
                tmpdate = tmpdate.AddMonths(1);
                months++;
            }
            if (tmpdate < enddate) days = (enddate - tmpdate).Days;
            enddate = enddate.AddDays(-1);
            #endregion

            #region 关联全品项
            string relatebrands = "";
            foreach (PDT_Brand brand in PDT_BrandBLL.GetModelList("IsOpponent=1"))
            {
                relatebrands += brand.ID + ",";
            }
            #endregion

            FNA_FeeApplyBLL bll = new FNA_FeeApplyBLL();

            bll.Model.OrganizeCity = int.Parse(tr_OrganizeCity.SelectValue);
            bll.Model.AccountMonth = int.Parse(ddl_Month.SelectedValue);

            bll.Model.FeeType = 3;      //管理费-租赁费
            bll.Model.State = 1;        //草稿
            bll.Model.ApproveFlag = 2;  //未审核
            bll.Model.InsertStaff = (int)Session["UserID"];
            bll.Model["Title"] = ddl_Month.SelectedItem.Text + " 租赁费申请单" + " " + select_Client.SelectText + " " + Session["UserRealName"].ToString();

            foreach (CM_ContractDetail item in contractbll.Items)
            {
                FNA_FeeApplyDetail detail = new FNA_FeeApplyDetail();
                detail.Client = int.Parse(select_Client.SelectValue);
                detail.AccountTitle = item.AccountTitle;
                detail.ApplyCost = Math.Round(item.ApplyLimit * months + item.ApplyLimit * days / DateTime.DaysInMonth(enddate.Year, enddate.Month), 1, MidpointRounding.AwayFromZero);
                detail.BeginDate = begindate;
                detail.EndDate = enddate;
                detail.BeginMonth = AC_AccountMonthBLL.GetMonthByDate(begindate);
                detail.EndMonth = AC_AccountMonthBLL.GetMonthByDate(enddate);
                detail.RelateContractDetail = item.ID;
                detail.Remark = "合同编号:" + contractbll.Model["Code"] + " 日期范围:" + begindate.ToString("yyyy-MM-dd") + "~" + enddate.ToString("yyyy-MM-dd");
                detail.RelateBrands = relatebrands;
                detail.Flag = 1;  //未报销
                detail["FeeApplyType"] = (begindate == contractbll.Model.BeginDate ? "1" : "2");
                bll.Items.Add(detail);
            }

            bll.Model.SheetCode = FNA_FeeApplyBLL.GenerateSheetCode(bll.Model.OrganizeCity, bll.Model.AccountMonth);
            int applyid = bll.Add();

            MessageBox.ShowAndRedirect(this, "费用申请成功!", ResolveUrl("~/SubModule/FNA/FeeApply/FeeApplyDetail3.aspx?ID=" + applyid.ToString()));
        }
    }
    protected void bt_Generate_Click(object sender, EventArgs e)
    {
        decimal giftamountbalance = 0;
        int month = 0, city = 0, feetype = 0, client = 0, productbrand = 0, giftclassify = 0;
        feetype = (int)ViewState["GiftFeeType"];

        int.TryParse(ddl_ApplyMonth.SelectedValue, out month);
        int.TryParse(tr_OrganizeCity.SelectValue, out city);
        int.TryParse(select_Client.SelectValue, out client);
        int.TryParse(ddl_Brand.SelectedValue, out productbrand);
        int.TryParse(rbl_GiftClassify.SelectedValue, out giftclassify);

        #region 判断有效性
        if (city == 0)
        {
            MessageBox.Show(this, "请正确选择管理片区");
            return;
        }

        if (client == 0)
        {
            MessageBox.Show(this, "请正确选择经销商");
            return;
        }

        if (productbrand == 0)
        {
            MessageBox.Show(this, "请正确选择赠品费用归属品牌");
            return;
        }
        giftamountbalance = GetGiftAmountBalance();
        if (giftamountbalance == 0)
        {
            MessageBox.Show(this, "可申请赠品金额为0,不可申请赠品");
            return;
        }

        int AccountTitle = int.Parse(ddl_AccountTitle.SelectedValue);
        if (TreeTableBLL.GetChild("MCS_PUB.dbo.AC_AccountTitle", "ID", "SuperID", AccountTitle).Rows.Count > 0)
        {
            MessageBox.Show(this, "费用科目必须选择最底级会计科目!" + ddl_AccountTitle.SelectedItem.Text);
            return;
        }

        decimal applycost = 0;
        decimal.TryParse(tbx_ApplyCost.Text, out applycost);
        if (applycost == 0)
        {
            MessageBox.Show(this, "申请赠品金额不可为0");
            return;
        }

        if (applycost > giftamountbalance)
        {
            MessageBox.Show(this, "赠品申请金额:" + tbx_ApplyCost.Text + "不能大于可用申请赠品金额:" + lb_GiftAmountBalance.Text);
            return;
        }
        #endregion

        #region 创建费用申请单
        FNA_FeeApplyBLL bll = new FNA_FeeApplyBLL();

        bll.Model.OrganizeCity = int.Parse(tr_OrganizeCity.SelectValue);
        bll.Model.AccountMonth = int.Parse(ddl_ApplyMonth.SelectedValue);
        bll.Model.Client = client;         //费用代垫客户
        bll.Model.State = 1;               //草稿
        bll.Model.ApproveFlag = 2;         //未审核
        bll.Model.InsertStaff = (int)Session["UserID"];
        bll.Model["Title"] = ddl_ApplyMonth.SelectedItem.Text + " 赠品费用申请单" + " " + select_Client.SelectText + " " + Session["UserRealName"].ToString();
        bll.Model.FeeType = feetype;
        bll.Model["GiftFeeClassify"] = giftclassify.ToString();
        bll.Model.ProductBrand = productbrand;

        AC_AccountMonth accountmonth = new AC_AccountMonthBLL(month).Model;
        FNA_FeeApplyDetail detail = new FNA_FeeApplyDetail();
        detail.Client = client;
        detail.AccountTitle = AccountTitle;
        detail.BeginMonth = month;
        detail.EndMonth = month;
        detail.BeginDate = accountmonth.BeginDate;
        detail.EndDate = accountmonth.EndDate;
        detail.ApplyCost = applycost * (100 - decimal.Parse(tbx_DIPercent.Text)) / 100;
        detail.DICost = applycost * decimal.Parse(tbx_DIPercent.Text) / 100;
        detail.SalesForcast = decimal.Parse(tbx_SalesForcast.Text);
        detail.Remark = tbx_Remark.Text;
        detail.RelateBrands = productbrand.ToString();
        detail.LastWriteOffMonth = int.Parse(ddl_LastWriteOffMonth.SelectedValue);
        detail.Flag = 1;  //未报销
        detail["FeeApplyType"] = "1";
        bll.Items.Add(detail);

        bll.Model.SheetCode = FNA_FeeApplyBLL.GenerateSheetCode(bll.Model.OrganizeCity, bll.Model.AccountMonth);
        int id = bll.Add();
        #endregion

        if (id > 0)
            Response.Redirect("FeeApplyDetail3.aspx?ID=" + id.ToString());
        else
            MessageBox.Show(this, "对不起,赠品费用申请单生成失败!错误码:" + id.ToString());
    }
    private bool SaveGrid()
    {
        #region 获取关联品牌明细
        string relatebrands = "";
        foreach (ListItem item in cbl_Brand.Items)
        {
            if (item.Selected) relatebrands += item.Value + ",";
        }
        if (relatebrands.EndsWith(",")) relatebrands = relatebrands.Substring(0, relatebrands.Length - 1);
        #endregion

        ListTable<FNA_FeeApplyDetail> _details = ViewState["Details"] as ListTable<FNA_FeeApplyDetail>;
        foreach (GridViewRow gr in gv_List.Rows)
        {
            FNA_FeeApplyDetail item = new FNA_FeeApplyDetail();
            item.ID = (int)gv_List.DataKeys[gr.RowIndex]["ID"];
            if (select_Client.SelectValue != "")
            {
                item.Client = int.Parse(select_Client.SelectValue);
                item["RelateLinkMan"] = ddl_LinkMan.SelectedValue;
                item.SalesForcast = decimal.Parse(tbx_SalesForcast.Text);
            }
            item.AccountTitle = int.Parse(((DropDownList)gr.FindControl("ddl_AccountTitle")).SelectedValue);
            if (((TextBox)gr.FindControl("tbx_ApplyCost")).Text.Trim() != "")
                item.ApplyCost = decimal.Parse(((TextBox)gr.FindControl("tbx_ApplyCost")).Text.Trim());
            if (((TextBox)gr.FindControl("tbx_DICost")).Text.Trim() != "")
                item.DICost = decimal.Parse(((TextBox)gr.FindControl("tbx_DICost")).Text.Trim());

            if (item.AccountTitle > 1 && item.ApplyCost != 0)
            {
                #region 获取费用的开始及截止日期
                TextBox tbx_BeginDate = (TextBox)gr.FindControl("tbx_BeginDate");
                TextBox tbx_EndDate = (TextBox)gr.FindControl("tbx_EndDate");

                if (tbx_BeginDate != null && !string.IsNullOrEmpty(tbx_BeginDate.Text))
                {
                    item.BeginDate = DateTime.Parse(tbx_BeginDate.Text);
                    item.BeginMonth = AC_AccountMonthBLL.GetMonthByDate(item.BeginDate);
                }
                else
                {
                    item.BeginDate = _details[item.ID.ToString()].BeginDate;
                    item.BeginMonth = _details[item.ID.ToString()].BeginMonth;
                }

                if (tbx_EndDate != null && !string.IsNullOrEmpty(tbx_EndDate.Text))
                {
                    item.EndDate = DateTime.Parse(tbx_EndDate.Text);
                    item.EndMonth = AC_AccountMonthBLL.GetMonthByDate(item.EndDate);
                }
                else
                {
                    item.EndDate = _details[item.ID.ToString()].EndDate;
                    item.EndMonth = _details[item.ID.ToString()].EndMonth;
                }

                if (item.BeginDate > item.EndDate)
                {
                    MessageBox.Show(this, "费用发生范围的开始时间不能大于截止时间");
                    return false;
                }
                #endregion
                item.LastWriteOffMonth = int.Parse(ddl_LastWriteOffMonth.SelectedValue);
                item.Remark = ((TextBox)gr.FindControl("tbx_Remark")).Text;

                if (item.Remark == "")
                {
                    MessageBox.Show(this, "费用说明必填");
                    return false;
                }

                if (TreeTableBLL.GetChild("MCS_PUB.dbo.AC_AccountTitle", "ID", "SuperID", item.AccountTitle).Rows.Count > 0)
                {
                    MessageBox.Show(this, "费用科目必须选择最底级会计科目!" + ((DropDownList)gr.FindControl("ddl_AccountTitle")).SelectedItem.Text);
                    return false;
                }
                item.Flag = 1;      //未报销

                item.RelateBrands = relatebrands;
                _details.Update(item);
            }
            else
            {
                _details.Remove(item);
            }
        }

        return true;
    }