<template>
    <div class="mainBox">
        <div class="layerBox">
            <tableTitle :name="tableDivTitle" />
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="170px" class="demo-ruleForm">
                <div class="dialogText">
                    <el-form-item label="通栏名称:" prop="sectorName">
                        <el-input v-model="ruleForm.sectorName" placeholder="输入通栏名称"></el-input>
                    </el-form-item>
                    <el-form-item label="通栏编号:" prop="sectorId">
                        <el-input v-model="ruleForm.sectorId" placeholder="输入通栏编号"></el-input>
                    </el-form-item>
                    <el-form-item label="画布高度:" prop="pic_height">
                        <el-input v-model="ruleForm.pic_height" placeholder="输入画布高度"></el-input>
                    </el-form-item>
                    <el-form-item label="所属皮肤:" prop="templateStyle">
                        <el-select v-model="ruleForm.templateStyle" placeholder="请选择所属皮肤">
                            <el-option v-for="item in template_options" :key="item.template_id"
                                :label="item.template_name" :value="item.template_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="皮肤id:" prop="templateStyle">
                        <el-input v-model="ruleForm.templateStyle" placeholder="所属皮肤id" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="通栏分类:" prop="sectorType">
                        <el-select v-model="ruleForm.sectorType" placeholder="请选择通栏分类"
                            :disabled="this.dialogName === '编辑'">
                            <!-- 通栏分类：1：资讯类：2：通栏广告类；3：混合类；4：搜索框类；5：导航类；6：头条类；7：轮播图类； -->
                            <el-option v-for="item in this.typeList" :label="item.label" :value="item.value"
                                :key="item.value">{{ item.label }}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属页面:" prop="pageType">
                        <el-checkbox-group v-model="ruleForm.pageType" @change="changeCheckbox"
                            :disabled="this.dialogName === '编辑'">
                            <el-checkbox v-for="(item, index) in checkList" :key="index"
                                :label="item.value">{{ item.label }}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="通栏关键词：" class="custom-align-right">
                        <template #label>
                            <span class="askBox">
                                通栏关键词：
                                <el-tooltip class="item" effect="dark" content="皮肤关键词，如：黑色、卡通、英雄。" placement="top">
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                            </span>
                        </template>
                        <tagInput :initialTags="tags" @tags-updated="updateTags"></tagInput>
                    </el-form-item>
                    <el-form-item label="通栏缩略图：" prop="image" :label-width="formLabelWidth"
                        :class="['custom-form-item']" class="custom-align-right">
                        <div class="uploaderBox">
                            <!--图片上传组件 start ------------------------------------------------------------>
                            <div class="avatar-upload-container" @mouseenter="hovering = true"
                                @mouseleave="hovering = false">
                                <!-- 上传组件 -->
                                <el-upload class="avatar-uploader" action="#" :show-file-list="false"
                                    :before-upload="beforeAvatarUpload">
                                    <!-- 预览图片 -->
                                    <img v-if="this.logoUrl" :src="this.logoUrl" class="avatar">
                                    <!-- 上传图标 -->
                                    <div v-else class="chooseImgDiv">
                                        <div>
                                            <img src="@/assets/public/upload/noImage.png">
                                            <div>选择图片</div>
                                        </div>
                                    </div>
                                    <input type="hidden" name="logo" v-model="ruleForm.image">
                                </el-upload>
                                <!-- 删除按钮，当鼠标悬浮时显示 -->
                                <div v-if="hovering && logoUrl" class="delete-button" @click="handleDelete">
                                    <i class="el-icon-delete"></i>
                                </div>
                            </div>
                            <!--图片上传组件 end ------------------------------------------------------------>
                        </div>
                    </el-form-item>
                    <el-form-item label="组件数量:" prop="component_num">
                        <el-input v-model.number="ruleForm.component_num" id="component_num" placeholder="输入组件数量"
                            type="number" min="1" @change="getPlaceList(ruleForm.component_num)">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="版式类型:" prop="sectorPlace">
                        <el-select v-model="ruleForm.sectorPlace" placeholder="请选择版式类型" @change="changeStyleSort">
                            <el-option v-for="item in sectorPlace_options" :key="item.sector_type"
                                :label="item.name + '(' + item.width + '*' + item.height + ')'"
                                :value="item.sector_type">{{ item.name + '(' + item.width + '*' + item.height + ')' }}
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="尺寸:" prop="sizeList" v-if="this.ruleForm.sectorPlace != ''">
                        <p style="margin-top: 0px;">{{ ruleForm.sizeList }}</p>
                    </el-form-item>
                    <el-form-item label="通栏版式预览图:" prop="sector_img" v-if="this.ruleForm.sectorPlace != ''">
                        <img :src="ruleForm.sector_img" alt="" width="300px" height="150px">
                    </el-form-item>
                    <div class="boxes-container" v-if="this.ruleForm.sizeList != '' && this.ruleForm.sectorPlace">
                        <el-row class="layout-3">
                            <el-row v-if="checkPlace" style="width: 100%;height: 100%;">
                                <el-col v-for="(col, index) in JSON.parse(checkPlace.map)" :key="index"
                                    :style="{ width: col.col_data.col_width, height: '100%', marginRight: '1.2%' }">
                                    <el-row class="box" v-for="(row, rowIndex) in col.col_data.row_data" :key="rowIndex"
                                        :style="{
                                            height: row.row_height,
                                            width: (
                                                typeof row.row_width === 'string' && row.row_width.endsWith('%')
                                                    ? (parseFloat(row.row_width) >= 100 ? row.row_width : '100%')
                                                    : row.row_width
                                            ),
                                            marginBottom: '2.35%'
                                        }">
                                        {{component_option.find(item => item.sort_id == row.component_sort) ?
                                            `位置${component_option.find(item => item.sort_id == row.component_sort).sort_id}
                                        （${component_option.find(item => item.sort_id ==
                                                row.component_sort).width}*${component_option.find(item => item.sort_id ==
                                        row.component_sort).height}）` : '' }}
                                    </el-row>
                                </el-col>
                            </el-row>
                        </el-row>
                    </div>
                    <div v-for="(item, index) in component_option" :key="index" class="componentChoose">
                        <el-form-item :label="item.name + '：'" :prop="`${index}`" class="componentOptions">
                            <el-select v-model="ruleForm.component_code[index]" multiple clearable placeholder="请选择组件"
                                class="componentOption_one">
                                <el-option v-for="(compItem, comIndex) in item.component" :key="compItem.component_type"
                                    :label="compItem.component_name" :value="compItem.component_type">
                                    {{ compItem.component_name }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <div class="dialogBtn">
                    <el-button type="info" @click="cancelForm">取消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
//表格标题
import tableTitle from './components/tableTitle.vue';
import tagInput from '../../components/InputTag/index.vue';
//引入公用样式
import '@/styles/global.less';
export default {
    components: {
        tableTitle,//表格标题-
        tagInput
    },
    data() {
        // 验证字符串或数组是否为空
        const validateEmpty = (rule, value, callback) => {
            if (typeof value === 'string' && value.trim() === '') {
                callback(new Error('该项不能为空！'))
            } else if (typeof value === 'number' && value === null) {
                // 数字类型不能调用 trim 方法，直接判断是否为 null
                callback(new Error('该项不能为空！'))
            } else {
                callback()
            }
        }
        // 验证数组是否为空
        const validateArray = (rule, value, callback) => {
            if (Array.isArray(value) && value.length === 0) {
                callback(new Error('该项不能为空！'))
            } else {
                callback()
            }
        }
        return {
            // 0.0画布及多选组件输入框相关----------start
            component: true,  //验证组件是否有空数组
            name: '编辑',         //备份dialogName来判断是否执行添加和编辑的异步
            tableData: [{}], // 添加空数据使表格正常显示
            // 初始化时设置默认值为 1，确保有初始布局
            component_num: 1,
            activeBoxes: [false], // 初始化激活状态数组
            selectedComponents: { 0: [] }, // 初始化组件选择对象
            // 0.0画布及多选组件输入框相关----------end
            //1.1 初始化信息 
            tableDivTitle: "通栏列表",  //列表标题
            dialogTableVisible: false,      //编辑弹框
            dialogName: '编辑', //编辑弹窗名称
            plateLoading: true, //表格内容加载中
            tableData: [],//表格数据
            class_options: [],//风格下拉列表
            template_options: [],//皮肤下拉列表
            // componen_code: [],//组件版式及组件下拉列表
            sectorPlace_options: [],//通栏模版类型下拉列表
            component_option: [],
            tags: [],//标签数据
            templateStyle: '',//风格
            plateName: '',
            pageType: '',//页面类型
            value: '',
            checkList: [
                {
                    value: 1,
                    label: '首页',
                },
                {
                    value: 2,
                    label: '频道页',
                },
                {
                    value: 3,
                    label: '列表页',
                },
                {
                    value: 4,
                    label: '详情页',
                },
                {
                    value: 5,
                    label: '搜索页',
                },
                {
                    value: 6,
                    label: '单页（列表）',
                },
                {
                    value: 7,
                    label: '单页（详情）',
                },
            ],
            typeList: [],
            //活动id
            activeid: "",
            newArr: [],
            // 1.3 分页相关 
            page: 1,
            pageSize: 10,
            total: 0,
            formLabelWidth: '', //广告示例图相关
            //1.4 弹框相关数据 
            ruleForm: {
                sectorName: '',//通栏名称
                sectorPlace: null,//通栏模版类型
                component_num: null,//组件数量 
                sectorId: '',//通栏编号id
                templateStyle: '',//所属皮肤
                pageType: '',//页面类型
                sizeList: '',//尺寸
                sectorType: null,//通栏类别
                pageType: [],//页面类型
                sectorKeyword: '',//通栏关键词
                image: '',//通栏展示图
                sector_img: '',//通栏版式预览图
                component_code: [],//所选择位置的组件
                sector_width: '',
                sector_height: '',
                pic_height: ''//画布高度
            },
            rules: {
                sectorName: [{ required: true, trigger: 'blur', validator: validateEmpty }],
                component_num: [{ required: true, trigger: 'blur', message: '该项不能为空！' }],
                sectorId: [{ required: true, trigger: 'blur', validator: validateEmpty }],
                templateStyle: [{ required: true, trigger: 'blur', validator: validateEmpty }],//关联皮肤名称 
                sectorType: [{ required: true, trigger: 'blur', message: '该项不能为空！' }],
                image: [{ required: true, trigger: 'blur', validator: validateEmpty }],
                sectorPlace: [{ required: true, trigger: 'blur', validator: validateEmpty }],
                component_code: [{ required: true, trigger: 'blur', validator: validateArray }],
                pageType: [{ required: true, trigger: 'blur', validator: validateArray }],
                pic_height: [{ required: true, trigger: 'blur', validator: validateEmpty }]
            },
            logoUrl: '',
            hovering: false, // 鼠标悬浮状态 悬浮时显示删除
        }
    },
    computed: {
        // 计算激活的方块索引
        activeBoxIndices() {
            return this.activeBoxes
                .map((active, index) => active ? index : null)
                .filter(index => index !== null);
        },
        checkPlace() {
            // 检查 sectorPlace_options 是否为数组，避免调用 find 方法时报错
            if (Array.isArray(this.sectorPlace_options)) {
                return this.sectorPlace_options.find(item => item.sector_type == this.ruleForm.sectorPlace);
            }
            return null;
        }
    },
    methods: {
        //1.列表和分页相关 start ------------------------------------------------------------>
        //1.1 开始请求列表信息方法        
        // 获取版式列表
        getPlaceList(sectorType) {
            this.component_option = []
            this.ruleForm.component_code = []
            this.ruleForm.sectorPlace = ''
            let data = {
                component_num: this.ruleForm.component_num,
                type_id: 1,
            }
            this.$store.dispatch('plate/getAllSectorPlace', data).then(res => {
                this.sectorPlace_options = res.data
            }).catch(() => {
                this.$message({
                    type: 'error',
                    message: '网络错误，请重试！'
                });
            })
            // console.log("回显-22222",this.sectorPlace_options);
        },
        //获取风格列表
        getStyleList() {
            this.$store.dispatch('genre/getTemplateClass').then(res => {
                this.class_options = res.data
                // console.log(res.data);
            }).catch(() => {
                this.$message({
                    type: 'error',
                    message: '网络错误，请重试！'
                });
            })
        },
        //获取皮肤列表
        getSkinList() {
            let data = [];
            this.$store.dispatch('plate/getAllTemplate').then(res => {
                this.template_options = res.data
                console.log(res.data);
            }).catch(() => {
                this.$message({
                    type: 'error',
                    message: '网络错误，请重试！'
                });
            })
        },
        // 获取通栏分类
        getSectorType() {
            this.$store.dispatch('plate/getSectorType').then(res => {
                this.typeList = res.data
                this.typeList.forEach(item => {
                    item.label = item.name
                    item.value = item.id
                })

                console.log('获取类型', res.data);
            }).catch(() => {
                this.$message({
                    type: 'error',
                    message: '网络错误，请重试！'
                });
            })
        },
        //1.3 多选按钮发生变化
        changeCheckbox(val) {
            console.log(val)
            this.newArr = []
            val.forEach(item => {
                if (typeof item !== 'object' || !item.hasOwnProperty('__ob__')) {
                    this.newArr.push(item)
                }
            });
            this.pageType = JSON.stringify(this.newArr)
            // console.log(this.pageType);
        },
        // 通栏版式发生变化
        changeStyleSort(val) {
            let num = 0;
            this.component_option = []
            this.activeBoxes = []
            this.selectedComponents = {}
            this.ruleForm.component_code = []
            if (this.sectorPlace_options && Array.isArray(this.sectorPlace_options)) {
                this.sectorPlace_options.forEach(item => {
                    if (item.sector_type == val) {
                        this.ruleForm.sizeList = item.width + ' * ' + item.height
                        this.ruleForm.sector_img = item.sector_img
                        this.ruleForm.size_id = item.size_id
                        this.ruleForm.sector_width = item.width
                        this.ruleForm.sector_height = item.height
                        this.ruleForm.component_num = item.component_num;
                    }
                })
            }
            let data = {
                sector_type: this.ruleForm.sectorPlace,
                type_id: 2,
            }
            this.$store.dispatch('plate/getAllSectorPlace', data).then(res => {
                this.component_option = res.data
                if (this.component_option && Array.isArray(this.component_option)) {
                    this.component_option.forEach(item => {
                        item.name = '位置' + item.sort_id + '（' + item.width + '*' + item.height + '）'
                    })
                }
            }).catch(() => {
                this.$message({
                    type: 'error',
                    message: '网络错误，请重试！'
                });
            })
        },
        getStyleSort(val) {
            console.log('this.ruleForm.sectorPlace2222', this.ruleForm.sectorPlace);
            console.log('val', val);
            let data = {
                sector_type: this.ruleForm.sectorPlace,
                type_id: 2,
            }
            this.$store.dispatch('plate/getAllSectorPlace', data).then(res => {
                this.component_option = res.data
                this.component_option.forEach(item => {
                    item.name = '位置' + item.sort_id + '（' + item.width + '*' + item.height + '）';
                })
            }).catch(() => {
                this.$message({
                    type: 'error',
                    message: '网络错误，请重试！'
                });
            })
        },
        //列表和分页相关 end ------------------------------------------------------------>
        //验证关联组件（每一个位置必须至少有一个组件）
        checkComponent() {
            this.component = true
            if (this.ruleForm.component_code && Array.isArray(this.ruleForm.component_code)) {
                const component = '';
                this.ruleForm.component_code.forEach(component => {
                    if (component.length == 0) {
                        this.component = false,

                            console.log('component', component);
                        this.$message({
                            message: '请关联组件！',
                            type: 'error'
                        })
                    }
                });
                // return this.component;
            }
            return true;
        },
        //1.9 编辑
        goEdit(id, val) {
            // console.log(id)
            let data = {
                id: this.$route.query.id
            };
            this.$store.dispatch('plate/getSectorInfo', data).then(res => {
                console.log('res回显', this.typeList)
                this.ruleForm.sectorName = res.data.sector_name//通栏名称
                this.ruleForm.sectorId = res.data.sector_id//通栏编号id
                this.ruleForm.templateStyle = res.data.template_id//关联皮肤名称
                this.ruleForm.component_num = res.data.component_num//组件数量
                this.ruleForm.sizeList = res.data.sector_width + ' * ' + res.data.sector_height//通栏尺寸
                this.ruleForm.sectorType = parseInt(res.data.sector_type)//通栏类别
                this.ruleForm.pageType = JSON.parse(res.data.page_type)// 通栏页面类型，根据符号|划分字符串为数组
                if(res.data.sector_keyword=='\"\"'){
                    this.tags = []
                }else{
                    this.tags = JSON.parse(res.data.sector_keyword)
                }
                this.ruleForm.plateCode = res.data.sector_code//通栏代码
                this.ruleForm.sectorKeyword = this.tags//通栏关键词
                this.ruleForm.image = res.data.sector_img//通栏展示图
                this.logoUrl = res.data.sector_img
                this.ruleForm.sector_img = res.data.place.sector_img
                this.sectorPlace_options = this.getPlaceList(res.data.component_num)
                this.ruleForm.sectorPlace = parseInt(res.data.place_type)
                this.getStyleSort(res.data.sectorPlace)
                // this.ruleForm.size_id = res.data.size_id;
                this.ruleForm.sector_width = res.data.sector_width
                this.ruleForm.sector_height = res.data.sector_height
                this.ruleForm.component_code = JSON.parse(res.data.component_code)
                this.ruleForm.pic_height = res.data.pic_height
                console.log('回显表单', this.ruleForm)
                console.log('回显表单', this.tags)
            }).catch(() => {
                this.$message({
                    type: 'error',
                    message: '网络错误，请重试！'
                });
            })
        },
        //1.7 添加
        addPlate() {
            this.dialogTableVisible = true
            this.dialogName = "添加"
            this.name = "添加"
            this.name = this.dialogName
            //添加时清空回显回来的数据
            this.ruleForm.sectorName = ''      //通栏名称
            this.ruleForm.sectorId = ''      //通栏编号id
            this.ruleForm.templateStyle = ''   //关联皮肤名称
            this.ruleForm.sizeList = ''        //通栏尺寸
            this.ruleForm.sectorType = null      //通栏类别
            this.ruleForm.pageType = []        //通栏页面类型
            this.ruleForm.plateCode = ''       //通栏代码
            this.ruleForm.sectorKeyword = ''   //通栏关键词
            this.ruleForm.component_num = null  //组件数量
            this.ruleForm.image = ''           //通栏展示图
            this.ruleForm.sector_img = ''           //通栏展示图
            // this.ruleForm.size_id = ''           //通栏尺寸
            this.ruleForm.sectorPlace = ''         //通栏版式编号
            this.logoUrl = ''
            this.ruleForm.image = ''
            this.tags = []
            this.ruleForm.component_code = []
            this.component_option = []
            this.ruleForm.sector_width = ''
            this.ruleForm.sector_height = ''
            // this.getPlaceList();
            this.selectedComponents = []
            this.activeBoxes = []
        },
        // 弹出层相关方法
        // 提交表单
        submitForm(formName) {
            console.log('this.ruleForm', this.dialogName)
            // this.name = this.dialogName
            console.log('this.ruleForm111', this.dialogName)
            console.log('this.ruleForm222', this.name)
            this.checkComponent()
            console.log('this.component', this.component)
            if (!this.component) {
                this.dialogName = ""
                return
            } else {
                this.dialogName = this.name
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.ruleForm.sectorKeyword.length == 0){
                        //如果没添加关键词，也就不需要验证了
                        if (this.dialogName == "添加") {
                            const data = {
                                sector_name: this.ruleForm.sectorName,       //通栏名称
                                sector_id: this.ruleForm.sectorId,           //通栏编号
                                template_id: this.ruleForm.templateStyle,    //所属皮肤
                                // size_id: this.ruleForm.size_id,             //通栏尺寸
                                sector_type: this.ruleForm.sectorType,       //通栏类别
                                sector_code: this.ruleForm.plateCode,        //通栏代码
                                page_type: this.ruleForm.pageType,           //页面类型
                                component_num: this.ruleForm.component_num,  //组件数量
                                sector_keyword: JSON.stringify(this.ruleForm.sectorKeyword), //通栏关键词
                                sector_img: this.logoUrl,           //通栏展示图
                                place_type: this.ruleForm.sectorPlace,           //通栏版式id
                                component_code: JSON.stringify(this.ruleForm.component_code),           //通栏所选组件
                                sector_width: this.ruleForm.sector_width,           //通栏宽度
                                sector_height: this.ruleForm.sector_height,           //通栏高度
                                pic_height: this.ruleForm.pic_height,           //画布高度
                            }
                            console.log('添加表单--------data', data);
                            this.$store.dispatch('plate/addSector', data).then(data => {
                                if (data.code == 200) {
                                    this.$message({
                                        message: '添加成功',
                                        type: 'success'
                                    })
                                    this.$router.push({
                                        path: '/plate',
                                    });
                                } else {
                                    this.$message({
                                        message: data.message,
                                        type: 'error'
                                    })
                                }
                            })
                        }
                        if (this.dialogName == "编辑") {
                            const data = {
                                id: this.$route.query.id,
                                sector_name: this.ruleForm.sectorName,       //通栏名称
                                sector_id: this.ruleForm.sectorId,           //通栏编号
                                template_id: this.ruleForm.templateStyle,    //所属皮肤
                                // size_id: this.ruleForm.size_id,             //通栏尺寸
                                sector_type: this.ruleForm.sectorType,       //通栏类别
                                sector_code: this.ruleForm.plateCode,        //通栏代码
                                page_type: this.ruleForm.pageType,           //页面类型
                                component_num: this.ruleForm.component_num,  //组件数量
                                sector_keyword: JSON.stringify(this.ruleForm.sectorKeyword), //通栏关键词
                                sector_img: this.ruleForm.image,           //通栏展示图
                                place_type: this.ruleForm.sectorPlace,           //通栏版式id
                                component_code: JSON.stringify(this.ruleForm.component_code),           //通栏所选组件
                                sector_width: this.ruleForm.sector_width,           //通栏宽度
                                sector_height: this.ruleForm.sector_height,           //通栏高度
                                pic_height: this.ruleForm.pic_height,           //画布高度
                            }
                            console.log('编辑表单---data', data);
                            this.$store.dispatch('plate/updateSector', data).then(data => {
                                if (data.code == 200) {
                                    this.$message({
                                        message: '编辑成功',
                                        type: 'success'
                                    })
                                    this.$router.push({
                                        path: '/plate',
                                    });
                                } else {
                                    this.$message({
                                        message: data.message,
                                        type: 'error'
                                    })
                                }
                            })
                        }
                    }else{
                        //验证关键词是否重复 start ------------------------------------------------------------>
                        let StringKeyword;
                        if(this.ruleForm.sectorKeyword.length == 1){
                            let ar = [];
                            ar.push(this.ruleForm.sectorKeyword[0]);
                            StringKeyword = JSON.stringify(ar);
                        }else{
                            StringKeyword = JSON.stringify(this.ruleForm.sectorKeyword);
                        }

                        let data = {
                            keyword: StringKeyword,
                            type : 'sector',
                            template_id:this.ruleForm.templateStyle,
                            id:this.$route.query.id
                        }
                        this.$store.dispatch('genre/checkRepeatKeyword', data).then(res => {
                            if (res.code == 200) {
                                
                                if (this.dialogName == "添加") {
                                    const data = {
                                        sector_name: this.ruleForm.sectorName,       //通栏名称
                                        sector_id: this.ruleForm.sectorId,           //通栏编号
                                        template_id: this.ruleForm.templateStyle,    //所属皮肤
                                        // size_id: this.ruleForm.size_id,             //通栏尺寸
                                        sector_type: this.ruleForm.sectorType,       //通栏类别
                                        sector_code: this.ruleForm.plateCode,        //通栏代码
                                        page_type: this.ruleForm.pageType,           //页面类型
                                        component_num: this.ruleForm.component_num,  //组件数量
                                        sector_keyword: JSON.stringify(this.ruleForm.sectorKeyword), //通栏关键词
                                        sector_img: this.logoUrl,           //通栏展示图
                                        place_type: this.ruleForm.sectorPlace,           //通栏版式id
                                        component_code: JSON.stringify(this.ruleForm.component_code),           //通栏所选组件
                                        sector_width: this.ruleForm.sector_width,           //通栏宽度
                                        sector_height: this.ruleForm.sector_height,           //通栏高度
                                        pic_height: this.ruleForm.pic_height,           //画布高度
                                    }
                                    console.log('添加表单--------data', data);
                                    this.$store.dispatch('plate/addSector', data).then(data => {
                                        if (data.code == 200) {
                                            this.$message({
                                                message: '添加成功',
                                                type: 'success'
                                            })
                                            this.$router.push({
                                                path: '/plate',
                                            });
                                        } else {
                                            this.$message({
                                                message: data.message,
                                                type: 'error'
                                            })
                                        }
                                    })
                                }
                                if (this.dialogName == "编辑") {
                                    const data = {
                                        id: this.$route.query.id,
                                        sector_name: this.ruleForm.sectorName,       //通栏名称
                                        sector_id: this.ruleForm.sectorId,           //通栏编号
                                        template_id: this.ruleForm.templateStyle,    //所属皮肤
                                        // size_id: this.ruleForm.size_id,             //通栏尺寸
                                        sector_type: this.ruleForm.sectorType,       //通栏类别
                                        sector_code: this.ruleForm.plateCode,        //通栏代码
                                        page_type: this.ruleForm.pageType,           //页面类型
                                        component_num: this.ruleForm.component_num,  //组件数量
                                        sector_keyword: JSON.stringify(this.ruleForm.sectorKeyword), //通栏关键词
                                        sector_img: this.ruleForm.image,           //通栏展示图
                                        place_type: this.ruleForm.sectorPlace,           //通栏版式id
                                        component_code: JSON.stringify(this.ruleForm.component_code),           //通栏所选组件
                                        sector_width: this.ruleForm.sector_width,           //通栏宽度
                                        sector_height: this.ruleForm.sector_height,           //通栏高度
                                        pic_height: this.ruleForm.pic_height,           //画布高度
                                    }
                                    console.log('编辑表单---data', data);
                                    this.$store.dispatch('plate/updateSector', data).then(data => {
                                        if (data.code == 200) {
                                            this.$message({
                                                message: '编辑成功',
                                                type: 'success'
                                            })
                                            this.$router.push({
                                                path: '/plate',
                                            });
                                        } else {
                                            this.$message({
                                                message: data.message,
                                                type: 'error'
                                            })
                                        }
                                    })
                                }

                            } else {
                                this.$message.error(res.message);
                            }
                        })
                        //验证关键词是否重复 end ------------------------------------------------------------>
                    }

                } else {
                    console.log(this.$refs[formName]);
                    return;
                }
            });
        },
        //取消添加或编辑
        cancelForm() {
            this.$router.push({
                path: '/plate',
            });
        },
        // 验证输入的数量
        validateCount() {
            // 确保是数字且在1-3范围内（因为输入框min为1，移除小于0的判断）
            let count = parseInt(this.component_num, 10);
            if (isNaN(count)) count = 1;
            if (count > 3) count = 3;
            this.component_num = count;
            // 初始化激活状态数组
            this.activeBoxes = Array(count).fill(false);
            // 初始化组件选择对象
            this.selectedComponents = {};
            for (let i = 0; i < count; i++) {
                this.selectedComponents[i] = [];
            }
        },
        // 切换方块激活状态
        toggleBox(index) {
            this.$set(this.activeBoxes, index, this.component_option[index])
        },
        //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.image = res.data.imgUrl;//提供表单地址
                console.log(res.data.imgUrl)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '网络错误，请重试！'
                });
            })
            // 阻止默认的上传行为
            return false;
        },
        handleDelete() {
            // 删除图片
            this.logoUrl = ''; // 清空图片 URL
        },
        // 关键词标签
        updateTags(newTags) {
            this.tags = newTags;
            this.ruleForm.sectorKeyword = newTags;
        },
    },
    mounted() {
        if (this.$route.query.id && this.$route.query.id != 0) {
            this.dialogName = '编辑',
                this.goEdit()
        } else {
            this.dialogName = '添加',
                this.addPlate()
        }
        this.getStyleList()
        this.getSkinList()
        this.getSectorType()
    },
    watch: {
        component_num(newVal) {
            this.validateCount();
        },
        'ruleForm.component_num': {
            handler(oldVal, newVal) {
                console.log('监听val', oldVal);
                console.log('监听newval', newVal);
                if (!(this.newVal !== null && this.dialogName == '编辑')) {
                    this.component_option = [];
                    this.ruleForm.component_code = [];
                    this.ruleForm.sectorPlace = '';
                }
            },
            deep: true
        }
    }
}
</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,
    .listEditBtn {
        margin-left: 0px;
        padding-left: 0px;
        margin-right: 20px;
        width: 76px;
        height: 36px;
        line-height: 36px;
    }

    ::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: 14px;
    }
}

