protected void bt_AddDetail_Click(object sender, EventArgs e)
    {
        ListTable<CM_ContractDetail> _details = ViewState["Details"] as ListTable<CM_ContractDetail>;
        DateTime begindate = new DateTime();
        DateTime enddate = new DateTime();
        TextBox tbx_BeginDate = pl_detail.FindControl("CM_Contract_BeginDate") == null ? null : (TextBox)pl_detail.FindControl("CM_Contract_BeginDate");
        TextBox tbx_EndDate = pl_detail.FindControl("CM_Contract_EndDate") == null ? null : (TextBox)pl_detail.FindControl("CM_Contract_EndDate");
        if (tbx_BeginDate != null && tbx_EndDate != null)
        {
            DateTime.TryParse(tbx_BeginDate.Text, out begindate);
            DateTime.TryParse(tbx_EndDate.Text, out enddate);
            if (enddate <= begindate)
            {
                MessageBox.Show(this, "合同终止日期不能小于起始日期。");
                return;
            }
        }

        if (ddl_PayMode.SelectedValue == "0")
        {
            MessageBox.Show(this, "付款周期必选!");
            return;
        }

        if (ddl_BearMode.SelectedValue == "2" && ddl_PayMode.SelectedValue == "1")
        {
            MessageBox.Show(this, "付款周期为每月的不支付预提!");
            return;
        }
        decimal displaycount = 0;
        if (!decimal.TryParse(txt_count.Text.Trim(), out displaycount))
        {
            MessageBox.Show(this, "请正确填写数量!");
            return;
        }
        CM_ContractDetail item;
        if (ViewState["Selected"] == null)
        {
            if (ddl_AccountTitle.SelectedValue != "220" && ddl_AccountTitle.SelectedValue != "224")
            {
                IList<CM_ContractDetail> _list = (_details.GetListItem()).Where(p => p.AccountTitle == int.Parse(ddl_AccountTitle.SelectedValue)).ToList();
                //新增科目
                if (_details.GetListItem().Where(p => p.AccountTitle == int.Parse(ddl_AccountTitle.SelectedValue)).Count() > 0)
                {
                    MessageBox.Show(this, "该科目已添加!");
                    return;
                }
            }
            item = new CM_ContractDetail();
            ViewState["MAXID"] = ((int)ViewState["MAXID"]) + 1;
            item.ID = (int)ViewState["MAXID"];
            item.AccountTitle = int.Parse(ddl_AccountTitle.SelectedValue);
            if (TreeTableBLL.GetChild("MCS_PUB.dbo.AC_AccountTitle", "ID", "SuperID", item.AccountTitle).Rows.Count > 0)
            {
                MessageBox.Show(this, "费用科目必须选择最底级会计科目!" + ddl_AccountTitle.SelectedItem.Text);
                return;
            }
        }
        else
        {//修改科目

            item = _details[ViewState["Selected"].ToString()];
        }
        CM_Contract _m = new CM_Contract();
        pl_detail.GetData(_m);

        item.BearMode = int.Parse(ddl_BearMode.SelectedValue);
        item.FeeCycle = GetContractcycle();
        item.Amount = decimal.Parse(tbx_Amount.Text);
        item.BearPercent = decimal.Parse(tbx_BearPercent.Text);
        item.ApplyLimit = decimal.Parse(tbx_ApplyLimit.Text);
        item["DiaplayCount"] = txt_count.Text.Trim();
        item["ISCA"] = ddl_YesNO.SelectedValue;
        if (item.Amount == 0 || item.BearPercent == 0 || item.ApplyLimit == 0)
        {
            MessageBox.Show(this, "对不起,合同总额(元),每次付款金额(元),占月目标销售额比不能为0!");
            return;
        }
        item.PayMode = int.Parse(ddl_PayMode.SelectedValue);
        item.Remark = tbx_Remark.Text;

        #region 获取已选择关联的品牌
        if (cbl_Brand.Visible)
        {
            if (cbl_Brand.SelectedIndex < 0)
            {
                MessageBox.Show(this, "对不起,请选择该费用关联的产品品牌!");
                return;
            }

            item["RelateBrand"] = "";
            foreach (ListItem i in cbl_Brand.Items)
            {
                if (i.Selected) item["RelateBrand"] += i.Value + ",";
            }
        }
        #endregion

        if (ViewState["Selected"] == null)
            _details.Add(item);
        else
            _details.Update(item);

        gv_Detail.SelectedIndex = -1;
        BindGrid();

        tbx_Amount.Text = "0";
        tbx_BearPercent.Text = "100";
        tbx_ApplyLimit.Text = "0";
        tbx_Remark.Text = "";
        bt_AddDetail.Text = "新增";
        ViewState["Selected"] = null;
    }
    protected void bt_OK_Click(object sender, EventArgs e)
    {
        CM_ContractBLL _bll = null;

        #region 判断合同编码是否重复
        //合同编码的获取
        TextBox tbx_ContractCode = pl_detail.FindControl("CM_Contract_ContractCode") == null ? null : (TextBox)pl_detail.FindControl("CM_Contract_ContractCode");
        if ((int)ViewState["ContractID"] == 0)
        {
            _bll = new CM_ContractBLL();

            if (tbx_ContractCode != null && tbx_ContractCode.Text != "" && CM_ContractBLL.GetModelList("ContractCode='" + tbx_ContractCode.Text.Trim() + "'").Count > 0)
            {
                MessageBox.Show(this, "对不起,合同编码" + tbx_ContractCode.Text.Trim() + "数据库已存在。");
                return;
            }
        }
        else
        {
            _bll = new CM_ContractBLL((int)ViewState["ContractID"]);
            if (tbx_ContractCode != null && tbx_ContractCode.Text != "" && CM_ContractBLL.GetModelList("ContractCode='" + tbx_ContractCode.Text.Trim() + "' AND ID !=" + _bll.Model.ID.ToString()).Count > 0)
            {
                MessageBox.Show(this, "对不起,合同编码" + tbx_ContractCode.Text.Trim() + "数据库已存在。");
                return;
            }
        }
        #endregion

        pl_detail.GetData(_bll.Model);
        if (((int)ViewState["Classify"] == 2 || (int)ViewState["Classify"] == 3) && (int)ViewState["ContractID"] == 0)
        {
            AC_AccountMonth minbegainmonth = new AC_AccountMonthBLL(AC_AccountMonthBLL.GetCurrentMonth() - 1).Model;
            if (_bll.Model.BeginDate < minbegainmonth.BeginDate)
            {
                MessageBox.Show(this, "对不起,新增协议的合作日期最小值为" + minbegainmonth.BeginDate.ToString("yyyy-MM-dd") + "。");
                return;
            }
        }

        if ((int)ViewState["Classify"] == 2 || (int)ViewState["Classify"] == 3)
        {

            IList<CM_Contract> _listcontract = CM_ContractBLL.GetModelList("ID!=" + ViewState["ContractID"].ToString() + " AND State IN(1,2,3,9) AND Classify=" + ViewState["Classify"].ToString() + " AND Client=" + ViewState["ClientID"].ToString() + " Order By EndDate DESC");
            if (_listcontract.Count > 0)
            {
                AC_AccountMonth month = new AC_AccountMonthBLL(AC_AccountMonthBLL.GetMonthByDate(_listcontract[0].EndDate)).Model;
                AC_AccountMonth bemonth = new AC_AccountMonthBLL(AC_AccountMonthBLL.GetMonthByDate(_listcontract[0].BeginDate)).Model;
                if (month == null)
                {
                     MessageBox.Show(this, "对不起,新增协议的合作日期与原有协议重复");
                    return;
                }
                if (_bll.Model.BeginDate <= month.EndDate && _bll.Model.EndDate >= bemonth.BeginDate)
                {
                    MessageBox.Show(this, "对不起,新增协议的合作日期与原有协议重复,请重新确认!建议的开始日期为" + new AC_AccountMonthBLL(month.ID + 1).Model.BeginDate.ToString("yyyy-MM-dd"));
                    return;
                }
            }
        }
        //导购工资
        #region 导购工资单独判断 2014-05-07 Jace
        if ((int)ViewState["Classify"] == 3)
        {
            //A、若开始日期范围在过去的最新一个会计月且单月管理费用已随工资流程生成,则该导购协议无法进行保存,并由系统提示:“本协议开始日期需重新填写,导购工资已生成过该笔费用”,若开始日期包含过去的最新一个会计月,但工资流程中并未产生该笔费用,则可以进行保存。
            int month = AC_AccountMonthBLL.GetMonthByDate(_bll.Model.BeginDate);
            int applyedmonth = _bll.CheckPMFeeApplyLastMonth(int.Parse(ViewState["ClientID"].ToString()));
            CM_ClientBLL cm = new CM_ClientBLL(int.Parse(ViewState["ClientID"].ToString()));
            if (month <= applyedmonth)
            {
                MessageBox.Show(this, "本协议开始日期需重新填写,导购工资已生成过该笔费用(最大可提前至" + new AC_AccountMonthBLL(applyedmonth + 1).Model.BeginDate + ")!");
                return;
            }
            //C、导购协议合同周期最多不超过2年。
            if (_bll.Model.BeginDate.AddYears(2) < _bll.Model.EndDate)
            {
                MessageBox.Show(this, "导购协议合同周期最多不超过2年!");
                return;
            }
            //B、导购人数录入的数量 不得超过当时申请时门店实际关联的导购人数,但可以少于门店实际人数,最小的基数为1。
            //若门店没有关联导购员或业务员,该门店不得添加导购费用协议,系统提示:“门店没有关联导购员或业务员,请关联后再做申请”。
            int conpmcount = 0, actpmcount = 0;
            int.TryParse(_bll.Model["PromotorCount"],out conpmcount);
            actpmcount = PM_PromotorInRetailerBLL.GetModelList("Client=" + ViewState["ClientID"].ToString()).Count(p => (new PM_PromotorBLL(p.Promotor).Model.Dimission == 1 || new PM_PromotorBLL(p.Promotor).Model.EndWorkDate < new AC_AccountMonthBLL(month).Model.BeginDate));
            if (actpmcount > 0)
            {
                if (actpmcount < conpmcount)
                {
                    MessageBox.Show(this, "导购人数录入的数量不得超过当时申请时门店实际关联的导购人数!");
                    return;
                }
            }
            else
            {
                MessageBox.Show(this, "门店没有关联导购员或业务员,请关联后再做申请!");
                return;
            }

            //该门店为LKA或NKA门店,但KA系统没有填写,同样不得添加导购费用协议,系统提示:“门店为KA店,KA系统没有填写,需填写后再做申请”。
            if (cm.Model["RTChannel"] == "1" || cm.Model["RTChannel"] == "2")
            {
                if (cm.Model["VestKA"] == "" || cm.Model["VestKA"] == "0")
                {
                    MessageBox.Show(this, "门店为KA店,KA系统没有填写,需填写后再做申请!");
                    return;
                }
            }
            //门店为非LKA或NKA门店,但KA系统有填写内容,不得添加导购费用协议,系统提示“门店为非KA店,但KA系统错填写内容,请修改后再做申请”。
            else if (cm.Model["VestKA"] != "" && cm.Model["VestKA"] != "0")
            {
                MessageBox.Show(this, "门店为非KA店,但KA系统错填写内容,请修改后再做申请!");
                return;
            }

        #endregion

        }
        if (ViewState["ClientID"] != null && (int)ViewState["Classify"] == 2)
        {
            IList<PM_Promotor> pmlist = PM_PromotorBLL.GetModelList("EXISTS (SELECT 1 FROM MCS_Promotor.dbo.PM_PromotorInRetailer WHERE PM_PromotorInRetailer.Promotor=PM_Promotor.ID AND Client=" + ViewState["ClientID"].ToString()
                                                                    + ")AND Dimission=2 AND ApproveFlag=1 ORDER BY EndWorkDate DESC");

            if (pmlist.Count > 0 )
            {
                AC_AccountMonth month = new AC_AccountMonthBLL(AC_AccountMonthBLL.GetMonthByDate(pmlist[0].EndWorkDate)).Model;
                if (month!=null&&_bll.Model.BeginDate <= month.EndDate)
                {
                    MessageBox.Show(this, "对不起,该开始日期期间为导购店,请重新确认!建议的开始日期为" + new AC_AccountMonthBLL(month.ID + 1).Model.BeginDate.ToString("yyyy-MM-dd"));
                    return;
                }

            }

        }

        ListTable<CM_ContractDetail> _details = ViewState["Details"] as ListTable<CM_ContractDetail>;

        int cycle = GetContractcycle();
        #region 判断必填字段
        //if (_bll.Model.BeginDate < DateTime.Today)
        //{
        //    MessageBox.Show(this, "对不起,合同起始日期不能小于今天!");
        //    return;
        //}
        if (_bll.Model.EndDate <= _bll.Model.BeginDate)
        {
            MessageBox.Show(this, "对不起,合同起始日期不能大于截止日期!");
            return;
        }

        if (_bll.Model.EndDate != _bll.Model.BeginDate.AddMonths(cycle).AddDays(-1))
        {
            MessageBox.Show(this, "提醒,合同截止日期与开始日期不足月匹配,请确认输入是否正确!建议的截止日期为" +
               _bll.Model.BeginDate.AddMonths(cycle).AddDays(-1).ToString("yyyy-MM-dd"));
            return;
        }

        if (_bll.Model.Classify==1 && (_bll.Model["IsKA"] == "" || _bll.Model["IsKA"] == "0"))
        {
            MessageBox.Show(this, "对不起请正确选择是否KA费用!");
            return;
        }

        if (_bll.Model.Classify == 2)
        {
            if (_bll.Model["RebateLevel"] == "0")
            {
                MessageBox.Show(this, "对不起请正确选择返利标准!");
                return;
            }
        }

        if (_bll.Model.Classify == 3)
        {
            if (_bll.Model["PromotorCostPayMode"] == "0")
            {
                MessageBox.Show(this, "对不起,请正确选择【导购管理费付款方式】!");
                return;
            }
            #region 增加导购管理费科目明细
            CM_ContractDetail item;
            int accounttitle = ConfigHelper.GetConfigInt("ContractAccountTitle-PromotorCost");
            item = _details.GetListItem().FirstOrDefault(p => p.AccountTitle == accounttitle);
            if (item == null)
            {
                //新增科目
                item = new CM_ContractDetail();
                item.AccountTitle = accounttitle;
                _details.Add(item);
            }
            else
            {
                //修改科目
                _details.Update(item);
            }

            item.ApplyLimit = decimal.Parse(_bll.Model["PromotorCost"]) * int.Parse(_bll.Model["PromotorCount"]);
            item.Amount = item.ApplyLimit * cycle;
            item.FeeCycle = cycle;
            item.BearPercent = 100 - decimal.Parse(_bll.Model["PromotorCostRate"]);
            item.PayMode = int.Parse(_bll.Model["PromotorCostPayMode"]);
            item.Remark = "导购管理费";
            #endregion
        }
        #endregion

        if ((int)ViewState["ContractID"] == 0)
        {

            _bll.Model.State = 1;
            _bll.Model.ApproveFlag = 2;
            _bll.Model.InsertStaff = (int)Session["UserID"];
            _bll.Model.Client = int.Parse(ViewState["ClientID"].ToString());
            CM_ClientBLL _cm = new CM_ClientBLL(_bll.Model.Client);
            //导购店添加返利协议
            if (_cm.Model["RTClassify"] == "3" && (int)ViewState["Classify"] == 2)
            {
                MessageBox.Show(this, _cm.CheckRealClassifyShowMessage(1));
                return;
            }
            _bll.Items = _details.GetListItem();

            ViewState["ContractID"] = _bll.Add();
        }
        else
        {
            _bll.Model.UpdateTime = DateTime.Now;
            _bll.Model.UpdateStaff = (int)Session["UserID"];
            _bll.Update();

            #region 修改明细
            _bll.Items = _details.GetListItem(ItemState.Added);
            _bll.AddDetail();

            foreach (CM_ContractDetail _deleted in _details.GetListItem(ItemState.Deleted))
            {
                _bll.DeleteDetail(_deleted.ID);
            }

            foreach (CM_ContractDetail d in _details.GetListItem())
            {
                if (d.PayMode == 20)
                {
                    //一次性支付
                    if (d.ApplyLimit != d.Amount)
                    {
                        d.ApplyLimit = d.Amount;
                        _details.Update(d);
                    }
                }
                else
                {
                    //非一次性支付
                    if (d.ApplyLimit != 0 && d.Amount / d.ApplyLimit != cycle)
                    {
                        d.Amount = d.ApplyLimit * cycle;
                        _details.Update(d);
                    }
                }
            }
            _bll.Items = _details.GetListItem(ItemState.Modified);

            _bll.UpdateDetail();

            #endregion
        }

        if (sender != null)
        {
            if (Request.QueryString["Decision"] != "" && Request.QueryString["Decision"] == "Y")
                MessageBox.Show(this, "合同编码保存成功!");
            else
                MessageBox.ShowAndRedirect(this, "保存零售商合同详细信息成功!", "RetailerContractDetail.aspx?ContractID=" + ViewState["ContractID"].ToString());
        }
        else
            ViewState["SaveResult"] = true;
    }
    protected void bt_AddDetail_Click(object sender, EventArgs e)
    {
        ListTable<CM_ContractDetail> _details = ViewState["Details"] as ListTable<CM_ContractDetail>;

        DateTime begindate = new DateTime();
        DateTime enddate = new DateTime();
        TextBox tbx_BeginDate = pl_detail.FindControl("CM_Contract_BeginDate") == null ? null : (TextBox)pl_detail.FindControl("CM_Contract_BeginDate");
        TextBox tbx_EndDate = pl_detail.FindControl("CM_Contract_EndDate") == null ? null : (TextBox)pl_detail.FindControl("CM_Contract_EndDate");
        if (tbx_BeginDate != null && tbx_EndDate != null)
        {
            DateTime.TryParse(tbx_BeginDate.Text, out begindate);
            DateTime.TryParse(tbx_EndDate.Text, out enddate);
            if (enddate < begindate)
            {
                MessageBox.Show(this, "协议终止日期不能小于起始日期。");
                return;
            }
        }

        if (ddl_PayMode.SelectedValue == "0")
        {
            MessageBox.Show(this, "付款周期必选!");
            return;
        }

        CM_ContractDetail item;
        if (ViewState["Selected"] == null)
        {
            //新增科目
            if (_details.Contains(ddl_AccountTitle.SelectedValue))
            {
                MessageBox.Show(this, "该科目已添加!");
                return;
            }

            item = new CM_ContractDetail();
            item.AccountTitle = int.Parse(ddl_AccountTitle.SelectedValue);
            if (TreeTableBLL.GetChild("MCS_PUB.dbo.AC_AccountTitle", "ID", "SuperID", item.AccountTitle).Rows.Count > 0)
            {
                MessageBox.Show(this, "费用科目必须选择最底级会计科目!" + ddl_AccountTitle.SelectedItem.Text);
                return;
            }
        }
        else
        {//修改科目
            if (!_details.Contains(ddl_AccountTitle.SelectedValue))
            {
                MessageBox.Show(this, "要修改的项目不存在!");
                return;
            }
            item = _details[ViewState["Selected"].ToString()];
        }
        item.ApplyLimit = decimal.Parse(tbx_ApplyLimit.Text);
        if (item.ApplyLimit == 0)
        {
            MessageBox.Show(this, "对不起,月费用金额不能为0!");
            return;
        }
        item.PayMode = int.Parse(ddl_PayMode.SelectedValue);

        if (ViewState["Selected"] == null)
            _details.Add(item);
        else
            _details.Update(item);

        BindGrid();

        tbx_ApplyLimit.Text = "0";
        bt_AddDetail.Text = "新增";
        ViewState["Selected"] = null;
    }