@using PageAdmin.Utils;

@functions
{
    //判断是否有权限
    private bool HasPermission(string from, string roleIds, string memberTypeIds, int roleId, int memberGroupId)
    {
        string permissionIds;
        string currentId;
        if (from == "admin")
        {
            permissionIds = roleIds;
            currentId = roleId.ToString();
        }
        else if (from == "member")
        {
            permissionIds = memberTypeIds;
            currentId = memberGroupId.ToString();
        }
        else
        {
            return true;
        }
        if (string.IsNullOrEmpty(permissionIds))
        {
            return true;
        }
        if (!permissionIds.Split(',').Contains(currentId))
        {
            return false;
        }

        return true;
    }

}

@{
    dynamic fieldData = Model;
    int forItemsNum = (int)ViewData["i"]; //父级页for循环的序号
    string from = (string)ViewData["from"];
    string guid = (string)ViewData["guid"];
    CurrentUser currentUser = (CurrentUser)ViewData["currentUser"];
    int memberGroupId = 0;
    int detailId = 0;
    if (ViewData.ContainsKey("detailId"))
    {
        detailId = (int)ViewData["detailId"];
    }
    else
    {
        detailId = StringHelper.Format<int>(Request.QueryString["id"]);
    }

    if (ViewData["memberGroupId"] != null)
    {
        memberGroupId = (int)ViewData["memberGroupId"]; //不传递则默认currentUser.MemberGroupId,后台涉及pa_member的表单建议传递memberGroupId
    }
    string fieldPrefix = "";//字段表单前缀
    if (ViewData["fieldPrefix"] != null)
    {
        fieldPrefix = (string)ViewData["fieldPrefix"];
    }

    //以上参数需要从父页面传递
    string userName = "";
    int uid = 0;
    int roleId = 0;
    string table = fieldData.TableName;
    if (currentUser != null)
    {
        userName = currentUser.UserName;
        uid = currentUser.Uid;
        roleId = currentUser.RoleId;
        if (from == "admin") //检测from合法性
        {
            if (roleId <= 0)
            {
                from = "";
            }
        }
        else if (from == "member")//检测from合法性
        {
            if (uid == 0)
            {
                from = "";
            }
        }
        //if (table == "pa_member" && detailId > 0)
        //{
        //    DataBaseContext dbContext = DbHelper.DbContext();
        //    memberGroupId = (int)(dbContext.GetField(table, "member_group_id", "id=" + detailId)??0);
        //}
        //else
        //{

        //}
        if (memberGroupId == 0)
        {
            memberGroupId = currentUser.MemberGroupId;
        }
    }
    int fieldId = fieldData.Id;
    string field = StringHelper.FirstCharUpper(fieldData.Name);
    string fieldObjName = fieldPrefix + field;
    string remark = fieldData.Remark;
    string fieldType = fieldData.FieldType;
    string fieldChildType = fieldData.FieldChildType;
    string valueType = fieldData.ValueType;
    string isMultipleSelect = fieldData.IsMultipleSelect.ToString();
    string fieldLength = fieldData.ValueLength.ToString();
    string defaultValue = fieldData.DefaultValue.ToString();
    string mustItem = fieldData.MustItem.ToString();
    string onlyItem = fieldData.OnlyItem.ToString();
    string dataType = fieldData.DataType.ToString().Trim();
    string editor_style = fieldData.EditorStyle.ToString();
    if (editor_style == "")
    {
        editor_style = "normal";
    }
    string editor_width = fieldData.EditorWidth.ToString();
    string editor_height = fieldData.EditorHeight.ToString();
    if (!StringHelper.IsInt(editor_height))
    {
        editor_height = "320";
    }
    //上传参数
    string watermark = fieldData.Watermark.ToString();
    string thumbnail = fieldData.Thumbnail.ToString();
    string thumbnailWidth = fieldData.ThumbnailWidth.ToString();
    string thumbnailHeight = fieldData.ThumbnailHeight.ToString();
    if (watermark == "1")
    {
        watermark = "true";
    }
    else
    {
        watermark = "false";
    }

    if (thumbnail == "1")
    {
        thumbnail = "true";
    }
    else
    {
        thumbnail = "false";
    }


    string upload_ext = fieldData.UploadExt.ToString();
    string upload_maxsize = fieldData.UploadMaxsize.ToString();
    string max_num = fieldData.MaxNum.ToString();

    string reName = fieldData.Rename.ToString();
    if (reName == "1")
    {
        reName = "true";
    }
    else
    {
        reName = "false";
    }


    //数据源
    string datasource_open = fieldData.DatasourceOpen.ToString();
    string datasource_table = fieldData.DatasourceTable.ToString();
    string datasource_where = fieldData.DatasourceWhere.ToString();
    string datasource_valuefield = StringHelper.FirstCharUpper(fieldData.DatasourceValueField);
    string datasource_textfield = StringHelper.FirstCharUpper(fieldData.DatasourceTextField);
    string datasource_showtype = fieldData.DatasourceShowType.ToString();
    string datasource_multilevel = fieldData.DatasourceMultiLevel.ToString();
    string datasource_onlyselect_final = fieldData.DatasourceOnlySelectFinal.ToString();

    string items = fieldData.Items.ToString();
    string[] AItems = items.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
    string[] A_AItems = new string[2];
    string memberTypeIds = fieldData.MemberGroupIds.ToString();
    string roleIds = fieldData.RoleIds.ToString();
    bool hasPermission = HasPermission(from, roleIds, memberTypeIds, roleId, memberGroupId);
    string noPerrmissionContent = fieldData.NoPermissionContent.ToString();
    string zdyContent = fieldData.ZdyContent.ToString();
    if (!string.IsNullOrWhiteSpace(zdyContent))
    {
        hasPermission = false;
        noPerrmissionContent = zdyContent;
    }
    string tips = fieldData.Tips.ToString();
    string additionalContent = fieldData.AdditionalContent.ToString();
    string beforeSubmitJs = fieldData.BeforeSubmitJs.ToString();
    string inputParams = fieldData.InputParams.ToString();
    string bt_text = fieldData.BtText.ToString();
    string win_width = fieldData.WinWidth.ToString();
    string win_height = fieldData.WinHeight.ToString();
    string pageSize = fieldData.Pagesize.ToString();
    string orderBy = fieldData.Orderby.ToString();
    string sys_field = fieldData.SysField.ToString();
    string nullMsg = remark + "不能为空!";
    if (!string.IsNullOrWhiteSpace(inputParams))
    {
        inputParams = " " + inputParams.Replace("\r\n", " ") + " ";
    }
    string addClass = "";
    string showMust = "";

    switch (fieldType)
    {

        case "select":
        case "radio":
        case "checkbox":
            nullMsg = "请选择" + remark;
            break;
        case "text":
        case "password":
        case "hidden":
            switch (valueType)
            {
                case "int":
                case "smallint":
                case "bigint":
                case "tinyint":
                case "float":
                    if (dataType == "")
                    {
                        dataType = "numeric";
                    }
                    if (defaultValue == "")
                    {
                        defaultValue = "0";
                    }
                    break;

                case "datetime":
                    var date = DateTime.Now;
                    addClass = " laydate-icon";
                    int dateLength = int.Parse(fieldLength);
                    if (dateLength == 10)
                    {
                        if (dataType == "")
                        {
                            dataType = "date";
                        }
                        inputParams += " onclick=\"laydate({istime: true,format:'YYYY-MM-DD'})\"";
                        if (defaultValue == "")
                        {
                            defaultValue = date.ToString("yyyy-MM-dd");
                        }
                    }
                    else
                    {
                        if (dataType == "")
                        {
                            dataType = "datetime";
                        }
                        inputParams += " onclick=\"laydate({istime: true,format:'YYYY-MM-DD hh:mm:ss'})\"";
                        if (defaultValue == "")
                        {
                            defaultValue = date.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                    }
                    break;

            }

            break;
            ;
        case "images":
        case "files":
            dataType = "*";
            break;

        case "subtable":
            if (dataType == "")
            {
                dataType = "numeric";
            }
            break;

        case "editor":
            if (dataType == "")
            {
                dataType = "editor";
            }
            break;
    }
    if (mustItem == "1")
    {
        if (dataType == "")
        {
            dataType = "*";
        }
        string checkUrlString = "";
        if (onlyItem == "1")
        {
            string checkUrl = Url.Action("CheckCustomField", "CheckRepeate", new { fieldId = fieldId, id = Request.QueryString["id"], area = "E" });
            checkUrlString = ",checkUrl:'" + checkUrl + "',checkError:'" + remark + "已经存在，请重新填写！'";
        }
        if (dataType == "*")
        {
            dataType = " data-validate=\"dataType:'" + dataType + "',min:1,nullMsg:'" + nullMsg + "'" + checkUrlString + "\" ";
        }
        else if (dataType == "numeric")
        {
            string minLimit = ",min:1,errorMsg:'" + nullMsg + "'";
            if (fieldType == "subtable" || fieldType == "images" || fieldType == "files")
            {
            }
            else
            {
                minLimit = ",errorMsg:'" + nullMsg + "'";
            }
            dataType = " data-validate=\"dataType:'" + dataType + "'" + minLimit + ",nullMsg:'" + nullMsg + "'" + checkUrlString + "\" ";
        }

        else
        {
            dataType = " data-validate=\"dataType:'" + dataType + "',nullMsg:'" + nullMsg + "'" + checkUrlString + "\" ";
        }
        if (inputParams.IndexOf("data-validate=") < 0)
        {
            inputParams += dataType;
        }
        showMust = "*";
    }
    else
    {
        dataType = "";
    }
    string mimeTypes = "image/jpg,image/jpeg,image/png,image/gif";
    if (fieldType == "file" || fieldType == "files")
    {
        mimeTypes = "*/*";
    }
    if (forItemsNum == 0)
    {
        <text>
            <script type="text/javascript">
                //表单全局变量
                var uid = "@uid";
                var userName = "@userName";
                var from = "@from";
                var roleId = "@roleId";
                var memberGroupId = "@memberGroupId";
            </script>
        </text>
    }
    @*if (field == "_seo")
        {
        if (hasPermission)
        {
        <div class="form-group box_seo_title">
            <label class="control-label" for="seo_title">seo标题</label>
            <div class="controls">
                <input name="seo_title" id="seo_title" type="text" maxlength="150" class="form-control">
                <span class="help-block" id="_ValidateTips_@fieldObjName"></span>
            </div>
        </div>
        <div class="form-group box_seo_keywords">
            <label class="control-label" for="seo_keywords">seo关键词</label>
            <div class="controls">
                <input name="seo_keywords" id="seo_keywords" type="text" maxlength="150" class="form-control">
                <span class="help-block" id="_ValidateTips_@fieldObjName"></span>
            </div>
        </div>
        <div class="form-group box_seo_description">
            <label class="control-label" for="seo_description">seo描述</label>
            <div class="controls">
                <textarea id="seo_description" name="seo_description" class="form-control" style="height:70px;"></textarea>
                <span class="help-block" id="_ValidateTips_@fieldObjName"></span>
            </div>
        </div>
        }
        else
        {
        @noPerrmissionContent;
        }

        }*@

    if (fieldType == "hidden")
    {
        if (hasPermission)
        {
            <input type="hidden" name="@fieldObjName" id="@fieldObjName" value="@defaultValue" maxlength="@fieldLength" @Html.Raw(inputParams)>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "text" || fieldType == "password")
    {
        if (hasPermission)
        {
            <div class="form-group">
                <label class="control-label" for="@fieldObjName">@remark@showMust</label>
                <div class="controls">
                    <input type="@fieldType" name="@fieldObjName" id="@fieldObjName" value="@defaultValue" maxlength="@fieldLength" class="form-control@(addClass)" @Html.Raw(inputParams)>
                    @Html.Raw(additionalContent)
                    <span class="help-block" id="_ValidateTips_@fieldObjName">@Html.Raw(tips)</span>
                </div>
            </div>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "select")
    {
        string options = "";
        if (hasPermission)
        {
            for (int i = 0; i < AItems.Length; i++)
            {
                if (AItems[i].Split(',').Length == 2)
                {
                    A_AItems = AItems[i].Split(',');
                }
                else
                {
                    A_AItems[0] = AItems[i];
                    A_AItems[1] = AItems[i];
                }
                if (A_AItems[0] == "" && A_AItems[1] == "") { continue; }
                options += "<option value=\"" + A_AItems[0] + "\">" + A_AItems[1] + "</option>";
            }
            <div class="form-group">
                <label class="control-label" for="@fieldObjName">@remark@showMust</label>
                <div class="controls @if(isMultipleSelect == "0"){<text>form-inline</text>}">
                    @if (datasource_open == "1" && datasource_table != "" && datasource_valuefield != "" && datasource_textfield != "" && datasource_showtype != "0")
                    {
                        <select name="@fieldObjName" id="@fieldObjName" @if (isMultipleSelect == "1") { <text> multiple="multiple" </text> } class="@if(isMultipleSelect == "1"){<text>multiple-select </text>}form-control ui-convertSelect @(addClass)" @Html.Raw(inputParams) data-custom-params="url:'/E/SelectData/LoadData?fieldId=@fieldId',textField:'@datasource_textfield'">
                            @Html.Raw(options)
                        </select>
                        <div class="btn-group btn-group-sm">
                            <a href="javascript:void(0)" class="btn btn-default btn-sm ui-dialog" data-custom-params="title:'@(remark)',url:'/E/SelectData/Select?fieldId=@fieldId&objName=@Server.UrlEncode("#"+fieldObjName)',width:'@win_width',height:'@win_height',target:'self'">@Html.Raw(bt_text)</a>
                            @if (isMultipleSelect == "1")
                            {<a href="javascript:void(0)" class="btn btn-default btn-sm ui-removeSelectedOptions" title="按住Ctrl键可实现多选" data-custom-params="obj:'#@fieldObjName'">删除选中</a>
                            }
                        </div>
                    }
                    else
                    {
                        <select name="@fieldObjName" id="@fieldObjName" @if (isMultipleSelect == "1") { <text> multiple="multiple" </text> } class="@if(isMultipleSelect == "1"){<text>multiple-select </text>}form-control@(addClass)" @Html.Raw(inputParams)>
                            @Html.Raw(options)
                        </select>
                    }
                    @Html.Raw(additionalContent)
                    <span class="help-block" id="_ValidateTips_@fieldObjName">@Html.Raw(tips)</span>
                </div>
            </div>
            if (datasource_open == "1" && datasource_table != "" && datasource_valuefield != "" && datasource_textfield != "")
            {
                string onlySelectFinal = "false";
                string isTree = "false";
                if (datasource_multilevel == "1")
                {
                    isTree = "true";
                }
                if (datasource_onlyselect_final == "1")
                {
                    onlySelectFinal = "true";
                }
                if (datasource_showtype == "0")
                {
                    <text>
                        <script type="text/javascript">
                        //填充下拉
                        var fillParams={type:"get",async:false,url:"/E/SelectData/ListData?fieldId=@fieldId",valueField:"@(datasource_valuefield)",textField:"@(datasource_textfield)",isTree:@isTree,onlySelectFinal:@onlySelectFinal};
                        $("#@fieldObjName").SelectBind(fillParams);
                        </script>
                    </text>
                }
            }
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }

    }
    //radio或ckeckbox
    else if (fieldType == "radio" || fieldType == "checkbox")
    {
        if (hasPermission)
        {
            <div class="form-group">
                <label class="control-label" for="@fieldObjName">@remark@showMust</label>
                <div class="controls checkbox">
                    @for (int i = 0; i < AItems.Length; i++)
                    {
                        string defaultChecked = "";
                        if (AItems[i].Split(',').Length == 2)
                        {
                            A_AItems = AItems[i].Split(',');
                        }
                        else
                        {
                            A_AItems[0] = AItems[i];
                            A_AItems[1] = AItems[i];
                        }
                        if (A_AItems[0] == "" && A_AItems[1] == "") { continue; }
                        if (fieldType == "radion")
                        {
                            defaultChecked = defaultValue == A_AItems[0] ? "checked" : "";
                        }
                        else if (defaultValue.Split(',').Contains(A_AItems[0]))
                        {
                            defaultChecked = " checked";
                        }
                        <label class="@fieldType-inline">
                            <input type="@fieldType" name="@fieldObjName" id="@fieldObjName" @defaultChecked value="@A_AItems[0]" @Html.Raw(inputParams)>@(A_AItems[1])
                        </label>
                    }
                    @Html.Raw(additionalContent)
                    <span class="help-block" id="_ValidateTips_@fieldObjName">@Html.Raw(tips)</span>
                </div>
            </div>

        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }

    }
    //textarea
    else if (fieldType == "textarea")
    {
        if (hasPermission)
        {
            <div class="form-group">
                <label class="control-label" for="@fieldObjName">@remark@showMust</label>
                <div class="controls">
                    <textarea name="@fieldObjName" id="@fieldObjName" class="form-control textarea" @Html.Raw(inputParams)></textarea>
                    @Html.Raw(additionalContent)
                    <span class="help-block" id="_ValidateTips_@fieldObjName">@Html.Raw(tips)</span>
                </div>
            </div>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }

    }
    else if (fieldType == "editor")
    {
        if (hasPermission)
        {
            <div class="form-group">
                <label class="control-label" for="@fieldObjName">@remark@showMust</label>
                <div class="controls">
                    <textarea id="@fieldObjName" name="@fieldObjName" @Html.Raw(inputParams)></textarea>
                    <script type="text/javascript">
                    var _ueditor_@(fieldObjName)=UE.getEditor("@(fieldObjName)",
                        {
                            initialFrameWidth: null,
                            @*,initialFrameWidth:"@editor_width" , //初始化编辑器宽度,默认1000*@
                            initialFrameHeight:@editor_height,  //初始化编辑器高度,默认320
                            toolbars: _UeditorZdyConfig.@(editor_style)
                        });
                    _ueditor_@(fieldObjName).ready(function() {
                        var $formObj=$("#@fieldObjName").parents("form").eq(0);
                        var $guid=$formObj.find("#Guid");
                        if($formObj.length>0 && $guid.length>0)
                        {
                            var guid=$guid.val();
                            _ueditor_@(fieldObjName).execCommand("serverparam", {
                                "guid":guid,
                                "tableName":"@table",
                                "fieldName":"@field",
                                });
                        }
                    });
                    </script>

                    @if (sys_field == "1" && from == "admin" && field == "content")
                    {
                        <!--<div style='text-align:left;padding-top:3px' class="form-inline btn-group btn-group-sm ">
                            <button type="button" class="btn btn-sm btn-default" onclick="TakeImage(this,'savehttpimage','@table','@fieldObjName')">下载远程图片</button>
                            <button type="button" class="btn btn-sm btn-default" onclick="TakeImage(this,'savehttpimage','@table','@fieldObjName')">内容附件管理</button>
                        </div>;-->
                    }
                    @Html.Raw(additionalContent)
                    <span class="help-block" id="_ValidateTips_@fieldObjName">@Html.Raw(tips)</span>
                </div>
            </div>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }

    }
    if (fieldType == "image" || fieldType == "file")
    {
        if (hasPermission)
        {
            <div class="form-group ">
                <label class="control-label" for="@fieldObjName">@remark@showMust</label>
                <div class="controls">
                    <div class="input-group">
                        <input type="text" name="@fieldObjName" id="@fieldObjName" maxlength="@fieldLength" class="form-control ui-uploadPanel @(addClass)" data-upload-params="tableName:'@table',fieldName:'@fieldObjName',fileType:'@fieldType',mimeTypes:'@mimeTypes',fileNumLimit:1,fileSingleSizeLimit:'@upload_maxsize',extensions:'@upload_ext',watermark:'@watermark',rename:@(reName)@if (fieldType == "image"){<text>,thumbnail: '@thumbnail',thumbnailWidth: '@thumbnailWidth',thumbnailHeight: '@thumbnailHeight'</text>}" @Html.Raw(inputParams)>
                        @Html.Raw(additionalContent)
                    </div>
                    <span class="help-block" id="_ValidateTips_@fieldObjName">@Html.Raw(tips)</span>
                </div>
            </div>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "images" || fieldType == "files")
    {
        if (hasPermission)
        {
            <div class="form-group">
                <label class="control-label" for="@fieldObjName">@remark@showMust</label>
                <div class="controls">
                    <input type="hidden" name="@fieldObjName" id="@fieldObjName" readonly maxlength="@fieldLength" data-formBind="false" value="@Html.GetAttachmentsFieldJson(fieldId,detailId)" class="form-control ui-uploadPanel @(addClass)" data-upload-params="tableName:'@table',fieldName:'@fieldObjName',fileType:'@fieldType',fileNumLimit:@max_num,mimeTypes:'@mimeTypes',fileSingleSizeLimit:'@upload_maxsize',extensions:'@upload_ext',watermark:'@watermark',rename:@(reName)@if (fieldType == "images"){<text>,thumbnail: '@thumbnail',thumbnailWidth: '@thumbnailWidth',thumbnailHeight: '@thumbnailHeight'</text>}" @Html.Raw(inputParams)>
                    @Html.Raw(additionalContent)
                    <span class="help-block" id="_ValidateTips_@fieldObjName">@Html.Raw(tips)</span>
                </div>
            </div>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "subtable")
    {
        string subTable = table + "_" + field;
        if (hasPermission)
        {
            <div class="form-group">
                <label class="control-label" for="@fieldObjName">@remark@showMust</label>
                <div class="controls">
                    <input type="hidden" name="@fieldObjName" id="@fieldObjName" class="ui-changeTrigger" data-triggerObj="#_@(field)_recordCount" data-formBind="false" value="@Html.SubDataCount(fieldId,detailId)" @Html.Raw(inputParams)>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-default btn-sm ui-dialog" data-custom-params='title:"@(remark)",url:"/E/SubData/@(fieldChildType=="multiple"?"":"Set")?parentguid=@guid&parentId=@detailId&_fieldId=@fieldId&_from=@from",width:"@win_width",height:"@win_height",target:"self"'>@(bt_text)</button>
                        <button type="button" class="btn btn-default btn-sm" id="_@(@fieldObjName)_recordCount">0</button>
                    </div>
                    @Html.Raw(additionalContent)
                    <span class="help-block" id="_ValidateTips_@fieldObjName">@Html.Raw(tips)</span>
                </div>
            </div>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
}