protected void bt_RevocationApply_Click(object sender, EventArgs e)
    {
        CM_ClientBLL bll = new CM_ClientBLL((int)ViewState["ClientID"]);

        if (PM_PromotorInRetailerBLL.GetModelList("Client=" + bll.Model.ID.ToString() + " AND EXISTS(SELECT 1 FROM MCS_Promotor.dbo.PM_Promotor WHERE PM_Promotor.ID=PM_PromotorInRetailer.Promotor AND Dimission=1 AND ApproveFlag=1)").Count > 0)
        {
            MessageBox.Show(this, "该门店还有关联的导购,请转移或解除与该门店的关系!");
            return;
        }

        NameValueCollection dataobjects = new NameValueCollection();

        dataobjects.Add("ID", ViewState["ClientID"].ToString());
        dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString());
        dataobjects.Add("ClientName", bll.Model.FullName.ToString());
        dataobjects.Add("Channel", bll.Model["RTChannel"]);
        dataobjects.Add("CloseTime", DateTime.Now.ToShortDateString());
        dataobjects.Add("Remark", "门店终止合作");
        dataobjects.Add("IsKeyClient", bll.Model["IsKeyClient"].ToString());


        int TaskID = EWF_TaskBLL.NewTask("Revocation_Retailer", (int)Session["UserID"], "撤销门店,名称:" + bll.Model.FullName, "~/SubModule/CM/RT/RetailerDetail.aspx?ClientID=" + ViewState["ClientID"].ToString(), dataobjects);

        if (TaskID > 0)
        {
            bll.Model["TaskID"] = TaskID.ToString();
            bll.Model["State"]  = "2";
            bll.Update();
        }

        Response.Redirect("~/SubModule/EWF/Apply.aspx?TaskID=" + TaskID.ToString());
    }
 protected void bt_Add_Click(object sender, EventArgs e)
 {
     #region 判断当前导购是否有所在工作的门店
     if (PM_PromotorInRetailerBLL.GetModelList("Promotor=" + ViewState["PromotorID"].ToString()).Count == 0)
     {
         MessageBox.ShowAndRedirect(this, "请设置该导购员所在的门店!", "PM_PromotorDetail.aspx");
         return;
     }
     #endregion
     ViewState["PromotorSalaryID"] = 0;
     BindData(null);
 }
    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_AddContract3_Click(object sender, EventArgs e)
    {
        bt_OK_Click(null, null);
        CM_ClientBLL _cm = new CM_ClientBLL((int)ViewState["ClientID"]);
        IList <PM_PromotorInRetailer> pms = PM_PromotorInRetailerBLL.GetModelList("Client=" + ViewState["ClientID"] + "AND EXISTS (SELECT 1 FROM MCS_Promotor.dbo.PM_Promotor " +
                                                                                  " WHERE Dimission=1 AND ApproveFlag=1 AND PM_Promotor.ID=PM_PromotorInRetailer.Promotor)");

        if (_cm.Model.ClientManager == 0 || pms.Count == 0)
        {
            MessageBox.Show(this, "门店无负责人或者无导购不能新增导购协议!");
            return;
        }
        Response.Redirect("RetailerContractDetail.aspx?ClientID=" + ViewState["ClientID"].ToString() + "&Classify=3");
    }
    protected string PromotorInClient(int promotor)
    {
        string clientname = "";
        IList <PM_PromotorInRetailer> lists = PM_PromotorInRetailerBLL.GetModelList("Promotor=" + promotor.ToString());

        foreach (PM_PromotorInRetailer item in lists)
        {
            CM_Client c = new CM_ClientBLL(item.Client).Model;
            if (c != null)
            {
                clientname += "<a href='../CM/RT/RetailerDetail.aspx?ClientID=" + c.ID.ToString() + "' target='_blank' class='listViewTdLinkS1'>"
                              + c.FullName + "</a><br/>";
            }
        }
        return(clientname);
    }
    protected void gv_list_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        IList <PM_PromotorInRetailer> _list = PM_PromotorInRetailerBLL.GetModelList("Promotor=" + ViewState["PromotorID"].ToString());

        if (_list.Count > 1)
        {
            int id = int.Parse(gv_list.DataKeys[e.RowIndex]["PM_PromotorInRetailer_ID"].ToString());
            PM_PromotorInRetailerBLL bll = new PM_PromotorInRetailerBLL(id);
            bll.Delete();
            BindData();
        }
        else
        {
            MessageBox.Show(this, "请确保将导购关联新的门店再删除!");
            return;
        }
    }
    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_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 Page_Load(object sender, EventArgs e)
    {
        ddl_BasePayMode        = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_BasePayMode");
        ddl_BasePaySubsidyMode = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_BasePaySubsidyMode");
        ddl_MinimumWageMode    = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_MinimumWageMode");
        ddl_InsuranceMode      = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_InsuranceMode");
        ddl_SeniorityPayMode   = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_SeniorityPayMode");
        ddl_SalesType          = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_SalesType");

        ddl_BankType = DV_pm.FindControl("PM_Promotor_BankType") == null ? null : (DropDownList)UC_DetailView1.FindControl("PM_Promotor_BankType");
        txt_BankName = DV_pm.FindControl("PM_Promotor_BankName") == null ? null : (TextBox)UC_DetailView1.FindControl("PM_Promotor_BankName");


        if (ddl_BankType != null)
        {
            ddl_BankType.AutoPostBack          = true;
            ddl_BankType.SelectedIndexChanged += new EventHandler(ddl_BankType_SelectedIndexChanged);
        }

        ddl_BasePaySubsidyMode.AutoPostBack          = true;
        ddl_BasePaySubsidyMode.SelectedIndexChanged += new EventHandler(ddl_BasePaySubsidyMode_SelectedIndexChanged);

        ddl_MinimumWageMode.AutoPostBack          = true;
        ddl_MinimumWageMode.SelectedIndexChanged += new EventHandler(ddl_MinimumWageMode_SelectedIndexChanged);

        ddl_InsuranceMode.AutoPostBack          = true;
        ddl_InsuranceMode.SelectedIndexChanged += new EventHandler(ddl_InsuranceMode_SelectedIndexChanged);


        txt_AvgSales       = (TextBox)UC_DetailView1.FindControl("PM_PromotorSalary_AvgSales");
        txt_BaseFeeRate    = (TextBox)UC_DetailView1.FindControl("PM_PromotorSalary_BaseFeeRate");
        txt_FloatingTarget = (TextBox)UC_DetailView1.FindControl("PM_PromotorSalary_FloatingTarget");



        Page.ClientScript.RegisterClientScriptInclude("meizzDate", Page.ResolveClientUrl("~/App_Themes/basic/meizzDate.js"));
        if (!IsPostBack)
        {
            txt_AvgSales.Enabled           = false;
            txt_BaseFeeRate.Enabled        = false;
            txt_FloatingTarget.Enabled     = false;
            ddl_SalesType.Enabled          = false;
            ddl_BasePaySubsidyMode.Enabled = false;
            ddl_MinimumWageMode.Enabled    = false;

            txt_FloatingTarget.Text = "0";
            txt_AvgSales.Text       = "0";
            txt_BaseFeeRate.Text    = "0";

            ViewState["PromotorID"] = Request.QueryString["PromotorID"] == null ? 0 : int.Parse(Request.QueryString["PromotorID"]);

            //新增薪资标准
            #region 判断当前导购是否有所在工作的门店
            if (PM_PromotorInRetailerBLL.GetModelList("Promotor=" + ViewState["PromotorID"].ToString()).Count == 0)
            {
                MessageBox.ShowAndRedirect(this, "请设置该导购员所在的门店!", "PM_PromotorDetail.aspx?PromotorID=" + ViewState["PromotorID"].ToString());
                return;
            }
            #endregion

            PM_Promotor m = new PM_PromotorBLL((int)ViewState["PromotorID"]).Model;
            if (m != null)
            {
                DV_pm.BindData(m);
            }
            else
            {
                MessageBox.ShowAndClose(this, "导购员信息读取失败!");
                return;
            }



            DropDownList ddl_Classfiy      = DV_pm.FindControl("PM_Promotor_Classfiy") as DropDownList;
            TextBox      tbx_BeginWorkDate = DV_pm.FindControl("PM_Promotor_BeginWorkDate") as TextBox;
            int          classfiy          = 0;
            int.TryParse(m["Classfiy"], out classfiy);
            if (classfiy == 0)
            {
                MessageBox.ShowAndClose(this, "导购员类别读取失败!");
                return;
            }
            if (m["State"] == "2")
            {
                MessageBox.ShowAndClose(this, "导购有流程正在审批,无法再发起流程!");
                return;
            }
            else if (classfiy == 1 || classfiy == 2)
            {
                ddl_Classfiy.Items.FindByValue("1").Enabled = false;
                ddl_Classfiy.Items.FindByValue("2").Enabled = false;
            }
            else
            {
                ddl_Classfiy.Items.FindByValue("6").Enabled = false;
            }
            tbx_BeginWorkDate.Text = "";
            BindData(classfiy);
        }
    }
    protected void bt_Submit_Click(object sender, EventArgs e)
    {
        if ((int)ViewState["PromotorSalaryID"] == 0)
        {
            MessageBox.Show(this, "对不起,请您先保存后在发起申请");
            return;
        }
        PM_PromotorSalaryBLL bll = new PM_PromotorSalaryBLL((int)ViewState["PromotorSalaryID"]);
        PM_Promotor          p   = new PM_PromotorBLL((int)ViewState["PromotorID"]).Model;

        #region 判断是否KA店导购
        bool IsKAChannel = false;  //是否KA店导购

        if (p["Classify"] != "2")  //非流导
        {
            IList <PM_PromotorInRetailer> retailers = PM_PromotorInRetailerBLL.GetModelList(" Promotor=" + ViewState["PromotorID"].ToString());
            //判断导购是否在KA店工作
            foreach (PM_PromotorInRetailer item in retailers)
            {
                CM_Client client = new CM_ClientBLL(item.Client).Model;
                if (client["RTChannel"] == "1" || client["RTChannel"] == "2")
                {
                    IsKAChannel = true;
                }
            }
        }
        #endregion

        #region 判断是否超薪酬超准
        bool bSalaryFlag         = false;
        PM_PromotorSalary salary = bll.Model;

        if (salary.BasePaySubsidy >= 1)
        {
            bSalaryFlag = true;                                     //有底薪补贴
        }
        if (salary.MinimumWageMode == 2)
        {
            bSalaryFlag = true;                                //特殊保底
        }
        if (salary.InsuranceMode == 1 && salary.InsuranceSubsidy > 100)
        {
            bSalaryFlag = true;                                                                 //社保补贴大于100元的
        }
        #endregion

        NameValueCollection dataobjects = new NameValueCollection();
        dataobjects.Add("ID", p.ID.ToString());
        dataobjects.Add("PromotorSalaryID", ViewState["PromotorSalaryID"].ToString());
        dataobjects.Add("OrganizeCity", p.OrganizeCity.ToString());
        dataobjects.Add("SalaryFlag", bSalaryFlag ? "2" : "1");      //薪酬标志 1:薪酬标准内 2:薪酬标准外
        dataobjects.Add("StaffName", p.Name.ToString());
        dataobjects.Add("IsKAChannel", IsKAChannel ? "1" : "2");     //是否KA卖场的导购

        int TaskID = EWF_TaskBLL.NewTask("Apply_PromotorSalary", (int)Session["UserID"], "调整导购员薪酬福利申请,姓名:" + p.Name,
                                         "~/SubModule/PM/PM_PromotorSalaryDetail.aspx?ID=" + bll.Model.ID.ToString(), dataobjects);
        if (TaskID > 0)
        {
            bll.Model.ApproveTask = TaskID;
            bll.Model.State       = 2;
            bll.Update();
            // new EWF_TaskBLL(TaskID).Start();        //直接启动流程
        }

        Response.Redirect("~/SubModule/EWF/Apply.aspx?TaskID=" + TaskID.ToString());
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        #region 获取界面控件
        ddl_BasePayMode        = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_BasePayMode");
        ddl_BasePaySubsidyMode = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_BasePaySubsidyMode");
        ddl_MinimumWageMode    = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_MinimumWageMode");
        ddl_InsuranceMode      = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_InsuranceMode");
        ddl_SeniorityPayMode   = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_SeniorityPayMode");
        ddl_SalesType          = (DropDownList)UC_DetailView1.FindControl("PM_PromotorSalary_SalesType");

        ddl_BasePayMode.AutoPostBack          = true;
        ddl_BasePayMode.SelectedIndexChanged += new EventHandler(ddl_BasePayMode_SelectedIndexChanged);

        ddl_BasePaySubsidyMode.AutoPostBack          = true;
        ddl_BasePaySubsidyMode.SelectedIndexChanged += new EventHandler(ddl_BasePaySubsidyMode_SelectedIndexChanged);

        ddl_MinimumWageMode.AutoPostBack          = true;
        ddl_MinimumWageMode.SelectedIndexChanged += new EventHandler(ddl_MinimumWageMode_SelectedIndexChanged);

        ddl_InsuranceMode.AutoPostBack          = true;
        ddl_InsuranceMode.SelectedIndexChanged += new EventHandler(ddl_InsuranceMode_SelectedIndexChanged);

        txt_AvgSales       = (TextBox)UC_DetailView1.FindControl("PM_PromotorSalary_AvgSales");
        txt_BaseFeeRate    = (TextBox)UC_DetailView1.FindControl("PM_PromotorSalary_BaseFeeRate");
        txt_FloatingTarget = (TextBox)UC_DetailView1.FindControl("PM_PromotorSalary_FloatingTarget");

        chk_arrivetarget.Text    = "是否达到过上限";
        chk_arrivetarget.Enabled = false;
        txt_FloatingTarget.Parent.Controls.Add(chk_arrivetarget);
        #endregion
        if (!IsPostBack)
        {
            ViewState["PromotorSalaryID"] = Request.QueryString["ID"] == null ? 0 : int.Parse(Request.QueryString["ID"]);
            ViewState["PromotorID"]       = Request.QueryString["PromotorID"] == null ? 0 : int.Parse(Request.QueryString["PromotorID"]);
            ViewState["AvgSales"]         = 0m; ViewState["BaseFeeRate"] = 0m;
            if ((int)ViewState["PromotorSalaryID"] > 0)
            {
                PM_PromotorSalary m = new PM_PromotorSalaryBLL((int)ViewState["PromotorSalaryID"]).Model;
                if (m != null)
                {
                    BindData(m);
                    bt_Add.Visible = false;
                }
                else
                {
                    Response.Redirect("PM_PromotorDetail.aspx");
                }
            }
            else if ((int)ViewState["PromotorID"] > 0)
            {
                IList <PM_PromotorSalary> lists = PM_PromotorSalaryBLL.GetModelList("Promotor=" + ViewState["PromotorID"].ToString() +
                                                                                    " AND State <= 3  ORDER BY State DESC,ID DESC");
                if (lists.Count == 0)
                {
                    //新增薪资标准
                    #region 判断当前导购是否有所在工作的门店
                    if (PM_PromotorInRetailerBLL.GetModelList("Promotor=" + ViewState["PromotorID"].ToString()).Count == 0)
                    {
                        MessageBox.ShowAndRedirect(this, "请设置该导购员所在的门店!", "PM_PromotorDetail.aspx?PromotorID=" + ViewState["PromotorID"].ToString());
                        return;
                    }
                    #endregion

                    BindData(null);
                    bt_Add.Visible = false;
                }
                else
                {
                    BindData(lists[0]);
                    if (lists.FirstOrDefault(p => p.State < 3) != null)
                    {
                        bt_Add.Visible = false;
                    }
                }
            }
            else
            {
                Response.Redirect("PM_PromotorDetail.aspx");
            }
        }
    }
    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();
    }
    protected void bt_AddApply_Click(object sender, EventArgs e)
    {
        if ((int)ViewState["PromotorID"] == 0)
        {
            MessageBox.Show(this, "对不起,请您先保存后在发起申请");
            return;
        }
        bt_OK_Click(null, null);

        PM_PromotorBLL bll = new PM_PromotorBLL((int)ViewState["PromotorID"]);
        DateTime       birthday;

        if (DateTime.TryParse(bll.Model["Birthday"], out birthday))
        {
            if (DateTime.Now < birthday.AddYears(16) || DateTime.Now > birthday.AddYears(50))
            {
                int year = DateTime.Now.Year - birthday.Year;
                if (birthday.AddYears(year) > DateTime.Now)
                {
                    year++;
                }
                MessageBox.Show(this, "对不起,该导购年龄不符合规则(16~49岁),该人员年龄:" + year);
                return;
            }
        }
        if (PM_PromotorNumberLimitBLL.CheckAllowAdd(bll.Model.OrganizeCity, int.Parse(bll.Model["Classfiy"])) < 0)
        {
            MessageBox.Show(this, "对不起当前城市导购员人数满额,要想继续新增请与人事经理联系");
            return;
        }
        if (bll.Model.BeginWorkDate.AddDays(40) < DateTime.Now)
        {
            MessageBox.Show(this, "对不起,入职时间必须在发起日期前40天之内!");
            return;
        }
        if (bll.Model["IDCode"] == "")
        {
            MessageBox.Show(this, "请录入身份证号!");
            return;
        }
        if (bll.Model["InfoSource"] == "" || bll.Model["InfoSource"] == "0")
        {
            MessageBox.Show(this, "请正确选择导购来源!");
            return;
        }
        if (bll.Model["OldClassify"] == "" || bll.Model["OldClassify"] == "0")
        {
            MessageBox.Show(this, "请正确选择原属品牌!");
            return;
        }
        if (bll.Model["BankType"] == "" || bll.Model["BankType"] == "0")
        {
            MessageBox.Show(this, "请正确选择银行信息");
            return;
        }
        string[]        allowday  = Addr_OrganizeCityParamBLL.GetValueByType(1, 3).Split(new char[] { ',', ',', ';', ';' });
        AC_AccountMonth lastmonth = GetMaxSalaryDate((int)ViewState["PromotorID"], AC_AccountMonthBLL.GetCurrentMonth() - 1);

        if (lastmonth != null && allowday.Contains(DateTime.Now.Day.ToString()) && bll.Model.BeginWorkDate > lastmonth.EndDate)
        {
            MessageBox.Show(this, "该导购在" + lastmonth.Name + "生成过工资,入职日期不能大于" + lastmonth.EndDate.ToString("yyyy-MM-dd"));
            return;
        }

        #region 判断是否KA店导购
        bool IsKAChannel = false;         //是否KA店导购

        if (bll.Model["Classify"] != "2") //非流导
        {
            IList <PM_PromotorInRetailer> retailers = PM_PromotorInRetailerBLL.GetModelList(" Promotor=" + ViewState["PromotorID"].ToString());
            if (retailers.Count == 0)
            {
                MessageBox.Show(this, "对不起,请关联该导购所在的工作门店!");
                return;
            }

            //判断导购是否在KA店工作
            foreach (PM_PromotorInRetailer item in retailers)
            {
                CM_Client client = new CM_ClientBLL(item.Client).Model;
                if (client["RTChannel"] == "1" || client["RTChannel"] == "2")
                {
                    IsKAChannel = true;
                }
            }
        }
        #endregion

        #region 判断是否超薪酬超准
        bool bSalaryFlag = false;   //false : 薪酬标准内 true:超标准
        IList <PM_PromotorSalary> salarylists = PM_PromotorSalaryBLL.GetModelList("Promotor=" + bll.Model.ID.ToString() + " AND State IN(1,3) Order BY State");

        if (salarylists.Count == 0 || salarylists.Count > 0 && (bll.Model["Classfiy"] == "6" && salarylists[0].BasePayMode != 3 || bll.Model["Classfiy"] != "6" && salarylists[0].BasePayMode == 3))
        {
            MessageBox.Show(this, "对不起,尚未为该导购设定薪酬信息,请设定完薪酬信息后,再提交入职申请!");
            return;
        }
        else
        {
            PM_PromotorSalary salary = salarylists[0];
            if (salary.BasePaySubsidy > 0)
            {
                bSalaryFlag = true;                              //有底薪补贴
            }
            if (salary.MinimumWageMode == 2)
            {
                bSalaryFlag = true;                              //特殊保底
            }
            if (salary.InsuranceMode == 1 && salary.InsuranceSubsidy > 100)
            {
                bSalaryFlag = true;                                                                 //社保补贴大于100元的
            }
        }
        #endregion

        int budget = PM_PromotorNumberLimitBLL.CheckOverBudget(bll.Model.OrganizeCity, int.Parse(bll.Model["Classfiy"]));

        NameValueCollection dataobjects = new NameValueCollection();
        dataobjects.Add("ID", ViewState["PromotorID"].ToString());
        dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString());
        dataobjects.Add("SalaryFlag", !bSalaryFlag ? "1" : "2");      //薪酬标志 1:薪酬标准内 2:薪酬标准外
        dataobjects.Add("StaffName", bll.Model.Name.ToString());
        dataobjects.Add("IsKAChannel", IsKAChannel ? "1" : "2");      //是否KA卖场的导购
        dataobjects.Add("IsOverBudget", budget < 0 ? "1" : "2");      //是否超人数预算 1:超 2:未超


        int TaskID = EWF_TaskBLL.NewTask("Add_Promotor", (int)Session["UserID"], "新增导购员流程,姓名:" + bll.Model.Name + "【" + ddl_Classify.SelectedItem.Text.ToString() + "】", "~/SubModule/PM/PM_PromotorDetail.aspx?PromotorID=" + ViewState["PromotorID"].ToString(), dataobjects);
        if (TaskID > 0)
        {
            bll.Submit(TaskID, (int)Session["UserID"]);
        }

        Response.Redirect("~/SubModule/EWF/Apply.aspx?TaskID=" + TaskID.ToString());
    }
 protected void gv_Promotor_RowDeleting(object sender, GridViewDeleteEventArgs e)
 {
     string promotor = gv_Promotor.DataKeys[e.RowIndex]["PM_Promotor_ID"].ToString();
     IList<PM_PromotorInRetailer> _list = PM_PromotorInRetailerBLL.GetModelList("Promotor=" + promotor);
     if (_list.Count > 1)
     {
         int id = int.Parse(gv_Promotor.DataKeys[e.RowIndex]["PM_PromotorInRetailer_ID"].ToString());
         PM_PromotorInRetailerBLL bll = new PM_PromotorInRetailerBLL(id);
         bll.Delete();
         BindData();
     }
     else
     {
         MessageBox.Show(this, "请确保将导购关联新的门店再删除!");
         return;
     }
 }
