@using PageAdmin.Utils;
@functions
{
    //判断是否有权限HasPermission
    private bool HasPermission(PageAdmin.Common.FromEnum from, string canRoleIds, string canMemberGroupIds, CurrentUser currentUser)
    {
        string permissionIds;
        HashSet<string> currentIds;
        if (from == PageAdmin.Common.FromEnum.Admin)
        {
            if (currentUser.IsSuperAdmin)
            {
                return true;
            }
            permissionIds = canRoleIds;
            currentIds = new HashSet<string>(currentUser.RoleIds.Split(','));
        }
        else if (from == PageAdmin.Common.FromEnum.Member)
        {
            permissionIds = canMemberGroupIds;
            currentIds = new HashSet<string>();
            currentIds.Add(currentUser.MemberGroupId.ToString());
        }
        else
        {
            return true;
        }
        if (string.IsNullOrEmpty(permissionIds))
        {
            return true;
        }
        if (!permissionIds.Split(',').All(id => currentIds.Contains(id)))
        {
            return false;
        }

        return true;
    }
}
@{
    dynamic fieldData = Model;
    PageAdmin.Common.FromEnum from = (PageAdmin.Common.FromEnum)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;
    string roleIds = "";
    string table = fieldData.TableName;
    if (currentUser != null)
    {
        userName = currentUser.UserName;
        uid = currentUser.Uid;
        roleIds = currentUser.RoleIds;
        if (from == PageAdmin.Common.FromEnum.Admin) //检测from合法性
        {
            if (currentUser.IsSuperAdmin || !string.IsNullOrEmpty(roleIds))
            {
                //from = PageAdmin.Common.FromEnum.Guest;
            }
            else
            {
                from = PageAdmin.Common.FromEnum.Guest;
            }
        }
        else if (from == PageAdmin.Common.FromEnum.Member)//检测from合法性
        {
            if (uid == 0)
            {
                from = PageAdmin.Common.FromEnum.Guest;
            }
        }
        //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;
        }
    }
    else
    {
        currentUser = new CurrentUser();
    }

    int fieldId = fieldData.Id;
    string field = StringHelper.FirstCharUpper(fieldData.Name);
    string fieldObjName = field;
    string modelName = field;
    if (fieldPrefix != "")
    {
        fieldObjName = fieldPrefix + "_" + field;
        modelName = fieldPrefix + "." + field;
    }
    string remark = fieldData.Remark;
    string fieldType = fieldData.FieldType;
    string subTableType = fieldData.SubTableType;
    string valueType = fieldData.ValueType;
    string isMultipleSelect = StringHelper.Format<string>(fieldData.IsMultipleSelect);
    int fieldLength = StringHelper.Format<int>(fieldData.ValueLength);
    string defaultValue = StringHelper.Format<string>(fieldData.DefaultValue);

    string mustItem = StringHelper.Format<string>(fieldData.MustItem);
    string onlyItem = StringHelper.Format<string>(fieldData.OnlyItem);
    string dataType = StringHelper.Format<string>(fieldData.DataType).Trim();
    string editor_style = StringHelper.Format<string>(fieldData.EditorStyle);
    if (editor_style == "")
    {
        editor_style = "normal";
    }
    string editor_width = StringHelper.Format<string>(fieldData.EditorWidth);
    string editor_height = StringHelper.Format<string>(fieldData.EditorHeight);
    if (!StringHelper.IsInt(editor_height))
    {
        editor_height = "320";
    }
    //上传参数
    string watermark = StringHelper.Format<string>(fieldData.Watermark);
    string thumbnail = StringHelper.Format<string>(fieldData.Thumbnail);
    string thumbnailWidth = StringHelper.Format<string>(fieldData.ThumbnailWidth);
    string thumbnailHeight = StringHelper.Format<string>(fieldData.ThumbnailHeight);
    if (watermark == "1")
    {
        watermark = "true";
    }
    else
    {
        watermark = "false";
    }

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


    string upload_ext = StringHelper.Format<string>(fieldData.UploadExt);
    string upload_maxsize = StringHelper.Format<string>(fieldData.UploadMaxsize);
    int uploadImageMaxWidth= StringHelper.Format<int>(fieldData.MaxImageWidth);
    if (upload_maxsize == null)
    {
        upload_maxsize = "1024";
    }
    string max_num = StringHelper.Format<string>(fieldData.MaxNum);
    if (fieldType == "image" || fieldType == "file")
    {
        max_num = "1";
    }
    string reName = StringHelper.Format<string>(fieldData.Rename);
    if (reName == "1")
    {
        reName = "true";
    }
    else
    {
        reName = "false";
    }

    //数据源
    string datasource_open = StringHelper.Format<string>(fieldData.DatasourceOpen);
    string datasource_table = StringHelper.Format<string>(fieldData.DatasourceTable);
    string datasource_valuefield = "id";
    string datasource_textfield = StringHelper.FirstCharUpper(fieldData.TextField);
    string datasource_textFieldName =fieldData.TextFieldName;
    string datasource_selectDataType = StringHelper.Format<string>(fieldData.SelectDataType);
    string datasource_multilevel = StringHelper.Format<string>(fieldData.IsMultiLevelTable);
    string datasource_onlyselect_final = StringHelper.Format<string>(fieldData.OnlySelectFinal);

    //权限
    string memberTypeIds = StringHelper.Format<string>(fieldData.MemberGroupIds);
    roleIds = StringHelper.Format<string>(fieldData.RoleIds);
    bool hasPermission = HasPermission(from, roleIds, memberTypeIds, currentUser);


    string noPerrmissionContent = StringHelper.Format<string>(fieldData.NoPermissionContent);
    string zdyContent = StringHelper.Format<string>(fieldData.ZdyContent);
    string tips = StringHelper.Format<string>(fieldData.Tips);
    string additionalContent = StringHelper.Format<string>(fieldData.AdditionalContent);
    string beforeSubmitJs = StringHelper.Format<string>(fieldData.BeforeSubmitJs);
    string zdyParams = StringHelper.Format<string>(fieldData.InputParams);
    string elFormItemParams = ""; //容器属性
    string inputParams = ""; //表单属性
    string bt_text = StringHelper.Format<string>(fieldData.BtText);
    string win_width = StringHelper.Format<string>(fieldData.WinWidth);
    string win_height = StringHelper.Format<string>(fieldData.WinHeight);
    string pageSize = StringHelper.Format<string>(fieldData.Pagesize);
    string orderBy = StringHelper.Format<string>(fieldData.Orderby);
    string sys_field = StringHelper.Format<string>(fieldData.SysField);
    string nullMsg = remark + "不能为空!";
    string errorMsg = remark + "数据格式错误!";
    string vValidate = "";
    if (!string.IsNullOrWhiteSpace(zdyParams))
    {
        string[] inputParamsArray = zdyParams.Split(new string[] { "\n" }, StringSplitOptions.None);
        foreach (string param in inputParamsArray)
        {
            string paramString = param.Trim();
            if (string.IsNullOrEmpty(paramString))
            {
                continue;
            }
            if (paramString.StartsWith("row:"))
            {
                elFormItemParams += " " + paramString.Substring(4);
            }
            else
            {
                inputParams += " " + paramString;
            }
        }
    }
    string addClass = "";
    string showMust = "";
    switch (valueType)
    {
        case "int":
        case "smallint":
        case "bigint":
        case "tinyint":
        case "float":
            if (dataType == "")
            {
                dataType = "numeric";
            }
            if (defaultValue == "")
            {
                defaultValue = "0";
            }
            break;
        case "datetime":
            if (dataType == "")
            {
                dataType = "datetime";
            }
            break;
    }

    string options = null;

    switch (fieldType)
    {
        case "select":
        case "radio":
        case "checkbox":
            nullMsg = "请选择" + remark;
            break;
        case "datepicker":
            var date = DateTime.Now;
            if (string.IsNullOrWhiteSpace(defaultValue))
            {
                defaultValue = date.ToString("yyyy-MM-dd HH:mm:ss");
            }
            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")
        {//改到服务器端检测
        }
        if (dataType == "*")
        {
            vValidate = " v-validate=\"{data:" + modelName + ",dataType:'" + dataType + "',maxLength:" + fieldLength + ",nullMsg:'" + nullMsg + "'" + checkUrlString + ",ignoreHidden:true}\" ";
        }
        else if (dataType == "editor")
        {
            vValidate = " v-validate=\"{data:" + modelName + ",dataType:'" + dataType + "',maxLength:" + fieldLength + ",nullMsg:'" + nullMsg + "'" + checkUrlString + ",ignoreHidden:false}\" ";
        }
        else if (dataType == "numeric")
        {
            string minLimit = ",errorMsg:'" + remark + "填写错误，只能填写数字!'";
            if (fieldType == "subtable" || fieldType == "images" || fieldType == "files")
            {
            }
            vValidate = " v-validate=\"{data:" + modelName + ",maxLength:" + fieldLength + ",dataType:'" + dataType + "'" + minLimit + ",nullMsg:'" + nullMsg + "'" + checkUrlString + ",ignoreHidden:true}\" ";
        }
        else
        {
            vValidate = " v-validate=\"{data:" + modelName + ",maxLength:" + fieldLength + ",dataType:'" + dataType + "',nullMsg:'" + nullMsg + "'" + checkUrlString + ",ignoreHidden:true}\" ";
        }
        if (inputParams.IndexOf("v-validate=") >= 0)
        {
            vValidate = "";
        }
        showMust = "*";
    }
    else
    {
        vValidate = " v-validate=\"{data:" + modelName + ",dataType:'*',maxLength:" + fieldLength + ",ignoreEmpty:true,ignoreHidden:true}\" ";
    }

    if (fieldType == "file" || fieldType == "files")
    {
        if (string.IsNullOrEmpty(tips))
        {
            tips = "只能上传" + upload_ext + "格式文件";
            if (StringHelper.Format<int>(upload_maxsize) > 0)
            {
                tips += "，且不超过" + upload_maxsize + "kb";
            }
        }
    }


    if (fieldType == "datepicker")
    {
        if (hasPermission)
        {
            if (inputParams.IndexOf("type=")<=0)
            {
                inputParams += " type=\"datetime\"";
            }

            if (inputParams.IndexOf("value-format=") <= 0)
            {
                inputParams += " value-format=\"yyyy-MM-dd HH:mm:ss\"";
            }
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <el-date-picker v-model="@(modelName)" placeholder="请选择" @Html.Raw(inputParams) @Html.Raw(vValidate)></el-date-picker>
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "text" || fieldType == "password")
    {
        if (hasPermission)
        {
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <el-input type="@fieldType" ref="@fieldObjName" v-model.trim="@(modelName)" maxlength="@fieldLength" class="@(addClass)" @Html.Raw(inputParams) @Html.Raw(vValidate)></el-input>
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "number")
    {
        if (hasPermission)
        {
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <el-input-number type="@fieldType" controls-position="right" ref="@fieldObjName" v-model.trim="@(modelName)"  class="@(addClass)" @Html.Raw(inputParams) @Html.Raw(vValidate)></el-input-number>
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "slider")
    {
        if (hasPermission)
        {
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <el-slider ref="@fieldObjName" v-model.trim="@(modelName)" class="@(addClass)" @Html.Raw(inputParams) @Html.Raw(vValidate)></el-slider>
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "datapicker")
    {
        if (hasPermission)
        {
            options = Html.GetFieldOptionsJson(fieldId, detailId);
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <ui-select-popup ref="@fieldObjName" v-model="@(Html.Raw(modelName))" btn-title="@bt_text"  th-title="@datasource_textFieldName" :options='@Html.Raw(options)' url="/e/PopupSelectData/?fieldId=@(fieldId)"  :props="{checkStrictly:@(datasource_onlyselect_final == "0" ? "true" : "false"),showSearch:@(datasource_selectDataType == "0" ? "true" : "false")}"  :multiple="@(isMultipleSelect == "1" ? "true" : "false")" @Html.Raw(inputParams) @Html.Raw(vValidate)>
                </ui-select-popup>
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "select")
    {
        if (hasPermission)
        {
            options = Html.GetFieldOptionsJson(fieldId, detailId);
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <ui-select ref="@fieldObjName" v-model="@(Html.Raw(modelName))" :options='@Html.Raw(options)' :multiple="@(isMultipleSelect == "1" ? "true" : "false")" @Html.Raw(inputParams) @Html.Raw(vValidate) btn-title="@(bt_text)">
                </ui-select>
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "cascader") //级联
    {
        if (hasPermission)
        {
            options = Html.GetFieldOptionsJson(fieldId, detailId);
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <ui-cascader ref="@fieldObjName" v-model="@(Html.Raw(modelName))" collapse-tags :options="@options" :props="{expandTrigger:'hover',multiple:@(isMultipleSelect == "1" ? "true" : "false"),checkStrictly:@(datasource_onlyselect_final == "0" ? "true" : "false")}" @Html.Raw(inputParams) @Html.Raw(vValidate)>
                </ui-cascader>
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    //ckeckbox
    else if (fieldType == "checkbox")
    {
        if (hasPermission)
        {
            options = Html.GetFieldOptionsJson(fieldId, detailId);
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <ui-checkbox ref="@fieldObjName" v-model="@(modelName)" :options='@Html.Raw(options)' @Html.Raw(inputParams) @Html.Raw(vValidate)></ui-checkbox>
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips) </span>
            </el-form-item>

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

    }
    //radio
    else if (fieldType == "radio")
    {
        if (hasPermission)
        {
            options = Html.GetFieldOptionsJson(fieldId, detailId);
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <ui-radio ref="@fieldObjName" v-model="@(modelName)" :options='@Html.Raw(options)' @Html.Raw(inputParams) @Html.Raw(vValidate)></ui-radio>
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }

    }
    //textarea
    else if (fieldType == "textarea")
    {
        if (hasPermission)
        {
            if (inputParams.IndexOf(":autosize") <= 0)
            {
                inputParams += " :autosize=\"{ minRows: 4, maxRows: 8}\"";
            }
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <el-input ref="@fieldObjName" type="textarea" v-model="@(modelName)" class="@(addClass)" @Html.Raw(inputParams) @Html.Raw(vValidate)></el-input>
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "editor")
    {
        if (hasPermission)
        {
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <ui-editor ref="@fieldObjName" v-model="@(modelName)" :max-length="@fieldLength" :height="@editor_height" toolbars="@(editor_style)" :data="{guid:'@guid',maximumWords:@fieldLength,tableName:'@table',fieldName:'@field',maxImageWidth:'@uploadImageMaxWidth',}" @Html.Raw(inputParams) @Html.Raw(vValidate)></ui-editor>
                @if (sys_field == "1" && from == PageAdmin.Common.FromEnum.Admin && field == "content")
                {

                }
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }

    }
    else if (fieldType == "image" || fieldType == "images")
    {
        if (hasPermission)
        {
            var fileList = JsonHelper.JsonParse(Html.AttachmentDataList(new { Fields = "Domain,Name,Path,Thumbnail", ParentTable = table, ParentField = field, ParentId = detailId }));
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <ui-picture-upload ref="@fieldObjName" action="/e/uploadApi/" v-model="@(modelName)" return-type="string" :limit="@max_num" :max-size="@upload_maxsize" list-type="picture-card" :file-list='@Html.Raw(fileList)' accept="@upload_ext" :data="{tableName:'@table',fieldName:'@field',detailId:@detailId,fileType:'@fieldType',watermark:'@watermark',thumbnail:'@thumbnail',thumbnailWidth:'@thumbnailWidth',thumbnailHeight:'@thumbnailHeight',maxImageWidth:'@uploadImageMaxWidth'}" @Html.Raw(inputParams) @Html.Raw(vValidate)>
                    <i class="el-icon-plus"></i>
                </ui-picture-upload>
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "file" || fieldType == "files")
    {
        if (hasPermission)
        {
            var fileList = JsonHelper.JsonParse(Html.AttachmentDataList(new{Fields = "Domain,Name,Path", ParentTable = table, ParentField = field, ParentId = detailId }));
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <ui-file-upload ref="@fieldObjName" action="/e/uploadApi/" v-model="@(modelName)" return-type="string" :limit="@max_num" :max-size="@upload_maxsize" :file-list='@Html.Raw(fileList)' accept="@upload_ext" :data="{tableName:'@table',fieldName:'@field',detailId:@detailId,fileType:'@fieldType',watermark:'@watermark',thumbnail:'@thumbnail',thumbnailWidth:'@thumbnailWidth',thumbnailHeight:'@thumbnailHeight',maxWidth:'@uploadImageMaxWidth'}" @Html.Raw(inputParams) @Html.Raw(vValidate)>
                    <i class="el-icon-plus"></i>
                </ui-file-upload>
                <span class="help-block">@Html.Raw(tips) </span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "colorpicker")
    {
        if (hasPermission)
        {
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <el-color-picker ref="@fieldObjName" v-model="@(modelName)" @Html.Raw(inputParams) @Html.Raw(vValidate)></el-color-picker>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }

    else if (fieldType == "subtable" && from != PageAdmin.Common.FromEnum.Guest)
    {
        if (hasPermission)
        {
            <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                <el-button-group>
                    <el-button v-on:click='dialog({title:"@(remark)",url:"/E/SubData/@(subTableType=="multiple"?"":"Set")?parentguid=@guid&parentId=@detailId&fieldId=@fieldId",width:"@win_width",height:"@win_height",target:"self"})'>@(bt_text)</el-button>
                </el-button-group>
                @Html.Raw(additionalContent)
                <span class="help-block">@Html.Raw(tips)</span>
            </el-form-item>
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }
    }
    else if (fieldType == "zdy")
    {
        if (hasPermission)
        {
            if (!string.IsNullOrEmpty(zdyContent) && !string.IsNullOrEmpty(vValidate))
            {
                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(">");
                zdyContent = r.Replace(zdyContent, vValidate + ">", 1); //结束标签中加上验证
            }
            if (zdyContent.IndexOf("</el-form-item>") > 0)
            {
                <template>
                    @Html.Raw(zdyContent)
                </template>
            }
            else
            {
                <el-form-item label="@remark@showMust" @Html.Raw(elFormItemParams)>
                    @Html.Raw(zdyContent)
                    <span class="help-block">@Html.Raw(tips)</span>
                </el-form-item>
            }
        }
        else
        {
            @Html.Raw(noPerrmissionContent);
        }

    }
}
