protected void bt_AddPromotor_Click(object sender, EventArgs e)
    {
        //判断门店返利协议是否已过期
        bool   flag              = true;
        string condition         = " Client=" + ViewState["ClientID"].ToString() + "  AND Classify=2 ";
        IList <CM_Contract> list = CM_ContractBLL.GetModelList(condition);

        foreach (CM_Contract contract in list)
        {
            int currentMonth = AC_AccountMonthBLL.GetCurrentMonth();
            int endMonth     = AC_AccountMonthBLL.GetMonthByDate(contract.EndDate);

            if (contract.State == 3 || contract.State == 9 && endMonth >= currentMonth)
            {
                flag = false;
                break;
            }
        }
        if (!flag)
        {
            MessageBox.Show(this, "当前门店存在返利协议费用");
            return;
        }

        PM_PromotorInRetailerBLL bll = new PM_PromotorInRetailerBLL();

        bll.Model.Client   = int.Parse(ViewState["ClientID"].ToString());
        bll.Model.Promotor = int.Parse(ddl_Promotor.SelectedValue.ToString());
        if (bll.Model.Promotor <= 0)
        {
            MessageBox.Show(this, "导购员未选择,请选择需要添加的导购员!");
            return;
        }
        if (bll._GetModelList(" Promotor=" + bll.Model.Promotor + " and  Client=" + bll.Model.Client).Count > 0)
        {
            MessageBox.Show(this, "该导购员那已经存在!");
            return;
        }
        else
        {
            CM_ClientBLL _cm = new CM_ClientBLL(bll.Model.Client);
            //导购店添加返利协议
            if (_cm.Model["RTClassify"] == "2")
            {
                MessageBox.Show(this, _cm.CheckRealClassifyShowMessage(2));
                return;
            }
            bll.Add();
        }
        ddl_Promotor.SelectedValue = "0";
        BindData();
    }
    protected void bt_AddCM_Click(object sender, EventArgs e)
    {
        PM_PromotorInRetailerBLL bll = new PM_PromotorInRetailerBLL();

        bll.Model.Promotor = int.Parse(ViewState["PromotorID"].ToString());
        bll.Model.Client   = int.Parse(ddl_CM.SelectedValue.ToString());
        if (bll.Model.Client <= 0)
        {
            MessageBox.Show(this, "门店未选择,请选择需要添加的门店!");
            return;
        }
        if (PM_PromotorInRetailerBLL.GetModelList(" Promotor=" + bll.Model.Promotor + " and  Client=" + bll.Model.Client).Count > 0)
        {
            MessageBox.Show(this, "该门店已经存在!");
            return;
        }
        else
        {
            //IList<CM_Contract> contracts = CM_ContractBLL.GetModelList("Client= " + bll.Model.Client.ToString() +
            //    " AND GETDATE() BETWEEN BeginDate AND DATEADD(day,1,ISNULL(EndDate,GETDATE())) AND State=3");

            //CM_Contract _c = contracts.FirstOrDefault(p => p.Classify == 3);

            //int _AllowPromotorCount = 0;
            //if (_c != null) int.TryParse(_c["PromotorCount"], out _AllowPromotorCount);

            //if (PM_PromotorInRetailerBLL.GetModelList("Client=" + bll.Model.Client).Count >= _AllowPromotorCount)
            //{
            //    MessageBox.Show(this, "对不起,当前门店最多只允许" + _AllowPromotorCount.ToString() + "个导购入场,请修改门店导购入场协议数!");
            //    return;
            //}

            CM_ClientBLL _cm = new CM_ClientBLL(bll.Model.Client);
            //导购店添加返利协议
            if (_cm.Model["RTClassify"] == "2")
            {
                MessageBox.Show(this, _cm.CheckRealClassifyShowMessage(2));
                return;
            }
            bll.Add();
        }
        ddl_CM.SelectedValue = "0";
        BindData();
    }
    /// <summary>
    /// 新增返利协议
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void bt_AddContract2_Click(object sender, EventArgs e)
    {
        bool flag = true;//允许生生成陈列协议

        string condition = " Client=" + ViewState["ClientID"].ToString();
        IList <PM_PromotorInRetailer> list = PM_PromotorInRetailerBLL.GetModelList(condition);

        for (int i = 0; i < list.Count; i++)
        {
            PM_PromotorBLL PM_PromotorBLL = new PM_PromotorBLL(list[i].Promotor);
            PM_Promotor    promoter       = PM_PromotorBLL.Model;
            int            endMonth       = AC_AccountMonthBLL.GetMonthByDate(promoter.EndWorkDate);
            int            currentMonth   = AC_AccountMonthBLL.GetCurrentMonth();
            //导购在职或导购离职判断离职日期,即使无销量也需生成基本工资
            if (promoter.Dimission == 1 || promoter.Dimission == 2 && endMonth >= currentMonth)//
            {
                flag = false;
                break;
            }
        }
        if (!flag)
        {
            MessageBox.Show(this, "当前门店存在导购或本月需生成导购工资");
            return;
        }

        bt_OK_Click(null, null);
        CM_ClientBLL _cm = new CM_ClientBLL((int)ViewState["ClientID"]);

        if (_cm.Model["Classification"] == "" || _cm.Model["Classification"] == "0")
        {
            MessageBox.Show(this, "请先选择门店归类再新增返利协议!");
            return;
        }
        //导购店添加返利协议
        if (_cm.Model["RTClassify"] == "3")
        {
            MessageBox.Show(this, _cm.CheckRealClassifyShowMessage(1));
            return;
        }
        Response.Redirect("RetailerContractDetail.aspx?ClientID=" + ViewState["ClientID"].ToString() + "&Classify=2");
    }
    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;
    }
    /// <summary>
    /// 新增返利协议
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void bt_AddContract2_Click(object sender, EventArgs e)
    {
        bool flag = true;//允许生生成陈列协议

        string condition = " Client=" + ViewState["ClientID"].ToString();
        IList<PM_PromotorInRetailer> list = PM_PromotorInRetailerBLL.GetModelList(condition);
        for (int i = 0; i < list.Count; i++)
        {
            PM_PromotorBLL PM_PromotorBLL = new PM_PromotorBLL(list[i].Promotor);
            PM_Promotor promoter = PM_PromotorBLL.Model;
            int endMonth = AC_AccountMonthBLL.GetMonthByDate(promoter.EndWorkDate);
            int currentMonth = AC_AccountMonthBLL.GetCurrentMonth();
            //导购在职或导购离职判断离职日期,即使无销量也需生成基本工资
            if (promoter.Dimission == 1 || promoter.Dimission == 2 && endMonth >= currentMonth)//
            {
                flag = false;
                break;
            }
        }
        if (!flag)
        {
            MessageBox.Show(this, "当前门店存在导购或本月需生成导购工资");
            return;
        }

        bt_OK_Click(null, null);
        CM_ClientBLL _cm = new CM_ClientBLL((int)ViewState["ClientID"]);
        if (_cm.Model["Classification"] == "" || _cm.Model["Classification"] == "0")
        {
            MessageBox.Show(this, "请先选择门店归类再新增返利协议!");
            return;
        }
        //导购店添加返利协议
        if (_cm.Model["RTClassify"] == "3")
        {
            MessageBox.Show(this, _cm.CheckRealClassifyShowMessage(1));
            return;
        }
        Response.Redirect("RetailerContractDetail.aspx?ClientID=" + ViewState["ClientID"].ToString() + "&Classify=2");
    }
    protected void bt_AddPromotor_Click(object sender, EventArgs e)
    {
        //判断门店返利协议是否已过期
        bool flag = true;
        string condition = " Client=" + ViewState["ClientID"].ToString() + "  AND Classify=2 ";
        IList<CM_Contract> list = CM_ContractBLL.GetModelList(condition);
        foreach (CM_Contract contract in list)
        {
            int currentMonth = AC_AccountMonthBLL.GetCurrentMonth();
            int endMonth = AC_AccountMonthBLL.GetMonthByDate(contract.EndDate);

            if (contract.State == 3 || contract.State == 9 && endMonth >= currentMonth)
            {
                flag = false;
                break;
            }
        }
        if (!flag)
        {
            MessageBox.Show(this, "当前门店存在返利协议费用");
            return;
        }

        PM_PromotorInRetailerBLL bll = new PM_PromotorInRetailerBLL();
        bll.Model.Client = int.Parse(ViewState["ClientID"].ToString());
        bll.Model.Promotor = int.Parse(ddl_Promotor.SelectedValue.ToString());
        if (bll.Model.Promotor <= 0)
        {
            MessageBox.Show(this, "导购员未选择,请选择需要添加的导购员!");
            return;
        }
        if (bll._GetModelList(" Promotor=" + bll.Model.Promotor + " and  Client=" + bll.Model.Client).Count > 0)
        {
            MessageBox.Show(this, "该导购员那已经存在!");
            return;
        }
        else
        {
            CM_ClientBLL _cm = new CM_ClientBLL(bll.Model.Client);
            //导购店添加返利协议
            if (_cm.Model["RTClassify"] == "2")
            {
                MessageBox.Show(this, _cm.CheckRealClassifyShowMessage(2));
                return;
            }
            bll.Add();
        }
        ddl_Promotor.SelectedValue = "0";
        BindData();
    }
    protected void bt_AddCM_Click(object sender, EventArgs e)
    {
        PM_PromotorInRetailerBLL bll = new PM_PromotorInRetailerBLL();

        bll.Model.Promotor = int.Parse(ViewState["PromotorID"].ToString());
        bll.Model.Client = int.Parse(ddl_CM.SelectedValue.ToString());
        if (bll.Model.Client <= 0)
        {
            MessageBox.Show(this, "门店未选择,请选择需要添加的门店!");
            return;
        }
        if (PM_PromotorInRetailerBLL.GetModelList(" Promotor=" + bll.Model.Promotor + " and  Client=" + bll.Model.Client).Count > 0)
        {
            MessageBox.Show(this, "该门店已经存在!");
            return;
        }
        else
        {
            //IList<CM_Contract> contracts = CM_ContractBLL.GetModelList("Client= " + bll.Model.Client.ToString() +
            //    " AND GETDATE() BETWEEN BeginDate AND DATEADD(day,1,ISNULL(EndDate,GETDATE())) AND State=3");

            //CM_Contract _c = contracts.FirstOrDefault(p => p.Classify == 3);

            //int _AllowPromotorCount = 0;
            //if (_c != null) int.TryParse(_c["PromotorCount"], out _AllowPromotorCount);

            //if (PM_PromotorInRetailerBLL.GetModelList("Client=" + bll.Model.Client).Count >= _AllowPromotorCount)
            //{
            //    MessageBox.Show(this, "对不起,当前门店最多只允许" + _AllowPromotorCount.ToString() + "个导购入场,请修改门店导购入场协议数!");
            //    return;
            //}

            CM_ClientBLL _cm = new CM_ClientBLL(bll.Model.Client);
            //导购店添加返利协议
            if (_cm.Model["RTClassify"] == "2")
            {
                MessageBox.Show(this, _cm.CheckRealClassifyShowMessage(2));
                return;
            }
            bll.Add();
        }
        ddl_CM.SelectedValue = "0";
        BindData();
    }