<template>
    <!-- 仿 单页 添加字段-->
    <div>
        <!--表格内容 start------------------------------------------------------------>
        <div class="layerBox">
            <tableTitle :name="tableDivTitle" /> 
            <button class="btn" @click="addWebsite('添加字段')">添加字段</button>
            <el-row>
                <template>
                    <el-table class="my-table" :data="tableData" style="width: 100%">
                        <el-table-column prop="id" label="ID" width="">
                        </el-table-column>
                        <el-table-column prop="field_name" label="字段" width="">
                        </el-table-column>
                        <el-table-column prop="type_name" label="类别" width="">
                        </el-table-column>
                        <el-table-column prop="is_check" label="验证" width="">
                              <template slot-scope="scope">
                                {{ scope.row.is_check === 1 ? '验证' : '不验证' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="title" label="展示名" width="">
                        </el-table-column>
                        <el-table-column fixed="right" label="操作"  width="177">
                            <template slot-scope="scope">
                                <div class="listBtnBox">
                                    <div class="listEditBtn" @click="goEdit(scope.row.id, scope.row)">
                                       <i class="el-icon-edit-outline"></i>
                                       修改 
                                   </div>
                                    <div class="listDeleteBtn" @click="deleteRow(scope.row.id)" 
                                        v-if="scope.row.disable_del === 0">
                                        <i class="el-icon-delete"></i>
                                          删除 
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </el-row>
        </div>
        <!--表格内容 end------------------------------------------------------------>
        <!-- 弹出框 编辑 start----------------------------------------------------------->
        <el-dialog :title="dialogName" :visible.sync="dialogTableVisible" width="50%" top="8vh"
            :close-on-click-modal="false">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
                <div class="dialogText">
                    <el-form-item label="字段名称:" prop="field_name">
                        <el-input 
                            v-model="ruleForm.field_name" 
                            placeholder="请输入字段名称(小写字母和下划线:complaints_report)"
                            :disabled="dialogName === '修改字段'"
                            
                            clearable>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="显示名称:" prop="field_name_show">
                        <el-input 
                            v-model="ruleForm.field_name_show" 
                             
                            placeholder="请输入显示名称:投诉举报"
                            clearable>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="字段类别:" prop="field_type">
                        <el-select v-model="ruleForm.field_type" 
                                placeholder="请选择"
                                @change="select_change"
                                filterable>
                            <el-option v-for="item in field_type_arr" 
                                    :key="item.value" 
                                    :label="item.label" 
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
 
                    <el-form-item label="选项列表:" prop="field_textarea"
                        :rules="[
                            { 
                                required: ruleForm.field_type >= 3 && ruleForm.field_type <= 5 ? true : false, 
                                message: '该项不能为空!', 
                                trigger: 'blur' 
                            } 
                        ]">

                        <el-input
                        type="textarea"
                        :rows="2"
                        placeholder="请输入内容"
                        v-model="ruleForm.field_textarea"
                        :disabled="ruleForm.field_type >= 3 && ruleForm.field_type <= 5 ? false : true"
                        >
                        </el-input>
                    </el-form-item>


                    <el-form-item label="字段长度:" prop="field_length">
                        <el-input 
                        placeholder="请输入字段长度:"
                        v-model="ruleForm.field_length"
                        number
                        class="hint-input"> 
 
                        </el-input>

                        <div class="hint-message">长度必须在1-255之间</div>

                    </el-form-item>

                    <el-form-item label="是否校验:" prop="field_switch">
                        <el-switch
                            v-model="ruleForm.field_switch"
                            :active-value="1"
                            :inactive-value="0"
                            @change="handleSwitchChange"
                            >
                        </el-switch>
                    </el-form-item>
 
 
                    <el-form-item label="正则验证:" prop="field_regular" 
                        :rules="[
                            { 
                                required: ruleForm.field_switch === 1, 
                                message: '请输入正则表达式', 
                                trigger: 'blur' 
                            } 
                        ]">
                        <el-input 
                            v-model="ruleForm.field_regular" 
                            placeholder="请输入正则表达式，例如：/^\d+$/" 
                            :disabled="ruleForm.field_switch !== 1">
                        </el-input>
                    </el-form-item>

                    <el-form-item label="后端是否展示:" prop="field_switch_backend">
                        <el-switch
                            v-model="ruleForm.field_switch_backend"
                            :active-value="1"
                            :inactive-value="0">
                        </el-switch>
                    </el-form-item>
                    <el-form-item label="前端是否展示:" prop="field_switch_web">
                        <el-switch
                            v-model="ruleForm.field_switch_web"
                            :active-value="1"
                            :inactive-value="0">
                        </el-switch>
                    </el-form-item>
                </div>
                <div class="dialogBtn">
                    <el-button type="info" @click="cancelForm">取消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                </div>
            </el-form>
        </el-dialog>
        <!-- 弹出框 编辑 end----------------------------------------------------------->
    </div>