.boxes-container {
    margin-left: 170px;
    width: 700px;
    height: 350px;
    margin-bottom: 25px;
    border: 1px dashed #d1d5db;
    border-radius: 6px;
    overflow: hidden;
}

.box {
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
}

.box:hover {
    filter: brightness(1.1);
}

.box.active {
    background-color: #1e40af;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.layout-3 {
    display: flex;
    height: 100%;
    /* 固定高度确保左右等高 */
    gap: 10px;
    padding: 10px;
}

.layout-3-left {
    flex: 1.5;
    display: flex;
    flex-direction: column;
    gap: 10px;
    height: 100%;
}

.layout-3-right {
    flex: 1;
    height: 100%;
}

.layout-3-left .box {
    height: 50%;
}

.layout-3 .box {
    background-color: #3b82f6;
    border-radius: 6px;
    height: 100%;
}

.layout-3-1 .box {
    background-color: #3b82f6;
    border-radius: 6px;
    height: 100%;
}

.layout-3-1-left {
    flex: 3;
    height: 100%;
}

.layout-3-1-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 10px;
    height: 100%;
}

.layout-3-1-right .box {
    height: 50%;
}

.layout-3-1-left .box {
    height: 100%;
}

.layout-3-1 {
    display: flex;
    height: 100%;
    gap: 10px;
    padding: 10px;
}