Exemplo n.º 16
0
    protected void bt_Import_Click(object sender, EventArgs e)
    {
        string ImportInfo = "";

        lb_ErrorInfo.Text = "";

        System.Data.DataTable dtSellIn = null, dtSellOut = null;

        if (Session["DataTable-SellIn"] != null && Session["DataTable-SellOut"] != null)
        {
            dtSellIn  = (System.Data.DataTable)Session["DataTable-SellIn"];
            dtSellOut = (System.Data.DataTable)Session["DataTable-SellOut"];
        }

        #region 获取允许最迟的销量日期
        int             JXCDelayDays = ConfigHelper.GetConfigInt("JXCDelayDays");
        AC_AccountMonth month        = new AC_AccountMonthBLL(AC_AccountMonthBLL.GetMonthByDate(DateTime.Now.AddDays(-JXCDelayDays))).Model;
        DateTime        minday       = month.BeginDate;
        DateTime        maxday       = DateTime.Today < month.EndDate ? DateTime.Today : month.EndDate;
        #endregion

        IList <PDT_Product> productlists = PDT_ProductBLL.GetModelList("Brand IN (SELECT ID FROM dbo.PDT_Brand WHERE IsOpponent='1') AND State=1 AND ApproveFlag=1 ORDER BY ISNULL(SubUnit,999999),Code");

        ImportInfo += "<span style='color: Red'>-------------------------------------------------------------------------</span><br/>";
        ImportInfo += "<span style='color: Red'>----批量导入零售商进货销量----</span><br/>";

        #region 开始导入零售商进货
        foreach (System.Data.DataRow dr in dtSellIn.Rows)
        {
            #region 验证数据
            int       clientid = (int)dr["零售商ID"];
            CM_Client client   = new CM_ClientBLL(clientid).Model;
            if (client == null || client.FullName != (string)dr["零售商名称"])
            {
                ImportInfo += "<span style='color: Red'>序号:" + dr["序号"].ToString() + ",零售商ID与零售商名称不匹配!</span><br/>";
                continue;
            }

            if (dr["归属月份"].ToString() != month.Name)
            {
                ImportInfo += "<span style='color: Red'>序号:" + dr["序号"].ToString() + ",归属月份必须为【" + month.Name + "】</span><br/>";
                continue;
            }
            //DateTime salesdate = (DateTime)dr["进货日期"];
            //if (salesdate < minday || salesdate > maxday)
            //{
            //    ImportInfo += "<span style='color: Red'>序号:" + dr["序号"].ToString() + ",进货日期必须在" + minday.ToString("yyyy-MM-dd") +
            //        "至" + maxday.ToString("yyyy-MM-dd") + "之间!</span><br/>";
            //    continue;
            //}
            #endregion

            #region 组织销量头
            SVM_SalesVolumeBLL      bll      = null;
            IList <SVM_SalesVolume> svmlists = SVM_SalesVolumeBLL.GetModelList("Client=" + clientid.ToString()
                                                                               + " AND Type=2 AND AccountMonth=" + month.ID.ToString() //+ " AND SalesDate='" + salesdate.ToString("yyyy-MM-dd")
                                                                               + " AND MCS_SYS.dbo.UF_Spilt(ExtPropertys,'|',1)='N' ");
            if (svmlists.Count > 0)
            {
                if (svmlists[0].ApproveFlag == 1)
                {
                    ImportInfo += "<span style='color: Red'>序号:" + dr["序号"].ToString() + ",该零售商当月的进货已审核,不可再次导入!</span><br/>";
                    continue;
                }

                bll = new SVM_SalesVolumeBLL(svmlists[0].ID);
                bll.Items.Clear();
            }
            else
            {
                bll = new SVM_SalesVolumeBLL();
                bll.Model.Client        = clientid;
                bll.Model.OrganizeCity  = client.OrganizeCity;
                bll.Model.Supplier      = client.Supplier;
                bll.Model.AccountMonth  = month.ID;
                bll.Model.SalesDate     = maxday;
                bll.Model.Type          = 2;
                bll.Model.ApproveFlag   = 2;
                bll.Model.Flag          = 1;    //成品销售
                bll.Model["SubmitFlag"] = "1";
                bll.Model["IsCXP"]      = "N";
                bll.Model.InsertStaff   = (int)Session["UserID"];
                bll.Model.Remark        = "Excel批量导入";
            }
            #endregion

            #region 读取各产品销量
            IList <SVM_SalesVolume_Detail> details = new List <SVM_SalesVolume_Detail>();
            foreach (PDT_Product product in productlists)
            {
                int quantity = (int)dr["[" + product.ShortName + "]"];
                if (quantity != 0)
                {
                    decimal factoryprice = 0, salesprice = 0;
                    PDT_ProductPriceBLL.GetPriceByClientAndType(client.ID, product.ID, 2, out factoryprice, out salesprice);

                    if (factoryprice == 0)
                    {
                        factoryprice = product.FactoryPrice;
                    }
                    if (salesprice == 0)
                    {
                        salesprice = product.NetPrice;
                    }

                    SVM_SalesVolume_Detail detail = new SVM_SalesVolume_Detail();
                    detail.Product      = product.ID;
                    detail.FactoryPrice = factoryprice;
                    detail.SalesPrice   = salesprice;
                    detail.Quantity     = quantity;

                    details.Add(detail);
                }
            }
            #endregion

            #region 更新销量至数据库
            if (bll.Model.ID > 0)
            {
                if (details.Count > 0)
                {
                    bll.DeleteDetail();     //先清除原先导入的数据

                    bll.Items = details;
                    bll.AddDetail();
                    bll.Update();

                    ImportInfo += "<span style='color: Blue'>序号:" + dr["序号"].ToString() + ",零售商:" + client.FullName
                                  + " 的原有日期为:" + bll.Model.SalesDate.ToString("yyyy-MM-dd") + " 的进货单被成功更新!产品SKU数:"
                                  + bll.Items.Count.ToString() + ",产品总数量:" + bll.Items.Sum(p => p.Quantity).ToString() + "</span><br/>";
                }
            }
            else
            {
                //if (details.Count > 0)    //没有产品也新增一条空销量头
                {
                    bll.Items = details;
                    bll.Add();
                    ImportInfo += "<span style='color: Black'>序号:" + dr["序号"].ToString() + ",零售商:" + client.FullName
                                  + " 的进货单已成功导入!产品SKU数:" + bll.Items.Count.ToString() + ",产品总数量:"
                                  + bll.Items.Sum(p => p.Quantity).ToString() + "</span><br/>";
                }
            }
            #endregion
        }
        #endregion

        ImportInfo += "<br/><br/>";
        ImportInfo += "<span style='color: Red'>-------------------------------------------------------------------------</span><br/>";
        ImportInfo += "<span style='color: Red'>----批量导入零售商销货销量----</span><br/>";

        #region 开始导入零售商销货
        foreach (System.Data.DataRow dr in dtSellOut.Rows)
        {
            #region 验证数据
            int       clientid = (int)dr["零售商ID"];
            CM_Client client   = new CM_ClientBLL(clientid).Model;
            if (client == null || client.FullName != (string)dr["零售商名称"])
            {
                ImportInfo += "<span style='color: Red'>序号:" + dr["序号"].ToString() + ",零售商ID与零售商名称不匹配!</span><br/>";
                continue;
            }

            if (dr["归属月份"].ToString() != month.Name)
            {
                ImportInfo += "<span style='color: Red'>序号:" + dr["序号"].ToString() + ",归属月份必须为【" + month.Name + "】</span><br/>";
                continue;
            }
            //DateTime salesdate = (DateTime)dr["销售日期"];
            //if (salesdate < minday || salesdate > maxday)
            //{
            //    ImportInfo += "<span style='color: Red'>序号:" + dr["序号"].ToString() + ",销售日期必须在" + minday.ToString("yyyy-MM-dd") +
            //        "至" + maxday.ToString("yyyy-MM-dd") + "之前!</span><br/>";
            //    continue;
            //}

            int promotorid = (int)dr["导购ID"];
            if (promotorid > 0)
            {
                if (PM_PromotorInRetailerBLL.GetModelList("Client=" + client.ID.ToString() +
                                                          " AND Promotor=" + promotorid.ToString()).Count == 0)
                {
                    ImportInfo += "<span style='color: Red'>序号:" + dr["序号"].ToString() + ",零售商中没有关联该导购员!</span><br/>";
                    continue;
                }
            }
            #endregion

            #region 组织销量头
            SVM_SalesVolumeBLL      bll      = null;
            IList <SVM_SalesVolume> svmlists = SVM_SalesVolumeBLL.GetModelList("Supplier=" + clientid.ToString()
                                                                               + " AND Type=3 AND AccountMonth=" + month.ID.ToString() //+ " AND SalesDate='" + salesdate.ToString("yyyy-MM-dd")
                                                                               + " AND MCS_SYS.dbo.UF_Spilt(ExtPropertys,'|',1)='N' AND ISNULL(Promotor,0)=" + promotorid.ToString());
            if (svmlists.Count > 0)
            {
                if (svmlists[0].ApproveFlag == 1)
                {
                    ImportInfo += "<span style='color: Red'>序号:" + dr["序号"].ToString() + ",该零售商当月的销量已审核,不可再次导入!</span><br/>";
                    continue;
                }

                bll = new SVM_SalesVolumeBLL(svmlists[0].ID);
                bll.Model["SubmitFlag"] = "1";
                bll.Items.Clear();
            }
            else
            {
                bll = new SVM_SalesVolumeBLL();
                bll.Model.Client        = 0;
                bll.Model.OrganizeCity  = client.OrganizeCity;
                bll.Model.Supplier      = client.ID;
                bll.Model.Promotor      = promotorid;
                bll.Model.AccountMonth  = month.ID;
                bll.Model.SalesDate     = maxday;
                bll.Model.Type          = 3;
                bll.Model.ApproveFlag   = 2;
                bll.Model.Flag          = 1;    //成品销售
                bll.Model["SubmitFlag"] = "1";
                bll.Model["IsCXP"]      = "N";
                bll.Model.InsertStaff   = (int)Session["UserID"];
                bll.Model.Remark        = "Excel批量导入";
            }
            #endregion

            #region 读取各产品销量
            IList <SVM_SalesVolume_Detail> details = new List <SVM_SalesVolume_Detail>();
            foreach (PDT_Product product in productlists)
            {
                int quantity = (int)dr["[" + product.ShortName + "]"];
                if (quantity != 0)
                {
                    decimal factoryprice = 0, salesprice = 0;
                    PDT_ProductPriceBLL.GetPriceByClientAndType(client.ID, product.ID, 3, out factoryprice, out salesprice);

                    if (factoryprice == 0)
                    {
                        factoryprice = product.FactoryPrice;
                    }
                    if (salesprice == 0)
                    {
                        salesprice = product.StdPrice;
                    }

                    SVM_SalesVolume_Detail detail = new SVM_SalesVolume_Detail();
                    detail.Product      = product.ID;
                    detail.FactoryPrice = factoryprice;
                    detail.SalesPrice   = salesprice;
                    detail.Quantity     = quantity;

                    details.Add(detail);
                }
            }
            #endregion

            #region 更新销量至数据库
            if (bll.Model.ID > 0)
            {
                if (details.Count > 0)
                {
                    bll.DeleteDetail();     //先清除原先导入的数据

                    bll.Items = details;
                    bll.AddDetail();
                    bll.Update();

                    ImportInfo += "<span style='color: Blue'>序号:" + dr["序号"].ToString() + ",零售商:" + client.FullName
                                  + " 的原有日期为:" + bll.Model.SalesDate.ToString("yyyy-MM-dd") + " 的销量单被成功更新!产品SKU数:"
                                  + bll.Items.Count.ToString() + ",产品总数量:" + bll.Items.Sum(p => p.Quantity).ToString() + "</span><br/>";
                }
            }
            else
            {
                //if (details.Count > 0)    //没有产品也新增一条空销量头
                {
                    bll.Items = details;
                    bll.Add();
                    ImportInfo += "<span style='color: Black'>序号:" + dr["序号"].ToString() + ",零售商:" + client.FullName
                                  + " 的销量单已成功导入!产品SKU数:" + bll.Items.Count.ToString() + ",产品总数量:"
                                  + bll.Items.Sum(p => p.Quantity).ToString() + "</span><br/>";
                }
            }
            #endregion
        }
        #endregion

        lb_ErrorInfo.Text = ImportInfo;
        bt_Import.Enabled = false;

        Session["DataTable-SellIn"]  = null;
        Session["DataTable-SellOut"] = null;
    }
