<%@ Control Language="C#" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.Config" %>
<%@ Import Namespace="Kesion.Components" %>
<%@ Import Namespace="Kesion.HtmlTags" %>
<%@ Import Namespace="Kesion.UCenter" %>
<%@ Import Namespace="Kesion.XML" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<script runat="server" type="text/C#">

    dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息，

    public StringBuilder sb = new StringBuilder();
    public StringBuilder tags = new StringBuilder();
    private string noShowField = "realname,sex,mobile";
    public string diyTemplate = string.Empty;
    bool isLoadPage = true;  //定义页面是否加载
    public string tagsids = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (__user.GroupID == 4)
        {
            Response.Redirect(BasicField.GetUserUrl("teacher/teacher"));
        }
        else if (__user.GroupID == 3)
        {
            Response.Redirect(BasicField.GetUserUrl("School/UserEnterprise"));
        }
        if (KSCMS.S("action") == "dosave")
        {
            isLoadPage = false;
            DoSave();
            return;
        }
        string sql = "select top 1 tagsids from ks_user where userid=" + __user.UserID;
        using (DataTable dt = DataFactory.GetDataTable(sql))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                tagsids = dr["tagsids"].ToString();
           
               
            }
        }
        
        diyTemplate = initialUserTemplate();

    }
    public string GetBusiness(string nametype, int num, int status)
    {
        #region 经营范围
        StringBuilder sb = new StringBuilder();
        using (DataTable dt = DataFactory.GetDataTable("select top 1000 * from KS_KeyTags where status=1 and type=1 order by FirstAlphabet"))
        {
            nametype = ',' + nametype + ",";
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string str = string.Empty;

                    if (nametype.IndexOf("," + dr["tagsid"].ToString() + ",") != -1)
                    {
                        sb.AppendFormat(@"<option value ={0} selected = 'selected' >{1}</option>", dr["tagsid"].ToString(), str + dr["KeyText"].ToString());

                    }
                    else
                    {
                        sb.AppendFormat(@"<option value ='{0}' >{1}</option>", dr["tagsid"].ToString(), str + dr["KeyText"].ToString());
                    }
                }
            }
        }      
        return sb.ToString();
        #endregion
    }
    private void DoSave()
    {
        #region 保存用户资料
        string email = Utils.ChkSQL(Utils.RemoveXss(KSCMS.S("email")));
        string userface = "/UploadFiles/avatar/"+new TemporaryVar().UserID+".jpg";
        string realName = Utils.ChkSQL(Utils.RemoveXss(KSCMS.S("realName")));
        string sex = Utils.ChkSQL(KSCMS.S("sex"));
        if (string.IsNullOrEmpty(realName))
        {
            Msg.Alert("请输入您的真实姓名!");
            return;
        }
     
        //检查电子邮件是否被注册
        if (!string.IsNullOrEmpty(email))
        {
            if (MyCache.GetCacheConfig(37) == "0")
            {
                if (DataFactoryUser.Exists("KS_User", "username<>'" + __user.UserName+ "' and (username='" + email + "' or email='" + email + "')"))
                {
                    Msg.Alert("对不起，您输入的电子邮件已绑定了其它会员账号!");
                    return;
                }
            }
        }


        DataFactoryUser.ExecuteNonQuery("update ks_user set tagsids='" +Utils.ChkSQL(KSCMS.S("TagsIDS")) + "' , ProID=" + Utils.StrToInt(KSCMS.S("ProvinceID")) + ",CityID=" + Utils.StrToInt(KSCMS.S("CityID")) + ",CountyID=" + Utils.StrToInt(KSCMS.S("CountyID")) + ",realname='" + Utils.ChkSQL(realName) + "',sex='" + Utils.ChkSQL(sex) + "',userface='" + Utils.ChkSQL(userface) + "',email='" + Utils.ChkSQL(email) + "' where  username='" + Utils.ChkSQL(__user.UserName) + "'");
        #region 整合Ucenter
        if (MyCache.GetShopCommonConfig(84) == "1")
        {
            if (!string.IsNullOrEmpty(email))  //更新邮箱
            {
                new ucenter().UpataPass(new TemporaryVar().UserName, string.Empty, string.Empty, email);
            }
        }
        #endregion

        #region 判断数据合法性
        string FieldNameList = DataFactoryUser.GetOnlyValue("select FieldNameList from ks_userform where formid=(select formid from ks_usergroup where groupid=" + UserManage.GetUserInfo().GroupID + ")");

        string xmlStr = string.Empty;
        using (DataTable dt = DataFactoryUser.GetDataTable("select top 1 * From KS_UserConfig"))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                xmlStr = dr["userfield"].ToString();
            }
            else
            {
                Msg.Alert("找不到会员配置表，请检查！");
                return;
            }
        }
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(xmlStr);
        string FieldsXML = XmlObject.XMLToString(ref xmldoc);

        string[] F_Arr = FieldNameList.Split(',');
        string mustUpdateField = string.Empty;
        foreach (string FieldName in F_Arr)
        {
            string MustFillItem = string.Empty;
            string FieldAlias = string.Empty;
            string FieldType = string.Empty;
            if (Utils.InArray(FieldName.ToLower(), noShowField, ",") == false)
            {
                if (string.IsNullOrEmpty(mustUpdateField))
                {
                    mustUpdateField = FieldName;
                }
                else
                {
                    mustUpdateField += "," + FieldName;
                }
                FieldAlias = XmlObject.GetStrXmlNode(FieldsXML, "//UserField/Field[@Name='" + FieldName + "']/FieldAlias");
                FieldType = XmlObject.GetStrXmlNode(FieldsXML, "//UserField/Field[@Name='" + FieldName + "']/FieldType");
                MustFillItem = XmlObject.GetStrXmlNode(FieldsXML, "//UserField/Field[@Name='" + FieldName + "']/MustFillItem");
                if (MustFillItem == "1" && KSCMS.S(FieldName) == null)
                {
                    Utils.ShowError(FieldAlias + "必须输入!", 0);
                    break;
                }
                else
                {

                    switch (FieldType)
                    {
                        case "7":
                            try
                            {
                                Convert.ToDateTime(KSCMS.S(FieldName));
                            }
                            catch
                            {
                                Msg.Alert(FieldAlias + "格式不正确，请输入正确的日期格式!");
                                return;
                            }
                            break;
                        case "8":
                            if (Utils.IsNumber(KSCMS.S(FieldName)) == false)
                            {
                                Msg.Alert(FieldAlias + "格式不正确，请输入正确的数字!");
                                return;
                            }
                            break;
                        case "9":
                            if (Utils.IsValidEmail(KSCMS.S(FieldName)) == false)
                            {
                                Msg.Alert(FieldAlias + "格式不正确，请输入正确的邮箱格式!");
                                return;
                            }
                            break;

                    }
                }
            }
        }
        #endregion

        if (!string.IsNullOrEmpty(mustUpdateField))
        {
            UserManage.UpdateUserDefineField(FieldsXML, mustUpdateField, __user.UserID);
        }
        UserManage.CleanUserCache(__user.UserID);
        Msg.Alert("恭喜，用户资料修改成功!",KSCMS.GetComeUrl());
        #endregion
    }

    private  string initialUserTemplate()
    {
        #region 自定义字段
        string FieldsXML = string.Empty;
        using (DataTable dt = DataFactoryUser.GetDataTable("select top 1 * From KS_UserConfig"))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                FieldsXML = dr["userfield"].ToString();
            }
            else
            {
                JS.Alert("找不到会员配置表，请检查！");
            }
        }
        string template = UserFormManage.GetFormTemplateByGroupID(UserManage.GetUserInfo().GroupID);
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(FieldsXML);
        XmlNode xn = xmldoc.SelectSingleNode("UserField");
        XmlNodeList xnl = xn.ChildNodes;

        using (DataTable dt = DataFactoryUser.GetDataTable("select top 1 * from ks_user where password='" + KSCMS.Filter(KSCMS.GetCookie("User", "Password")) + "' and username='" + KSCMS.Filter(__user.UserName) + "'"))
        {

            foreach (XmlNode xnf in xnl)
            {
                XmlElement xe = (XmlElement)xnf;
                string FieldID = xe.GetAttribute("Name");
                if (Utils.InArray(FieldID.ToLower(), noShowField, ",") == false)
                {
                    int FieldType = Utils.StrToInt(xe.GetElementsByTagName("FieldType").Item(0).InnerText);
                    int FieldWidth = Utils.StrToInt(xe.GetElementsByTagName("FieldWidth").Item(0).InnerText);
                    if (FieldWidth == 0) FieldWidth = 200;
                    int FieldHeight = Utils.StrToInt(xe.GetElementsByTagName("FieldHeight").Item(0).InnerText);
                    string WidthStr = string.Empty;
                    if (FieldWidth > 0) WidthStr = "width:" + FieldWidth + "px;";
                    string HeightStr = string.Empty;
                    if (FieldHeight > 0) HeightStr = "height:" + FieldHeight + "px;";

                    string DefaultValue;
                    if (dt.Rows.Count > 0)
                        DefaultValue = dt.Rows[0][FieldID].ToString();
                    else
                        DefaultValue = xe.GetElementsByTagName("DefaultValue").Item(0).InnerText;
                    string Options = xe.GetElementsByTagName("Options").Item(0).InnerText;
                    string FieldAlias = xe.GetElementsByTagName("FieldAlias").Item(0).InnerText;
                    int MustFillItem = Utils.StrToInt(xe.GetElementsByTagName("MustFillItem").Item(0).InnerText);
                    if (MustFillItem == 1)
                    {
                        sb.AppendLine(string.Format(@"if ($(""#{0}"").val()==''){{
                        KesionJS.Alert('{1}必须输入!', '$(""#{0}"").focus();');
                    return false;
                }}", FieldID, FieldAlias));
                    }

                    string InputStr = string.Empty;
                    switch (FieldType)
                    {
                        case 7:
                            InputStr = string.Format(@"&nbsp;<input onclick=""WdatePicker({{dateFmt:'yyyy-MM-dd'}});""  class=""textbox Wdate"" type=""text"" id=""{0}"" name=""{0}"" style=""{1}"" value=""{2}"">", FieldID, WidthStr, DefaultValue);
                            break;
                        case 1:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                            InputStr = string.Format(@"&nbsp;<input  class=""textbox"" type=""text"" id=""{0}"" name=""{0}"" style=""{1}"" value=""{2}"">", FieldID, WidthStr, DefaultValue);
                            break;
                        case 2:
                            InputStr = string.Format(@"&nbsp;<textarea name=""{0}"" id=""{0}"" style=""{1}{2}"">{3}</textarea>", FieldID, WidthStr, HeightStr, DefaultValue);
                            break;
                        case 3:
                            InputStr = string.Format(@"<textarea name=""{0}"" id='{0}'  style='{2}{3}' />{1}</textarea>", FieldID, DefaultValue, WidthStr, HeightStr);
                            InputStr += Kesion.APPCode.EditorAPI.EchoEditor("editor" + FieldID, FieldID, "Basic", 0, false, false, true,false);
                            break;
                        case 4:
                            InputStr = string.Format(@"&nbsp;<select name=""{0}"" id=""{0}"" style=""{1}"">{2}</select>", FieldID, WidthStr, UtilsForms.SelectOption(Options, DefaultValue));
                            break;
                        case 5:
                            InputStr = UtilsForms.Radio(FieldID, Options, DefaultValue);
                            break;
                        case 6:
                            InputStr = UtilsForms.CheckBox(FieldID, Options, DefaultValue);
                            break;

                    }
                    if (FieldType == 10 || FieldType == 11)
                    {
                        InputStr = @"" + InputStr + @"<span style=""display:block;width:145px;float:right;"">&nbsp;" + string.Format(@"<iframe src=""/plus/include/UpLoad.aspx?FieldID={0}&channelid=10001&CreateThumbs=0"" scrolling=""no"" id=""upframe"" name=""upframe"" width=""100%"" frameborder=""no"" height=""32""></iframe>", FieldID) + "</span>";
                    }
                    template = template.Replace(string.Format("[@{0}]", FieldID), InputStr);
                }
                else
                {
                    template = Utils.ReplaceString(template, @"class=""tr_" + FieldID.ToLower() + @"""", " style='display:none'",true);
                }

            }
        }
        return template;
        #endregion
    }


</script>
<%
    if (!isLoadPage) return;
%>
<script type="text/javascript" src="<%=ResolveUrl("~/KS_Inc/DatePicker/WdatePicker.js") %>"></script>
    <% Kesion.APPCode.EditorAPI.EchoHead();%>
<script>
    function checkform() {
        if ($("#RealName").val() == '') {
            $.dialog.alert('请输入您的真实姓名!', function() {
                $("#RealName").focus();
            });
            return false;
        }
        <%=sb.ToString()%>
        return true;
    }
</script>

	<div class="t_tybox nomar">
        <div class="r_title">
            <h4>基本信息</h4>
            <div class="tabs">	
    			<ul class="clearfix">
                    <li class='puton'><a href="<%=BasicField.GetUserUrl("basic/editinfo") %>">修改我的资料</a></li>
                    <li><a href="<%=BasicField.GetUserUrl("basic/userface") %>">上传头像</a></li>
                    <li><a href="<%=BasicField.GetUserUrl("basic/editpass") %>">修改密码</a></li>
                    <li><a href="<%=BasicField.GetUserUrl("basic/editquestion") %>">修改安全问题</a></li>
                    <li><a href="<%=BasicField.GetUserUrl("basic/mobilebind") %>">第三方绑定</a></li>
                    <li><a href="<%=BasicField.GetUserUrl("Shop/MyAddress") %>">收货人地址</a></li>
                   
    			</ul>
            </div>
        </div>

      <iframe src="about:blank" name="hidframe" style="display:none;width:0px;height:0px"></iframe>
      <form name="myform" action="{$GetCurrUrl}" method="post" id="myform" target="hidframe">
       <input type="hidden" name="action" value="dosave"/>
         <table  class="border border_bottom" width="100%" align="center" border="0">
                <tr class="tdbg">
                 <td class="lefttd w120">用户名称：</td>
                 <td style="text-align:left"><%=__user.UserName %></td>
                </tr>
        
                <tr class="tdbg">
                <td class="lefttd w120">电子邮箱：</td>
                <td style="text-align:left"><input type="text" name="Email" id="Email" class="textbox" maxlength="100" value="<%=__user.Email %>"><span class="tips">请输入您的邮箱地址。</span></td>
                </tr>
                <tr class="tdbg">
                <td class="lefttd w120">真实姓名：</td>
                <td style="text-align:left"><input type="text" name="RealName" id="RealName" class="textbox" maxlength="20" value="<%=__user.RealName %>"><span class="tips">请输入您的真实姓名。</span></td>
                </tr>       
                <tr class="tdbg">
                <td class="lefttd w120">所在地区：</td>
                <td style="text-align:left">
                    <%=string.Format(@"<script src='/plus/area.aspx?classname=textbox&pid={0}&cityid={1}&countyid={2}'></script>", __user.ProID, __user.CityID, __user.CountyId) %>
                </td>
                </tr>
                <tr class="tdbg">
                 <td class="lefttd w120">绑定手机：</td>
                 <td style="text-align:left">
                 <%if (string.IsNullOrEmpty(__user.Mobile))
                   {
                       Response.Write("未绑定");
                   }
                   else
                   {
                       Response.Write(__user.Mobile);
                   } %>
                 <span class="tips"><a href="<%=BasicField.GetUserUrl("basic/mobilebind") %>" style="font-weight:bold">绑定管理</a></span></td>
                </tr>
                <tr class="tdbg">
                    <td class="lefttd w120">性别：</td>
                     <td style="text-align:left">
                         <label><input type="radio" class="radiobtn" name="sex" value="男" <%=(__user.Sex=="男"|| string.IsNullOrEmpty(__user.Sex))?" checked":"" %>/>男</label>&nbsp;&nbsp;
                          <label><input type="radio" class="radiobtn" name="sex" value="女" <%=__user.Sex=="女"?" checked":"" %>/>女</label>
                     </td>
                </tr>
                <tr class="tdbg  border-bottom" >
             <td class="lefttd w120">我的标签：</td>
            <td>
                   <%
                           tags.AppendFormat(@"<select name=""tagsids"" id=""prolist1"" style='width:100px;text-align:left;' multiple=""true""  >{0}</select>", GetBusiness(tagsids, 1, 0)); //  0面授，0状态
                          KSCMS.W(tags.ToString());
						  %>
	                </td>
                </tr>
             <tr  class="tdbg nopadding" <%=diyTemplate==""?"style='display:none'":"" %>>
                  <td colspan="2">
                     <div class="tytitle title-style">其他选项：</div>
                     <div class="reg_box_l" >
                       <ul id="diyoption"><%=diyTemplate %></ul>
                     </div>
                  </td>
                </tr>
         </table>
        
          <div class="cz_btn ">
              <div class="d-inline-block">
                  <span><input type="submit" ID="Button1" onclick="return(checkform())" class="green-bt bt-w-auto"  value="OK,提交修改" /></span>
                  <span style="display:none"><input type="reset" class="grey-bt" value="重新录入" /></span>
              </div>
          </div>

      </form>

</div>