.layout-2 {
    display: flex;
    height: 100%;
    gap: 10px;
    padding: 10px;
}

.layout-2-left {
    flex: 5;
    height: 100%;
}

.layout-2-right {
    flex: 5;
    height: 100%;
}

.layout-2 .box {
    background-color: #3b82f6;
    border-radius: 6px;
    height: 100%;
    width: 100%;
}

/* 数量=1的布局 */
.layout-1 {
    height: 100%;
    padding: 10px;
}

.layout-1 .box {
    background-color: #3b82f6;
    border-radius: 6px;
    height: 100%;
    width: 100%;
}

/* 输入框区域样式 */
.input-fields {
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin-top: 20px;
}

.field-item {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 12px;
    background-color: #f9fafb;
    border-radius: 6px;
}

.field-label {
    width: 120px;
    font-weight: 600;
    color: #374151;
}

.size-select {
    flex: 1;
    padding: 8px;
    border: 1px solid #d1d5db;
    border-radius: 4px;
    height: 100px;
    background-color: white;
}

.size-select option {
    padding: 4px 0;
}

// 弹出层内容
.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: 30px auto 20px;
    clear: both;
    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;
}

.rowMargin {
    margin-top: 20px;
}

.componentChoose {
    background-color: #f5f7fb;
    overflow: hidden;
}

.componentOptions {
    float: left;
    margin-right: 30px;
    width: 100%;
}

.componentOption_one {
    width: 100%;
}
</style>