Exemplo n.º 17
0
        private void threadStartImport(BackgroundWorker worker, DoWorkEventArgs e)
        {
            DataTable dt_OfficialCity = Addr_OfficialCityBLL.GetAllOfficialCity();
            DataTable dt_OrganizeCity = Addr_OrganizeCityBLL.GetAllOrganizeCity();
            DataTable dt_Position = Org_PositionBLL.GetAllPostion();
            bool bFind = false;

            StringBuilder _xhs_success = new StringBuilder("");//成功导入的记录序号(用于定期批量更新导入标志)
            string XH = "";

            #region 导入销售人员资料
            try
            {
                if (cbx_Promotor.Checked)
                {
                    lb_Count.Text = dt_SalesStaff.Rows.Count.ToString();
                    tabControl1.SelectedIndex = 0;
                    XH = "";
                    for (int i = 0; i < dt_SalesStaff.Rows.Count; i++)
                    {
                        worker.ReportProgress((i + 1) * 100 / this.dt_SalesStaff.Rows.Count, i);
                        if (worker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }
                        XH = dt_SalesStaff.Rows[i]["序号"].ToString();
                        Org_StaffBLL staff = new Org_StaffBLL();

                        //序号
                        if (dt_SalesStaff.Rows[i]["员工工号"].ToString() != "")
                            staff.Model["StaffCode"] = dt_SalesStaff.Rows[i]["员工工号"].ToString();
                        else
                            staff.Model["StaffCode"] = FormatClientCode('S', dt_SalesStaff.Rows[i]["序号"].ToString().Trim(), dt_SalesStaff.Rows[i]["管理片区代码"].ToString().Trim());

                        #region 判断数据是否重复
                        if (Org_StaffBLL.GetStaffList("StaffCode = '" + staff.Model["StaffCode"] + "'").Count > 0)
                        {
                            UpdateImportFlag(1, i, "导入失败,数据重复!");
                            continue;
                        }
                        #endregion

                        //姓名
                        staff.Model["RealName"] = dt_SalesStaff.Rows[i]["姓名"].ToString().Trim();

                        //职务
                        DataRow[] rows_Position = dt_Position.Select("Name = '" + dt_SalesStaff.Rows[i]["职务"].ToString().Trim() + "'");
                        if (rows_Position.Length == 0)
                        {
                            UpdateImportFlag(1, i, "导入失败,职务在系统字典中不存在!");
                            continue;
                        }
                        else
                            staff.Model["Position"] = rows_Position[0]["ID"].ToString().Trim();

                        //管理片区代码
                        DataRow[] rows_OrganizeCity = dt_OrganizeCity.Select("Code='" + dt_SalesStaff.Rows[i]["管理片区代码"].ToString().Trim() + "'");
                        if (rows_OrganizeCity.Length == 0)
                        {
                            UpdateImportFlag(1, i, "导入失败,管理片区代码在系统字典中不存在!");
                            continue;
                        }
                        else
                            staff.Model["OrganizeCity"] = rows_OrganizeCity[0]["ID"].ToString().Trim();

                        //性别
                        staff.Model["Sex"] = dt_SalesStaff.Rows[i]["性别"].ToString();
                        //bFind = false;
                        //foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("Pub_Sex").Values)
                        //{
                        //    if (item.Name == dt_SalesStaff.Rows[i]["性别"].ToString().Trim())
                        //    {
                        //        staff.Model["Sex"] = item.Code;
                        //        bFind = true;
                        //        break;
                        //    }
                        //}
                        //if (!bFind)
                        //{
                        //    UpdateImportFlag(1, i, "导入失败,性别在系统字典中不存在!");
                        //    continue;
                        //}

                        //联系电话
                        staff.Model["TeleNum"] = dt_SalesStaff.Rows[i]["联系电话"].ToString().Trim();

                        //手机
                        staff.Model["Mobile"] = dt_SalesStaff.Rows[i]["手机"].ToString().Trim();

                        //城市
                        string cityname = dt_SalesStaff.Rows[i]["城市"].ToString().Trim();
                        if (cityname.Length > 3) cityname = cityname.Substring(0, 3);
                        DataRow[] rows_OfficialCity = dt_OfficialCity.Select("Name like '" + cityname + "%'");
                        if (rows_OfficialCity.Length == 0)
                        {
                            UpdateImportFlag(1, i, "导入失败,城市在系统字典中不存在!");
                            continue;
                        }
                        else
                            staff.Model["OfficialCity"] = rows_OfficialCity[0]["ID"].ToString().Trim();

                        //家庭地址
                        staff.Model["Address"] = dt_SalesStaff.Rows[i]["家庭地址"].ToString().Trim();

                        //身份证号
                        staff.Model["IDCode"] = dt_SalesStaff.Rows[i]["身份证号"].ToString().Trim();

                        //上岗时间
                        if (dt_SalesStaff.Rows[i]["上岗时间"].ToString().Trim() != "")
                            staff.Model["BeginWorkTime"] = dt_SalesStaff.Rows[i]["上岗时间"].ToString().Trim();

                        //离岗时间
                        if (dt_SalesStaff.Rows[i]["离岗时间"].ToString().Trim() != "")
                            staff.Model["EndWorkTime"] = dt_SalesStaff.Rows[i]["离岗时间"].ToString().Trim();

                        //银行类别
                        staff.Model["BankName"] = dt_SalesStaff.Rows[i]["银行类别"].ToString().Trim();

                        //工资卡号
                        staff.Model["BankAccount"] = dt_SalesStaff.Rows[i]["工资卡号"].ToString().Trim();

                        //在职标志
                        staff.Model["Dimission"] = "1";

                        int iret = staff.Add();
                        if (iret > 0)
                        {
                            _xhs_success.Append(XH + ",");
                            //UpdateImportFlag(1, i, "导入成功,ID=" + iret.ToString());

                            #region 创建用户登录帐户
                            string username = staff.Model.RealName;
                            string pwd = "000000";
                            MembershipUserCollection haveusers = Membership.FindUsersByName(username);
                            if (haveusers.Count > 0)
                            {
                                username += "_" + haveusers.Count.ToString();
                            }
                            if (staff.Model["IDCode"].Length >= 6)
                                pwd = staff.Model["IDCode"].Substring(staff.Model["IDCode"].Length - 6);

                            MembershipUser user = Membership.CreateUser(username, pwd, "*****@*****.**");

                            if (user != null)
                            {
                                UserBLL.Membership_SetStaffID(user.UserName, iret);

                                Roles.AddUserToRole(user.UserName, " 全体员工");
                            }
                            #endregion
                        }
                        else
                            UpdateImportFlag(1, i, "导入失败,写入数据库失败!");
                    }
                    UpdateSuccess(_xhs_success.ToString(), 1);
                }
            }
            catch (System.Exception err)
            {
                UpdateSuccess(_xhs_success.ToString(), 1);
                MessageBox.Show(err.Source + "~r~n" + err.StackTrace, err.Message);
            }
            #endregion

            Thread.Sleep(1000);

            #region 导入经销商
            try
            {
                if (checkBox2.Checked)
                {
                    lb_Count.Text = dt_Distributor.Rows.Count.ToString();
                    tabControl1.SelectedIndex = 1;
                    XH = "";
                    for (int i = 0; i < dt_Distributor.Rows.Count; i++)
                    {
                        worker.ReportProgress((i + 1) * 100 / this.dt_Distributor.Rows.Count, i);

                        if (worker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }
                        XH = dt_Distributor.Rows[i]["序号"].ToString();
                        CM_ClientBLL client = new CM_ClientBLL();

                        client.Model.ClientType = 2;    //经销商

                        #region 编号
                        if (dt_Distributor.Rows[i]["经销商编号"].ToString().Trim() != "")
                            client.Model["Code"] = dt_Distributor.Rows[i]["经销商编号"].ToString().Trim();
                        else
                            client.Model["Code"] = FormatClientCode('D', dt_Distributor.Rows[i]["序号"].ToString().Trim(), dt_Distributor.Rows[i]["管理片区代码"].ToString().Trim());

                        #region 判断数据是否重复
                        if (CM_ClientBLL.GetModelList("Code = '" + client.Model["Code"] + "'").Count > 0)
                        {
                            UpdateImportFlag(2, i, "导入失败,数据重复!");
                            continue;
                        }
                        #endregion
                        #endregion

                        //全称
                        client.Model["FullName"] = dt_Distributor.Rows[i]["全称"].ToString().Trim();
                        client.Model["ShortName"] = dt_Distributor.Rows[i]["简称"].ToString().Trim();

                        #region 管理片区代码
                        DataRow[] rows_OrganizeCity = dt_OrganizeCity.Select("Code='" + dt_Distributor.Rows[i]["管理片区代码"].ToString().Trim() + "'");
                        if (rows_OrganizeCity.Length == 0)
                        {
                            UpdateImportFlag(2, i, "导入失败,管理片区代码在系统字典中不存在!");
                            continue;
                        }
                        else
                            client.Model["OrganizeCity"] = rows_OrganizeCity[0]["ID"].ToString().Trim();
                        #endregion

                        #region 联系方式
                        client.Model["TeleNum"] = dt_Distributor.Rows[i]["固定电话"].ToString().Trim();
                        client.Model["Fax"] = dt_Distributor.Rows[i]["传真"].ToString().Trim();
                        client.Model["PostCode"] = dt_Distributor.Rows[i]["邮编"].ToString().Trim();
                        client.Model["Email"] = dt_Distributor.Rows[i]["Email"].ToString().Trim();
                        client.Model["Address"] = dt_Distributor.Rows[i]["地址"].ToString().Trim();
                        #endregion

                        #region 所在城市
                        string cityname = dt_Distributor.Rows[i]["城市"].ToString().Trim();
                        string areaname = dt_Distributor.Rows[i]["县城"].ToString().Trim();
                        if (areaname != "")
                        {
                            DataRow[] rows_OfficialCity = dt_OfficialCity.Select("Name like '" + areaname + "%'");
                            if (rows_OfficialCity.Length == 1)
                                client.Model.OfficalCity = int.Parse(rows_OfficialCity[0]["ID"].ToString().Trim());
                        }
                        if (cityname != "" && client.Model.OfficalCity == 0)
                        {
                            DataRow[] rows_OfficialCity = dt_OfficialCity.Select("Name like '" + cityname + "%'");
                            if (rows_OfficialCity.Length == 1)
                                client.Model.OfficalCity = int.Parse(rows_OfficialCity[0]["ID"].ToString().Trim());
                        }

                        if (client.Model["TeleNum"] != "" && client.Model.OfficalCity == 0)
                        {
                            Addr_OfficialCity city = null;
                            city = Addr_OfficialCityBLL.GetCityByTeleNumOrPostCode(client.Model["TeleNum"]);
                            if (city != null) client.Model.OfficalCity = city.ID;
                        }

                        if (client.Model["PostCode"] != "" && client.Model.OfficalCity == 0)
                        {
                            Addr_OfficialCity city = null;
                            city = Addr_OfficialCityBLL.GetCityByTeleNumOrPostCode(client.Model["PostCode"]);
                            if (city != null) client.Model.OfficalCity = city.ID;
                        }

                        if (dt_Distributor.Rows[i]["手机"].ToString().Trim() != "" && client.Model.OfficalCity == 0)
                        {
                            Addr_OfficialCity city = null;
                            city = Addr_OfficialCityBLL.GetCityByTeleNumOrPostCode(dt_Distributor.Rows[i]["手机"].ToString().Trim());
                            if (city != null) client.Model.OfficalCity = city.ID;
                        }

                        if (client.Model.OfficalCity == 0)
                        {
                            UpdateImportFlag(2, i, "导入失败,城市在系统字典中不存在!");
                            continue;
                        }
                        #endregion

                        #region 经销商类别
                        bFind = false;
                        foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("CM_DI_Classify").Values)
                        {
                            if (item.Name == dt_Distributor.Rows[i]["类别"].ToString().Trim())
                            {
                                client.Model["DIClassify"] = item.Code;
                                bFind = true;
                                break;
                            }
                        }
                        if (!bFind)
                        {
                            UpdateImportFlag(2, i, "导入失败,类别在系统字典中不存在!");
                            continue;
                        }

                        #endregion

                        #region 活跃状态
                        bFind = false;
                        foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("CM_ActiveFlag").Values)
                        {
                            if (item.Name == dt_Distributor.Rows[i]["活跃状态"].ToString().Trim())
                            {
                                client.Model["ActiveFlag"] = item.Code;
                                bFind = true;
                                break;
                            }
                        }
                        if (!bFind)
                        {
                            UpdateImportFlag(2, i, "导入失败,活跃状态在系统字典中不存在!");
                            continue;
                        }
                        #endregion

                        #region 纳税类型
                        if (dt_Distributor.Rows[i]["纳税类型"].ToString().Trim() != "")
                        {
                            bFind = false;
                            foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("CM_TaxesClassify").Values)
                            {
                                if (item.Name == dt_Distributor.Rows[i]["纳税类型"].ToString().Trim())
                                {
                                    client.Model["TaxesClassify"] = item.Code;
                                    bFind = true;
                                    break;
                                }
                            }
                            if (!bFind)
                            {
                                UpdateImportFlag(2, i, "导入失败,纳税类型在系统字典中不存在!");
                                continue;
                            }
                        }
                        #endregion

                        #region 市场类型
                        if (dt_Distributor.Rows[i]["市场类型"].ToString().Trim() != "")
                        {
                            bFind = false;
                            foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("CM_MarketType").Values)
                            {
                                if (item.Name == dt_Distributor.Rows[i]["市场类型"].ToString().Trim())
                                {
                                    client.Model["MarketType"] = item.Code;
                                    bFind = true;
                                    break;
                                }
                            }
                            if (!bFind)
                            {
                                UpdateImportFlag(2, i, "导入失败,市场类型在系统字典中不存在!");
                                continue;
                            }
                        }
                        #endregion

                        #region 主营渠道
                        if (dt_Distributor.Rows[i]["主营渠道"].ToString().Trim() != "")
                        {
                            bFind = false;
                            foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("CM_RT_Channel").Values)
                            {
                                if (item.Name == dt_Distributor.Rows[i]["主营渠道"].ToString().Trim())
                                {
                                    client.Model["RTChannel"] = item.Code;
                                    bFind = true;
                                    break;
                                }
                            }
                            if (!bFind)
                            {
                                UpdateImportFlag(2, i, "导入失败,主营渠道在系统字典中不存在!");
                                continue;
                            }
                        }
                        #endregion

                        //开始合作时间
                        if (dt_Distributor.Rows[i]["开始合作时间"].ToString().Trim() != "")
                            client.Model["OpenTime"] = dt_Distributor.Rows[i]["开始合作时间"].ToString().Trim();

                        //覆盖区域
                        client.Model["CoverageArea"] = dt_Distributor.Rows[i]["覆盖区域"].ToString().Trim();

                        //主要销售奶粉品牌
                        client.Model["MostlyBrand"] = dt_Distributor.Rows[i]["主要销售奶粉品牌"].ToString().Trim();

                        //开户行类别
                        client.Model["BankName"] = dt_Distributor.Rows[i]["开户行类别"].ToString().Trim();
                        //开户行账号
                        client.Model["BankAccountNo"] = dt_Distributor.Rows[i]["开户行账号"].ToString().Trim();

                        #region 隶属一级商编号
                        if (client.Model["DIClassify"] != "1" && dt_Distributor.Rows[i]["隶属一级商编号"].ToString().Trim() != "")
                        {
                            IList<CM_Client> lists = CM_ClientBLL.GetModelList("Code='" + dt_Distributor.Rows[i]["隶属一级商编号"].ToString().Trim() + "'");
                            if (lists.Count > 0)
                            {
                                client.Model["Supplier"] = lists[0]["ID"];
                            }
                            else
                            {
                                //UpdateImportFlag(2, i, "导入失败,隶属一级商编号在客户中不存在!");
                                //continue;
                            }
                        }
                        else if (client.Model["DIClassify"] == "1")
                        {
                            client.Model.Supplier = 1223; //总部仓库
                        }
                        #endregion

                        #region 责任业代
                        bool fail1 = false;
                        if (dt_Distributor.Rows[i]["责任业代"].ToString().Trim() != "")
                        {
                            string cityids = new Addr_OrganizeCityBLL(client.Model.OrganizeCity).GetAllChildNodeIDs();
                            if (cityids != "") cityids += ",";
                            cityids += client.Model.OrganizeCity.ToString();

                            IList<Org_Staff> staffs = Org_StaffBLL.GetStaffList("OrganizeCity IN(" + cityids + ") AND RealName='" + dt_Distributor.Rows[i]["责任业代"].ToString().Trim() + "' AND Dimission=1");
                            if (staffs.Count == 1)
                                client.Model.ClientManager = staffs[0].ID;
                            else
                            {
                                fail1 = true;
                                //UpdateImportFlag(2, i, "导入失败,责任业代在员工表中不存在!" + staffs.Count.ToString());
                                //continue;
                            }
                        }
                        #endregion

                        client.Model.ApproveFlag = 1;
                        int iret = client.Add();
                        if (iret > 0)
                        {
                            //_xhs_success.Append(XH + ",");
                            if (!fail1)
                                UpdateImportFlag(2, i, "导入成功,ID=" + iret.ToString());
                            else
                                UpdateImportFlag(2, i, "部分导入成功,责任业代在员工表中不存在!");
                        }
                        else
                        {
                            UpdateImportFlag(2, i, "导入失败,写入数据库失败!");
                            continue;
                        }

                        #region 加入联系人
                        CM_LinkManBLL linkman = new CM_LinkManBLL();
                        linkman.Model.ClientID = iret;

                        #region 负责人
                        if (dt_Distributor.Rows[i]["负责人"].ToString().Trim() != "")
                        {
                            linkman.Model["Name"] = dt_Distributor.Rows[i]["负责人"].ToString().Trim();

                            #region 负责人职务
                            if (dt_Distributor.Rows[i]["负责人职务"].ToString().Trim() != "")
                            {
                                bFind = false;
                                foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("CM_LinkManJob").Values)
                                {
                                    if (item.Name == dt_Distributor.Rows[i]["负责人职务"].ToString().Trim())
                                    {
                                        linkman.Model["Job"] = item.Code;
                                        bFind = true;
                                        break;
                                    }
                                }
                            }
                            #endregion

                            //固定电话
                            linkman.Model["OfficeTeleNum"] = dt_Distributor.Rows[i]["固定电话"].ToString().Trim();

                            //手机
                            linkman.Model["Mobile"] = dt_Distributor.Rows[i]["手机"].ToString().Trim();
                            iret = linkman.Add();

                            if (iret > 0)
                            {
                                client.Model["ChiefLinkMan"] = iret.ToString();
                                client.Update();
                            }
                        }
                        #endregion

                        #region 法人
                        if (dt_Distributor.Rows[i]["负责人"].ToString().Trim() != "")
                        {
                            linkman.Model["Name"] = dt_Distributor.Rows[i]["法人代表"].ToString().Trim();
                            linkman.Model["Job"] = "2";       //法人代表
                            linkman.Model["OfficeTeleNum"] = dt_Distributor.Rows[i]["法人联系电话"].ToString().Trim();

                            if (linkman.Model["OfficeTeleNum"].StartsWith("1"))
                                linkman.Model["Mobile"] = linkman.Model["OfficeTeleNum"];

                            linkman.Add();
                        }
                        #endregion

                        #endregion
                    }
                    //UpdateSuccess(_xhs_success.ToString(), 2);
                }
            }
            catch (System.Exception err)
            {
                UpdateSuccess(_xhs_success.ToString(), 1);
                MessageBox.Show(err.Source + "~r~n" + err.StackTrace, err.Message);
            }
            #endregion

            Thread.Sleep(1000);

            #region 导入终端门店资料表
            StringBuilder _xhs_rt_fail1 = new StringBuilder("");
            StringBuilder _xhs_rt_fail2 = new StringBuilder("");
            try
            {
                if (checkBox3.Checked)
                {
                    lb_Count.Text = dt_Retailer.Rows.Count.ToString();
                    tabControl1.SelectedIndex = 2;
                    XH = "";
                    for (int i = 0; i < dt_Retailer.Rows.Count; i++)
                    {
                        worker.ReportProgress((i + 1) * 100 / this.dt_Retailer.Rows.Count, i);
                        if (worker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        bool bsuccess = true;
                        XH = dt_Retailer.Rows[i]["序号"].ToString();
                        CM_ClientBLL client = new CM_ClientBLL();

                        client.Model.ClientType = 3;    //终端门店

                        #region 序号
                        client.Model["Code"] = dt_Retailer.Rows[i]["门店编码"].ToString().Trim();

                        #region 判断数据是否重复
                        if (CM_ClientBLL.GetModelList("Code = '" + client.Model["Code"] + "'").Count > 0)
                        {
                            UpdateImportFlag(3, i, "导入失败,数据重复!");
                            continue;
                        }
                        #endregion
                        #endregion

                        //连锁店名称
                        client.Model["ChainStoreName"] = dt_Retailer.Rows[i]["连锁店名称"].ToString().Trim();

                        //门店全称
                        client.Model["FullName"] = dt_Retailer.Rows[i]["门店全称"].ToString().Trim();

                        //门店简称
                        client.Model["ShortName"] = dt_Retailer.Rows[i]["门店简称"].ToString().Trim();
                        if (client.Model.ShortName == "") client.Model.ShortName = client.Model.FullName;

                        #region 管理片区代码
                        DataRow[] rows_OrganizeCity = dt_OrganizeCity.Select("Code='" + dt_Retailer.Rows[i]["管理片区代码"].ToString().Trim() + "'");
                        if (rows_OrganizeCity.Length == 0)
                        {
                            UpdateImportFlag(3, i, "导入失败,管理片区代码在系统字典中不存在!");
                            continue;
                        }
                        else
                            client.Model["OrganizeCity"] = rows_OrganizeCity[0]["ID"].ToString().Trim();
                        #endregion

                        //固定电话
                        client.Model["TeleNum"] = dt_Retailer.Rows[i]["固定电话"].ToString().Trim();
                        if (client.Model["TeleNum"] == "") client.Model["TeleNum"] = dt_Retailer.Rows[i]["联系人手机"].ToString().Trim();

                        //门店地址
                        client.Model["Address"] = dt_Retailer.Rows[i]["门店地址"].ToString().Trim();

                        #region 所在城市
                        string cityname = dt_Retailer.Rows[i]["城市"].ToString().Trim();
                        string areaname = dt_Retailer.Rows[i]["县城"].ToString().Trim();
                        string townname = dt_Retailer.Rows[i]["乡镇"].ToString().Trim();
                        if (townname != "")
                        {
                            DataRow[] rows_OfficialCity = dt_OfficialCity.Select("Name like '" + townname + "%'");
                            if (rows_OfficialCity.Length == 1)
                                client.Model.OfficalCity = int.Parse(rows_OfficialCity[0]["ID"].ToString().Trim());
                        }
                        if (areaname != "" && client.Model.OfficalCity == 0)
                        {
                            DataRow[] rows_OfficialCity = dt_OfficialCity.Select("Name like '" + areaname + "%'");
                            if (rows_OfficialCity.Length == 1)
                                client.Model.OfficalCity = int.Parse(rows_OfficialCity[0]["ID"].ToString().Trim());
                        }
                        if (cityname != "" && client.Model.OfficalCity == 0)
                        {
                            DataRow[] rows_OfficialCity = dt_OfficialCity.Select("Name like '" + cityname + "%'");
                            if (rows_OfficialCity.Length > 0)
                                client.Model.OfficalCity = int.Parse(rows_OfficialCity[0]["ID"].ToString().Trim());
                        }

                        if (client.Model["TeleNum"] != "" && client.Model.OfficalCity == 0)
                        {
                            Addr_OfficialCity city = null;
                            city = Addr_OfficialCityBLL.GetCityByTeleNumOrPostCode(client.Model["TeleNum"]);
                            if (city != null) client.Model.OfficalCity = city.ID;
                        }

                        if (client.Model.OfficalCity == 0)
                        {
                            UpdateImportFlag(3, i, "导入失败,城市在系统字典中不存在!");
                            continue;
                        }
                        #endregion

                        #region 门店渠道
                        if (dt_Retailer.Rows[i]["门店渠道"].ToString().Trim() != "")
                        {
                            bFind = false;
                            foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("CM_RT_Channel").Values)
                            {
                                if (item.Name == dt_Retailer.Rows[i]["门店渠道"].ToString().Trim().ToUpper())
                                {
                                    client.Model["RTChannel"] = item.Code;
                                    bFind = true;
                                    break;
                                }
                            }
                            if (!bFind)
                            {
                                UpdateImportFlag(3, i, "导入失败,门店渠道在系统字典中不存在!");
                                continue;
                            }
                        }
                        #endregion

                        #region 门店类型
                        if (dt_Retailer.Rows[i]["门店类型"].ToString().Trim() != "")
                        {
                            bFind = false;
                            foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("CM_RT_Classify").Values)
                            {
                                if (item.Name == dt_Retailer.Rows[i]["门店类型"].ToString().Trim())
                                {
                                    client.Model["RTClassify"] = item.Code;
                                    bFind = true;
                                    break;
                                }
                            }
                            if (!bFind)
                            {
                                UpdateImportFlag(3, i, "导入失败,门店类型在系统字典中不存在!");
                                continue;
                            }
                        }
                        #endregion

                        #region 销售代表
                        if (dt_Retailer.Rows[i]["销售代表工号"].ToString().Trim() != "")
                        {
                            IList<Org_Staff> staffs = Org_StaffBLL.GetStaffList("StaffCode='" + dt_Retailer.Rows[i]["销售代表工号"].ToString().Trim() + "' AND Dimission=1");
                            if (staffs.Count > 1) staffs = Org_StaffBLL.GetStaffList("StaffCode='" + dt_Retailer.Rows[i]["销售代表工号"].ToString().Trim() + "' AND Dimission=1 AND RealName='" + dt_Retailer.Rows[i]["销售代表"].ToString().Trim() + "'");

                            if (staffs.Count == 0)
                            {
                                _xhs_rt_fail2.Append(XH + ",");
                                bsuccess = false;
                                //UpdateImportFlag(3, i, "导入失败,销售代表在员工中不存在!");
                                //continue;
                            }
                            else if (staffs.Count > 1)
                            {
                                _xhs_rt_fail2.Append(XH + ",");
                                bsuccess = false;
                                //UpdateImportFlag(3, i, "导入失败,销售代表在员工中有多个相同姓名的员工!");
                                //continue;
                            }
                            else
                            {
                                client.Model["ClientManager"] = staffs[0]["ID"];
                            }
                        }
                        #endregion

                        #region 送货经销商编号
                        IList<CM_Client> clients = CM_ClientBLL.GetModelList("Code='" + dt_Retailer.Rows[i]["送货经销商编号"].ToString().Trim() + "'");
                        if (clients.Count == 0)
                        {
                            _xhs_rt_fail1.Append(XH + ",");
                            bsuccess = false;
                            //UpdateImportFlag(3, i, "导入失败,送货经销商编号在客户中不存在!");
                            //continue;
                        }
                        else if (clients.Count > 1)
                        {
                            _xhs_rt_fail1.Append(XH + ",");
                            bsuccess = false;
                            //UpdateImportFlag(3, i, "导入失败,送货经销商编号在客户中有多个相同编号的客户!");
                            //continue;
                        }
                        else
                        {
                            client.Model["Supplier"] = clients[0]["ID"];
                        }
                        #endregion

                        client.Model["Salesroom"] = dt_Retailer.Rows[i]["奶粉月容量"].ToString().Trim();
                        client.Model["BusinessArea"] = dt_Retailer.Rows[i]["卖场面积"].ToString().Trim();

                        client.Model["BankName"] = dt_Retailer.Rows[i]["开户行全称"].ToString().Trim();
                        client.Model["AccountName"] = dt_Retailer.Rows[i]["开户名"].ToString().Trim();
                        client.Model["BankAccountNo"] = dt_Retailer.Rows[i]["卡账号"].ToString().Trim();

                        //活跃状态
                        client.Model["ActiveFlag"] = "1";
                        client.Model.ApproveFlag = 1;

                        int iret = client.Add();
                        if (iret > 0)
                        {
                            if (bsuccess) _xhs_success.Append(XH + ",");
                            if (_xhs_success.Length >= 10000)
                            {
                                UpdateSuccess(_xhs_success.ToString(), 3);
                                UpdateFail1(_xhs_rt_fail1.ToString());
                                UpdateFail2(_xhs_rt_fail2.ToString());

                                _xhs_success = new StringBuilder("");
                                _xhs_rt_fail1 = new StringBuilder("");
                                _xhs_rt_fail2 = new StringBuilder("");
                            }
                            //UpdateImportFlag(3, i, "导入成功,ID=" + iret.ToString());
                        }
                        else
                        {
                            UpdateImportFlag(3, i, "导入失败,写入数据库失败!");
                            continue;
                        }

                        #region 加入联系人
                        CM_LinkManBLL linkman = new CM_LinkManBLL();
                        linkman.Model.ClientID = iret;

                        //门店联系人
                        linkman.Model["Name"] = dt_Retailer.Rows[i]["门店联系人"].ToString().Trim();
                        if (linkman.Model["Name"] == "") linkman.Model.Name = "无";

                        //联系人职务
                        #region 联系人职务
                        if (dt_Retailer.Rows[i]["联系人职务"].ToString().Trim() != "")
                        {
                            bFind = false;
                            foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("CM_LinkManJob").Values)
                            {
                                if (item.Name == dt_Retailer.Rows[i]["联系人职务"].ToString().Trim())
                                {
                                    linkman.Model["Job"] = item.Code;
                                    bFind = true;
                                    break;
                                }
                            }
                        }
                        #endregion

                        //联系人固定电话
                        linkman.Model["OfficeTeleNum"] = dt_Retailer.Rows[i]["联系人固定电话"].ToString().Trim();

                        //联系人手机
                        linkman.Model["Mobile"] = dt_Retailer.Rows[i]["联系人手机"].ToString().Trim();

                        if (linkman.Model.Name == "无" && linkman.Model["OfficeTeleNum"] == "" && linkman.Model["Mobile"] == "")
                        {
                        }
                        else
                        {
                            iret = linkman.Add();

                            if (iret > 0)
                            {
                                client.Model["ChiefLinkMan"] = iret.ToString();
                                client.Update();
                            }
                        }
                        #endregion
                    }
                    UpdateSuccess(_xhs_success.ToString(), 3);
                    UpdateFail1(_xhs_rt_fail1.ToString());
                    UpdateFail2(_xhs_rt_fail2.ToString());
                }
            }
            catch (System.Exception err)
            {
                UpdateSuccess(_xhs_success.ToString(), 3);
                UpdateFail1(_xhs_rt_fail1.ToString());
                UpdateFail2(_xhs_rt_fail2.ToString());

                MessageBox.Show(err.Source + "~r~n" + err.StackTrace, err.Message);
            }
            #endregion

            Thread.Sleep(1000);

            #region 导入促销员
            try
            {
                if (checkBox4.Checked)
                {
                    lb_Count.Text = dt_Promotor.Rows.Count.ToString();
                    tabControl1.SelectedIndex = 3;
                    XH = "";

                    for (int i = 0; i < dt_Promotor.Rows.Count; i++)
                    {
                        worker.ReportProgress((i + 1) * 100 / this.dt_Promotor.Rows.Count, i);
                        if (worker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }
                        XH = dt_Promotor.Rows[i]["序号"].ToString();

                        PM_PromotorBLL promotor = new PM_PromotorBLL();

                        //序号
                        promotor.Model["Code"] = dt_Promotor.Rows[i]["导购编号"].ToString().Trim();

                        //判断数据是否重复
                        int promotorid = 0;
                        if (PM_PromotorBLL.GetModelList("Code = '" + promotor.Model["Code"] + "'").Count == 0)
                        {
                            #region 导入促销员资料
                            //姓名
                            promotor.Model["Name"] = dt_Promotor.Rows[i]["姓名"].ToString().Trim();

                            //管理片区代码
                            DataRow[] rows_OrganizeCity = dt_OrganizeCity.Select("Code='" + dt_Promotor.Rows[i]["管理片区代码"].ToString().Trim() + "'");
                            if (rows_OrganizeCity.Length == 0)
                            {
                                UpdateImportFlag(4, i, "导入失败,管理片区代码在系统字典中不存在!");
                                continue;
                            }
                            else
                                promotor.Model["OrganizeCity"] = rows_OrganizeCity[0]["ID"].ToString().Trim();

                            //联系电话
                            promotor.Model["TeleNum"] = dt_Promotor.Rows[i]["联系电话"].ToString().Trim();
                            if (promotor.Model["TeleNum"] == "")
                            {
                                promotor.Model["TeleNum"] = dt_Promotor.Rows[i]["手机"].ToString().Trim();
                            }

                            //手机
                            promotor.Model["Mobile"] = dt_Promotor.Rows[i]["手机"].ToString().Trim();
                            if (promotor.Model["Mobile"] == "" && promotor.Model["TeleNum"].StartsWith("1")) promotor.Model["Mobile"] = promotor.Model["TeleNum"];

                            #region 所在城市
                            string cityname = dt_Promotor.Rows[i]["城市"].ToString().Trim();
                            string areaname = dt_Promotor.Rows[i]["县城"].ToString().Trim();
                            string townname = dt_Promotor.Rows[i]["乡镇"].ToString().Trim();
                            if (townname != "")
                            {
                                DataRow[] rows_OfficialCity = dt_OfficialCity.Select("Name like '" + townname + "%'");
                                if (rows_OfficialCity.Length == 1)
                                    promotor.Model.OfficialCity = int.Parse(rows_OfficialCity[0]["ID"].ToString().Trim());
                            }
                            if (areaname != "" && promotor.Model.OfficialCity == 0)
                            {
                                DataRow[] rows_OfficialCity = dt_OfficialCity.Select("Name like '" + areaname + "%'");
                                if (rows_OfficialCity.Length == 1)
                                    promotor.Model.OfficialCity = int.Parse(rows_OfficialCity[0]["ID"].ToString().Trim());
                            }
                            if (cityname != "" && promotor.Model.OfficialCity == 0)
                            {
                                DataRow[] rows_OfficialCity = dt_OfficialCity.Select("Name like '" + cityname + "%'");
                                if (rows_OfficialCity.Length > 0)
                                    promotor.Model.OfficialCity = int.Parse(rows_OfficialCity[0]["ID"].ToString().Trim());
                            }

                            if (promotor.Model["TeleNum"] != "" && promotor.Model.OfficialCity == 0)
                            {
                                Addr_OfficialCity city = null;
                                city = Addr_OfficialCityBLL.GetCityByTeleNumOrPostCode(promotor.Model["TeleNum"]);
                                if (city != null) promotor.Model.OfficialCity = city.ID;
                            }

                            if (promotor.Model.OfficialCity == 0)
                            {
                                UpdateImportFlag(4, i, "导入失败,城市在系统字典中不存在!");
                                continue;
                            }
                            #endregion

                            //性别
                            if (dt_Promotor.Rows[i]["性别"].ToString().Trim() != "")
                            {
                                bFind = false;
                                foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("PUB_Sex").Values)
                                {
                                    if (item.Name == dt_Promotor.Rows[i]["性别"].ToString().Trim())
                                    {
                                        promotor.Model["Sex"] = item.Code;
                                        bFind = true;
                                        break;
                                    }
                                }
                                if (!bFind)
                                {
                                    UpdateImportFlag(4, i, "导入失败,性别在系统字典中不存在!");
                                    continue;
                                }
                            }

                            //分类
                            if (dt_Promotor.Rows[i]["分类"].ToString().Trim() != "")
                            {
                                bFind = false;
                                foreach (Dictionary_Data item in DictionaryBLL.GetDicCollections("PM_PromotorClassify").Values)
                                {
                                    if (item.Name == dt_Promotor.Rows[i]["分类"].ToString().Trim())
                                    {
                                        promotor.Model["Classfiy"] = item.Code;
                                        bFind = true;
                                        break;
                                    }
                                }
                                if (!bFind)
                                {
                                    UpdateImportFlag(4, i, "导入失败,分类在系统字典中不存在!");
                                    continue;
                                }
                            }

                            //家庭地址
                            promotor.Model["Address"] = dt_Promotor.Rows[i]["家庭地址"].ToString().Trim();

                            //身份证号
                            promotor.Model["IDCode"] = dt_Promotor.Rows[i]["身份证号"].ToString().Trim();

                            //上岗时间
                            if (dt_Promotor.Rows[i]["上岗时间"].ToString().Trim() != "")
                                promotor.Model["BeginWorkDate"] = dt_Promotor.Rows[i]["上岗时间"].ToString().Trim();

                            //离岗时间
                            if (dt_Promotor.Rows[i]["离岗时间"].ToString().Trim() != "")
                                promotor.Model["EndWorkDate"] = dt_Promotor.Rows[i]["离岗时间"].ToString().Trim();

                            //银行类别
                            promotor.Model["BankName"] = dt_Promotor.Rows[i]["银行类别"].ToString().Trim();

                            //工资卡号
                            promotor.Model["BankAccount"] = dt_Promotor.Rows[i]["工资卡号"].ToString().Trim();

                            //在职标志
                            promotor.Model["Dimission"] = "1";
                            promotor.Model.ApproveFlag = 1;
                            promotorid = promotor.Add();
                            if (promotorid > 0)
                            {
                                _xhs_success.Append(XH + ",");
                                //UpdateImportFlag(4, i, "导入成功,ID=" + iret.ToString());
                            }
                            else
                            {
                                UpdateImportFlag(4, i, "导入失败,写入数据库失败!");
                                continue;
                            }
                            #endregion
                        }
                        else
                        {
                            promotorid = PM_PromotorBLL.GetModelList("Code = '" + promotor.Model["Code"] + "'")[0].ID;
                        }

                        #region 促销员所在门店
                        //门店编号
                        string rtcodes = dt_Promotor.Rows[i]["门店编号"].ToString().Trim();
                        if (rtcodes != "")
                        {
                            char[] sep = { ',' };
                            string[] codes = rtcodes.Split(sep);
                            foreach (string c in codes)
                            {
                                if (string.IsNullOrEmpty(c)) continue;
                                //if (c.IndexOf('-') > 0)
                                //{
                                //    char[] sep2 = { '-' };
                                //    string[] codes2 = c.Split(sep2);

                                //    if (codes2.Length == 2)
                                //    {
                                //        int begincode, endcode;
                                //        if (int.TryParse(codes2[0], out begincode) && int.TryParse(codes2[1], out endcode))
                                //        {
                                //            for (int codexh = begincode; codexh <= endcode; codexh++)
                                //            {
                                //                string code = FormatClientCode('R', codexh.ToString(), dt_Promotor.Rows[i]["管理片区代码"].ToString().Trim());

                                //                IList<CM_Client> clients = CM_ClientBLL.GetModelList("Code='" + code + "' AND ClientType = 3");
                                //                if (clients.Count == 1)
                                //                {
                                //                    PM_PromotorInRetailerBLL pinr = new PM_PromotorInRetailerBLL();
                                //                    pinr.Model.Promotor = promotorid;
                                //                    pinr.Model.Client = clients[0].ID;
                                //                    pinr.Add();
                                //                }
                                //                else
                                //                    break;
                                //            }
                                //        }

                                //    }
                                //    else
                                //    {
                                //        string xhs = _xhs_success.ToString();
                                //        if (xhs.EndsWith(","))
                                //        {
                                //            xhs = xhs.Substring(0, xhs.Length - 1);
                                //            xhs = xhs.Substring(0, xhs.LastIndexOf(',') + 1);
                                //            _xhs_success.Remove(0, _xhs_success.Length);
                                //            _xhs_success.Append(xhs);
                                //        }
                                //        UpdateImportFlag(4, i, "导入成功,ID=" + promotorid.ToString() + ",关联所在门店失败!");
                                //        break;
                                //    }
                                //}
                                //else
                                {
                                    string code = c;

                                    IList<CM_Client> clients = CM_ClientBLL.GetModelList("Code='" + code + "' AND ClientType = 3");
                                    if (clients.Count == 1)
                                    {
                                        PM_PromotorInRetailerBLL pinr = new PM_PromotorInRetailerBLL();
                                        pinr.Model.Promotor = promotorid;
                                        pinr.Model.Client = clients[0].ID;
                                        pinr.Add();
                                    }
                                    else
                                    {
                                        string xhs = _xhs_success.ToString();
                                        if (xhs.EndsWith(","))
                                        {
                                            xhs = xhs.Substring(0, xhs.Length - 1);
                                            xhs = xhs.Substring(0, xhs.LastIndexOf(',') + 1);
                                            _xhs_success.Remove(0, _xhs_success.Length);
                                            _xhs_success.Append(xhs);
                                        }
                                        UpdateImportFlag(4, i, "导入成功,ID=" + promotorid.ToString() + ",关联所在门店失败!");
                                        break;
                                    }
                                }
                            }
                        }

                        #endregion
                    }

                    UpdateSuccess(_xhs_success.ToString(), 4);

                }
            }
            catch (System.Exception err)
            {
                UpdateSuccess(_xhs_success.ToString(), 1);
                MessageBox.Show(err.Source + "~r~n" + err.StackTrace, err.Message);
            }
            #endregion

            return;
        }