</template>
<script>
//表格标题
import tableTitle from './components/tableTitle.vue';
//引入公用样式
import '@/styles/global.less';
import {font_form_edit_api,font_form_del_api, font_form_add_api,font_form_select_api,font_form_api,getFooterCategory } from '@/api/globalFormApi'
export default {
    components: {
        tableTitle,//表格标题-
    },
    data() {
        const validateEmpty = (rule, value, callback) => {
            if (value.length == 0) {
                callback(new Error('该项不能为空！'))
            } else {
                callback()
            }
        }
        return {
            tableDivTitle: this.$route.query.website_name ? "自定义字段-"+this.$route.query.website_name :'自定义字段' ,  //列表标题
            dialogTableVisible: false,      //编辑弹框
            dialogName: '编辑1', //编辑弹窗名称
            disabled: false, //禁用
            tableData: [],//表格数据
            // 可以输入的搜索框相关
            webSiteList: [],//获取关联网站列表
            //3.4 上传logo图片
            logoUrl: '',
            hovering: false, // 鼠标悬浮状态 悬浮时显示删除
            value: '',
            activeid: "",  //活动id 
            type: "",  //查看时需要传递的类型
            formLabelWidth: '', //广告示例图相关
            // 搜索框相关
            webSiteName_name: '', //网站名称
            webSiteName_id: '', //网站名称id
            tabbarName: '', //单页名称
            website_id: "", //网站id
            field_type_arr:[],
            reg_inp_masg:"",//inp下的校验内容=提示


            ruleForm: {
                field_recive_id: this.$route.query.id, //表id   this.$route.query.id,   table_id
                field_name: '', //字段名称  field_name
                field_name_show: '', // 显示名称字段    title
                field_type: "", //字段类别  下拉下拉选中的列表id    field_type
                // field_select_id: '', //下拉选中的列表id           
                field_textarea: '', //选项列表  option
                field_length: '', //长度        length
                field_switch: 0, // 新增校验开关，默认0不校验   is_check
                field_switch_backend: 0, //后端是否展示 0：不展示 1：展示   admin_display
                field_switch_web: 0, //前端是否展示 0：不展示 1：展示   home_display

                field_regular: '', // 新增正则表达式字段

            },
            rules: {

                 field_name: [
                    { 
                        required: true, 
                        trigger: 'blur', 
                        validator: validateEmpty 
                    },
                    // 新增正则验证规则
                    {
                        pattern: /^[a-z_]+$/,
                        message: '字段名称只能包含小写字母和下划线',
                        trigger: 'blur'
                    }
                ],
                field_name_show : [{ required: true, trigger: 'blur', validator: validateEmpty }],
                field_type: [{ required: true, trigger: 'change', validator: validateEmpty  }],
                field_textarea: [{ required: true, trigger: 'blur', validator: validateEmpty }],
                field_length: [
                    { type: 'number', message: '必须为数字值', trigger: 'blur',transform: value => Number(value) },
                    { type: 'number', min: 1, max: 255, message: '长度必须在1-255之间', trigger: 'blur',required: true },
                ],

                field_regular: [{ 
                    required: true, 
                    message: '校验内容不能为空', 
                    trigger: 'blur',
                    validator: (rule, value, callback) => {
                        if (this.ruleForm.field_switch === 1 && !value) {
                            callback(new Error('校验内容不能为空'))
                        } else {
                            callback()
                        }
                    }
                }]
            
            
            }
        }
    },
    methods: {
        //1.列表和分页相关 start ------------------------------------------------------------>
        //1.1 开始请求列表信息方法
        getData() {
                // 表单字段类型=下拉
                font_form_select_api({
                }).then(data => {
                     this.field_type_arr = data.data.map(item => ({
                        label: item.type_name,
                        value: item.id,
                    }));
                })
                //得到字段表单列表=全局表单-自定义字段
                font_form_api({
                    id: this.$route.query.id,
                }).then(data => {
                    this.tableData = data.data 
                     
                })
            if (this.webSiteName_name && this.tabbarName) {
                getFooterCategory({
                    name: this.tabbarName,
                    website_name: this.webSiteName_name, //网站名称
                }).then(data => {
                     
                    this.tableData = data.data.rows
                })
            } else if (this.webSiteName_name && !this.tabbarName) {
                getFooterCategory({ 
                    // name: this.tabbarName,
                    website_name: this.webSiteName_name, //网站名称
                }).then(data => {
                     
                    this.tableData = data.data.rows
                })
            } else if (!this.webSiteName_name && this.tabbarName) {
                getFooterCategory({
                    name: this.tabbarName,
                    // website_name: this.webSiteName_name, //网站名称
                }).then(data => {
                    // console.log(data);
                    this.tableData = data.data.rows
                })
            } else {
                getFooterCategory({
                }).then(data => {
                    // console.log(data);
                    this.tableData = data.data.rows
                })
            }
        },
        //1.2 删除内容
        deleteRow(id) {
            // console.log(id);
            let data = new FormData()
            data.append('id', id)
            this.$confirm('注意:确定删除？', '提示：', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                // console.log("当前删除：" + id)
                font_form_del_api({
                    id: id
                }).then(data => {
                    // console.log(data);
                    if (data.code = 200) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        this.getData()
                    } else if (data.code == 0) {
                        this.$message({
                            message: data.message,
                            type: 'error'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'warning',
                    message: '已取消删除'
                });
            });
        },
        //1.3 查看示例图
        goGraph() {
            this.dialogVisible = true
        },
        //1.9 编辑
        goEdit(id, val) {
             
            this.dialogName = '修改字段'
            this.activeid = id
            this.dialogTableVisible = true
            this.disabled = true
             
            this.reg_inp_masg = val.regular

            this.ruleForm = {
                field_name: val.field_name,
                field_name_show: val.title,
                field_type: +val.field_type,
                field_textarea: val.option,
                field_length: val.length,
                field_switch: val.is_check,
                field_switch_backend: val.admin_display,
                field_switch_web: val.home_display,
                field_regular: val.regular,
                field_regular_message: "请输入正则表达式如:"+val.regular,
            }
        },
        //1.7 添加
        addWebsite() {
            this.dialogTableVisible = true
            this.dialogName = "添加字段"
            this.disabled = false
            //添加时清空回显回来的数据
            this.ruleForm = {
                field_recive_id: this.$route.query.id,
                field_name: '',
                field_name_show: '',
                field_type: "",
                field_textarea: '男|1\n女|2\n保密|3',
                field_length: '',
                field_switch: 1,
                field_switch_backend: 0,
                field_switch_web: 0,
                // field_regular: this.regular,
                // field_regular_message: "请输入正则表达式如:"+this.regular,
            }
        },


         handleSwitchChange(val) {
        this.$nextTick(() => {
            this.$refs.ruleForm.validateField('field_regular')
        })
    },
        // 弹出层相关方法
        // 提交添加字段
        submitForm(formName) {
            if (this.dialogName  == '修改字段') {
                // 提交前验证所有字段
                this.$refs[formName].validate((valid) => {


                    if (valid) {
                        font_form_edit_api({
                            table_id: this.$route.query.id,
                            field_name: this.ruleForm.field_name,
                            title: this.ruleForm.field_name_show,
                            field_type: this.ruleForm.field_type,
                            option: this.ruleForm.field_textarea,
                            length: this.ruleForm.field_length,
                            is_check: this.ruleForm.field_switch,
                            admin_display: this.ruleForm.field_switch_backend,
                            home_display: this.ruleForm.field_switch_web,
                            id: this.activeid,
                            regular: this.ruleForm.field_regular,
                            // id: this.$route.query.id,
                        }).then(data => {
                                if (data.code == 200) {
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                })
                                this.dialogTableVisible = false
                                this.getData()

                                
                            } else if (data.code == 0) {
                                this.$message({
                                    message: data.message,
                                    type: 'error'
                                })
                                this.dialogTableVisible = true
                                return
                            } else {
                                this.$message({
                                    message: data.message,
                                    type: 'error'
                                })
                                this.dialogTableVisible = true
                                return
                            }
                        })
                    } else {
                        this.$message.error('请填写所有必填字段！');
                        return false;
                    }
                });
            }
            if (this.dialogName == '添加字段') {
                // 提交前验证所有字段
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        font_form_add_api({
                            table_id: this.$route.query.id,
                            field_name: this.ruleForm.field_name,
                            title: this.ruleForm.field_name_show,
                            field_type: this.ruleForm.field_type,
                            option: this.ruleForm.field_textarea,
                            length: this.ruleForm.field_length,
                            is_check: this.ruleForm.field_switch,
                            admin_display: this.ruleForm.field_switch_backend,
                            home_display: this.ruleForm.field_switch_web,
                        }).then(data => {
                                if (data.code == 200) {
                                this.$message({
                                    message: '添加成功',
                                    type: 'success'
                                })
                                this.dialogTableVisible = false
                                this.getData()
                            } else if (data.code == 0) {
                                this.$message({
                                    message: data.message,
                                    type: 'error'
                                })
                                this.dialogTableVisible = true
                                return
                            } else {
                                this.$message({
                                    message: data.message,
                                    type: 'error'
                                })
                                this.dialogTableVisible = true
                                return
                            }
                        })
                    } else {
                        this.$message.error('请填写所有必填字段！');
                        return false;
                    }
                });
            }


        },
 
        //取消添加或编辑
        cancelForm() {
            this.dialogTableVisible = false
        },
        //3.6 上传图片操作
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG && !isPNG) {
                this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
                return false;
            }
            const formData = new FormData();
            formData.append('file', file);
            this.$store.dispatch('pool/uploadFile', formData).then(res => {
                this.logoUrl = res.data.imgUrl;//显示缩略图
                this.ruleForm.adPhoto = res.data.imgUrl;//提供表单地址
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '网络错误，请重试！'
                });
            })
            // 阻止默认的上传行为
            return false;
        },
        handleDelete() {
            // 删除图片
            this.logoUrl = ''; // 清空图片 URL
        },
        //添加 / 编辑弹窗中输入关键词下拉框 
        // 判断是否已经关联了网站
        detectionWebSite(value) {
            // console.log(value);
            this.website_id = value
        },


        // 选择下拉框
        select_change(val) {
                // 当切换类型时自动触发验证
                this.$nextTick(() => {
                    this.$refs.ruleForm.validateField('field_textarea')
                });
                
                // 如果切换为非选项类型（3-5之外），清空选项内容
                if (val < 3 || val > 5) {
                    this.ruleForm.field_textarea = '';
                }
            },
            





    },
    mounted() {
        this.getData()
    },
}
</script>
<style scoped lang="less">
input[aria-hidden=true] {
    display: none !important;
}
// 提示信息
.tips {
    margin: 30px;
    background-color: #e9ecf9;
    border-radius: 11px;
    .tipsIcon {
        margin: 10px 15px;
        display: inline-block;
        width: 24px;
        height: 24px;
        background: url("../../assets/advertise/Info Circle.png") no-repeat;
        vertical-align: middle;
    }
    .tipsText {
        font-size: 14px;
        color: #666666;
    }
}
// 头部
.title {
    margin: 30px 30px 20px 30px;
    padding: 30px 30px 40px 30px;
    background-color: #fff;
    border-radius: 20px 20px 20px 20px;
    border: 1px solid #E9EDF7;
    .left {
        float: left;
    }
    .right {
        float: right;
    }
    .searchBox {
        ::v-deep .el-input {
            position: relative;
            font-size: 14px;
            display: inline-block;
            width: 80%;
        }
        .searchTitle {
            padding-bottom: 10px;
            font-family: Microsoft YaHei, Microsoft YaHei;
            font-weight: 400;
            font-size: 14px;
            color: #999999;
            line-height: 16px;
        }
        .el-select {
            width: 100%;
            display: inline-block;
            position: relative;
        }
    }
    .btnList {
        float: right;
        padding-top: 28px;
        button {
            height: 38px;
            border: none;
            border-radius: 8px;
            padding: 0 30px;
        }
        .search {
            background-color: #5570f1;
            color: #fff;
            margin-right: 20px;
        }
        .reset {
            font-family: Microsoft YaHei, Microsoft YaHei;
            font-weight: 400;
            font-size: 16px;
            color: #333333;
            background: #F5F7FB;
            border-radius: 8px 8px 8px 8px;
            border: 1px solid rgba(85, 112, 241, 0.11);
        }
    }
}
.layerBox {
    padding: 30px 20px;
    position: relative;
    .btn {
        position: absolute;
        top: 30px;
        right: 20px;
        height: 38px;
        color: #fff;
        background-color: #5570f1;
        border: none;
        border-radius: 8px;
        padding: 8px 28px 9px;
        box-sizing: border-box;
    }
    .listBtnBox {
        justify-content: left;
    }
    .listDeleteBtn,.listMainBtn,
    .listEditBtn,
    .listLookBtn {
        margin-left: 0px;
        padding-left: 0px;
        margin-right: 10px;
         word-break: keep-all; white-space: nowrap;
        height: 36px;width:auto;padding:0px 10px;
        line-height: 36px;
    }
    .listLookBtn {
        text-align: center;
        border-radius: 8px;
        cursor: pointer;
        color: #55b5f1;
        background-color: rgba(85, 181, 241, 0.16);
        >i {
            padding-right: 8px;
        }
    }
    ::v-deep .el-form-item {
        margin-bottom: 50px;
    }
    ::v-deep .el-select {
        width: 100%;
    }
    ::v-deep .el-input--medium,
    ::v-deep .el-form-item__label {
        line-height: 36px;
        font-size: 16px;
    }
}
// 弹出层内容
.dialogText {
    margin: 0 7px 0 3px;
    padding-bottom: 1px;
    padding: 30px 60px 1px 20px;
    background-color: #f5f7fb;
    .adImage {
        width: 140px;
        height: 140px;
        line-height: 210px;
        border-radius: 12px;
        border: 1px solid rgba(85, 112, 241, 0.11);
        img {
            width: 140px;
            height: 80px;
        }
    }
    ::v-deep .avatar {
        width: 140px;
        height: auto;
    }
    .price {
        ::v-deep .el-input {
            width: 29%;
        }
    }
    .example {
        font-family: Microsoft YaHei;
        color: #5570F1;
    }
    .el_btnList {
        margin-right: 15px;
        margin-top: 20px;
    }
    //日期时间选择器的宽
    ::v-deep .el-date-editor.el-input {
        width: 48%;
    }
    ::v-deep .el-button+.el-button {
        margin-left: 0px;
    }
    ::v-deep .el-select {
        width: 100%;
    }
    ::v-deep .el-form-item {
        margin-bottom: 20px;
    }
}
// 弹出层按钮
.dialogBtn {
    text-align: center;
    margin: 50px auto 20px;
    button {
        width: 184px;
        padding: 16px;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 20px;
        border: none;
        border-radius: 12px 12px 12px 12px;
    }
    // 取消
    .cancel {
        color: #333333;
        background-color: #f5f7fb;
        border: 2px solid rgba(85, 112, 241, 0.11);
    }
    // 提交
    .submit {
        color: #fff;
        background-color: #5570F1;
        margin-left: 40px;
    }
}
//审核弹出框
.radioGroup {
    ::v-deep .el-form-item {
        margin-top: 40px;
        margin-bottom: 0;
    }
}
.graph {
    background-color: #f5f7fb;
    padding: 60px 100px;
    overflow: hidden;
    li {
        float: left;
    }
    >li:first-child {
        margin-right: 100px;
    }
}
.dialog-footer {
    margin: 0 auto;
}


.hint-message {
    color: #999;
    font-size: 12px;
    margin-top: 4px;
    line-height: 1.5;
}

</style>