<!-- 组件 -->
<template>
    <div>
        <!-- 头部搜索框部分 -->
        <div class="title">
            <el-row>
                <el-col :span="6" class="left">
                    <div class="searchBox">
                        <div class="searchTitle">网站名称</div>
                        <el-input v-model="websiteName" clearable placeholder="请输入网站名称"></el-input>
                    </div>
                </el-col>
                <el-col :span="6" class="left">
                    <div class="searchBox">
                        <div class="searchTitle">文件名称</div>
                        <el-input v-model="imgAlias" clearable placeholder="请输入文件名称"></el-input>
                    </div>
                </el-col>
                <el-col :span="6" class="left">
                    <div class="searchBox">
                      <div class="searchTitle">文件类型</div>
                      <el-select v-model="imgType" placeholder="请选择文件类型" filterable clearable>
                        <el-option :key="'jpg'" :label="'jpg'" :value="'jpg'">jpg</el-option>
                        <el-option :key="'jpeg'" :label="'jpeg'" :value="'jpeg'">jpeg</el-option>
                        <el-option :key="'png'" :label="'png'" :value="'png'">png</el-option>
                      </el-select>
                    </div>
                  </el-col>
                <el-col :span="8" class="right">
                    <div class="btnList">
                        <button class="search" @click="goSearch">搜索</button>
                        <button class="reset" @click="goReset">重置</button>
                    </div>
                </el-col>
            </el-row>
        </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 fixed prop="id" label="编号" width="90"></el-table-column>
                        <el-table-column prop="img_alias" label="图片别名" width=""></el-table-column>
                        <el-table-column prop="img_type" label="图片类型" width=""></el-table-column>
                        <el-table-column prop="img_url" label="图片地址" width=""></el-table-column>
                        <el-table-column prop="img_size" label="文件大小" width=""></el-table-column>
                        <el-table-column prop="website_name" label="所属网站" width="">
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" width="200">
                            <template slot-scope="scope">
                              <div class="listBtnBox">
                                <div class="listDeleteBtn" @click="deleteRow(scope.row.id)">
                                  <i class="el-icon-delete"></i> 删除
                                </div>
                                <!-- 改为查看按钮 -->
                                <!-- 先检查按钮无法点击的常见原因，如样式是否有 pointer-events: none; 或者事件绑定是否正常 -->
                                <!-- 以下是原代码，可检查 viewImage 方法是否存在，以及 scope.row.id 是否有值 -->
                                <div class="listViewBtn" @click="handleViewImage(scope.row)">
                                <i class="el-icon-view"></i> 查看
                                </div>
                              </div>
                            </template>
                          </el-table-column>
                    </el-table>
                </template>
            </el-row>
        </div>
        <!--分页 start------------------------------------------------------------>
        <div class="alignBox">
            <el-row>
                <el-col :span="24">
                    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="page" :page-size="pageSize" layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </el-col>
            </el-row>
        </div>
        <!--分页 end------------------------------------------------------------>
        <!--表格内容 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="website_id">
                        <el-select v-model="ruleForm.website_id" :multiple="false" :multiple-limit="1" filterable remote
                            reserve-keyword placeholder="请输入关联网站名称" :remote-method="getWebNavList" :loading="webSiteLoading" @change="detectionWebSite">
                            <el-option v-for="item in webSiteList" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="文件别名:" prop="img_alias">
                        <el-input v-model="ruleForm.img_alias" placeholder="请输入文件别名"></el-input>
                    </el-form-item>
                    <el-form-item label="组件展示图:" prop="img_url" :label-width="formLabelWidth">
                        <div class="uploaderBox">
                            <!-- 图片预览和信息展示 -->
                            <div v-if="logoUrl" class="image-preview">
                                <img :src="logoUrl" class="avatar">
                                <div class="image-meta">
                                <p>文件名：{{ imageInfo.name }}</p>
                                <p>文件大小：{{ imageInfo.size }}</p>
                                </div>
                            </div>
                            <!-- 上传组件 -->
                            <el-upload v-else class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload">
                                <div class="chooseImgDiv">
                                    <img src="@/assets/public/upload/noImage.png">
                                    <div>选择图片</div>
                                </div>
                            </el-upload>
                            <!-- 删除按钮（仅添加时显示） -->
                            <div v-if="hovering && logoUrl" class="delete-button" @click="handleDelete">
                                <i class="el-icon-delete"></i>
                            </div>
                            </div>
                        </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----------------------------------------------------------->
        <!-- 新增图片查看弹框 -->
        <el-dialog title="图片预览" :visible.sync="viewImageVisible" width="80%"  top="5vh"    :close-on-click-modal="true">
            <div style="text-align: center; padding: 30px 0;">
                <!-- 显示放大图片 -->
                <img
                    :src="currentImageUrl"
                    alt="图片预览"
                    style="max-width: 90%; max-height: 70vh; border-radius: 12px; box-shadow: 0 0 20px rgba(0,0,0,0.1)"
                >
                <!-- 显示图片地址 -->
                <div style="margin-top: 20px; font-size: 14px; color: #666;">
                    <span>图片地址：</span>
                    <span style="word-break: break-all; color: #5570F1; margin-left: 10px;">
                        {{ currentImageUrl }}
                    </span>
                </div>
            </div>
        </el-dialog>


        
    </div>
</template>

<script>
//表格标题
import tableTitle from './components/tableTitle.vue';

//引入公用样式
import '@/styles/global.less';
import { getComponentList, addComponent, delComponent, updateComponent, getComponentInfo } from '@/api/module'
import { getSectorList } from '@/api/plate'
import { getTemplateClass } from '@/api/style'
export default {
    components: {
        tableTitle,//表格标题-
    },
    data() {
        const validateEmpty = (rule, value, callback) => {
            if (value.length == 0) {
                callback(new Error('该项不能为空！'))
            } else {
                callback()
            }
        }
        return {
            webSiteList: [], // 网站列表
             // 新增查看弹框相关变量
             viewImageVisible: false, // 控制弹框显示状态
             currentImageUrl: '', // 当前查看的图片地址
            websiteOptions: [], //网站列表
            // 新增图片信息字段
            imageInfo: { name: '', size: '', type: '' },
            // 移除 dialogName、activeid 等编辑相关变量
            dialogTableVisible: false, // 仅保留添加弹窗
            // 1.1 初始化数据
            tableDivTitle: "静态资源管理列表",  //列表标题
            dialogTableVisible: false,      //编辑弹框
            dialogName: '编辑', //编辑弹窗名称
            moduleLoading: true, //表格数据加载中

            tableData: [],//表格数据
            options: [],//版块列表
            activeid: "", //活动id
            styleOptions: [],//关联版块
            plateOptions: [],//关联版块
            selectedId: '',
            selectedOptions: [],
            cascaderProps: {
                value: "id", // 指定实际表示值的字段为id
                label: "name", // 指定实际表示显示文本的字段为name
                expandTrigger: 'hover',
                checkStrictly: true, // 严格模式，只能选择叶子节点
                children: 'children',
            },
            webSiteLoading: false,

            // 1.2 搜索框相关
            websiteName: '', //网站名称
            imgAlias: '', //文件别名
            imgType: '', //文件类型

            //3.4 上传logo图片
            logoUrl: '',
            hovering: false, // 鼠标悬浮状态 悬浮时显示删除

            value: '',


            // 分页相关
            page: 1,
            pageSize: 10,
            total: 0,


            formLabelWidth: '', //广告示例图相关


            template_id: '', //关联风格id
            sector_id: '', //关联版块id

            ruleForm: {
                img_alias: '', //组件名称
                img_url: '',//组件展示
                website_id: '', //关联网站名称
            },

            rules: {
                img_url: [{ required: true, trigger: 'blur', validator: validateEmpty }],
            }
        }
    },
    methods: {
        // 查看图片方法（修正方法名和参数）
        handleViewImage(row) {
            // 从行数据中获取图片地址（假设图片地址字段为 img_url，需根据实际数据调整）
            this.currentImageUrl = row.img_url;
            this.viewImageVisible = true;
        },
        //1.列表和分页相关 start ------------------------------------------------------------>
        //1.1 开始请求列表信息方法
        getData() {
            this.$store.dispatch('module/getStaticResourceList',{page: this.page,pageSize: this.pageSize}).then(res=> {
                console.log("*******************",res.data.row);
                this.tableData =  res.data.row; //给与内容
                this.total = res.data.count; //给与总条数
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '网络错误，请重试！'
                });
              })
        },
        //获取版块列表
        getList() {
            this.$store.dispatch('module/getStaticResourceList',{page: this.page,pageSize: this.pageSize}).then(res=> {
                console.log("*******************",res.data.row);
                this.tableData =  res.data.row; //给与内容
                this.total = res.data.count; //给与总条数
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '网络错误，请重试！'
                });
              })
        },
        //1.2 删除内容
        deleteRow(id) {
            console.log(id);
            let data = new FormData()
            data.append('id', id)
            this.$confirm('注意:删除后，该条信息及其绑定关系全部删除', '是否确认删除该条信息？', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                console.log("当前删除：" + id)
                this.$store.dispatch('module/delStaticResource', { id: id }).then(res => {
                    console.log(res.data);
                    if (res.code == 200) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        this.getData()
                    }
                }).catch(error => {
                    console.error('删除失败:', error);
                    this.$message({
                        message: '删除失败',
                        type: 'error'
                    });
                });

            }).catch(() => {
                this.$message({
                    type: 'warning',
                    message: '已取消删除'
                });
            });
        },
        // 1.3 查看图片
        viewImage(url) {
            // 打开图片放大弹框，这里假设存在一个名为 imageDialogVisible 的变量控制弹框显示，以及一个 imageUrl 变量存储要展示的图片地址
            this.dialogTableVisible = true;
            this.imageUrl = url;
        },

        handleChange(value) {
            console.log('val', value);
            this.template_id = value[0]
            this.sector_id = value[1]
            console.log("当前选中的父级：", this.template_id);
            console.log("当前选中的子级：", this.sector_id);
            // 当选中的选项发生变化时触发
            if (value.length > 0) {
                const selectedValue = value[value.length - 1]; // 获取最后一级选中的值
                this.fetchChildren(selectedValue); // 请求对应的子选项

            }
        },

        //1.4 列表内容分页
        //直接跳转
        handleSizeChange(val) {
            this.page = val;
            this.getData();
        },
        //1.5 点击分页
        handleCurrentChange(val) {
            this.page = val;
            this.getData();
        },
        // 1.6 搜索按钮
        goSearch() {
            const data = {
                website_name: this.websiteName, //网站名称
                img_alias: this.imgAlias, //文件别名
                img_type: this.imgType, //文件类型
                page: 1, //页码
                pageSize: 10, //每页条数
            }
            this.$store.dispatch('module/getStaticResourceList',data).then(res=> {
            // console.log("*******************",this.page);
            console.log("*******************",res.data.row);
            this.tableData =  res.data.row; //给与内容
            this.total = res.data.count; //给与总条数
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '网络错误，请重试！'
            });
            })
        },
        //1.7 重置按钮
        goReset() {
            this.websiteName = ""
            this.imgAlias = ""
            this.imgType = ""
            this.page = 1
            this.pageSize = 10
            this.getData()
        },
        //列表和分页相关 end ------------------------------------------------------------>
        getWebNavList(query) {
            if (query !== '') {
                this.webSiteLoading = true;
                let data = { keyword: query }
                console.log("-----------------",data);
                let dataArr = [];
                this.$store.dispatch('pool/getNavWebList', data).then(res => {
                    console.log(res.data)
                    for (let item of res.data) {
                        let data = {};
                        data.key = item.id;
                        data.value = item.id;
                        data.label = item.website_name;
                        dataArr.push(data)
                    }
                    this.webSiteList = dataArr;
                    this.webSiteLoading = false;
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '网络错误，请重试！'
                    });
                })
            } else {
                this.navList = [];
            }
        },
        //1.8 添加
        addWebsite() {
            this.dialogTableVisible = true
            this.dialogName = "添加"
            //添加时清空回显回来的数据
            this.ruleForm.website_id = '' //网站id
            this.ruleForm.img_alias = '' //图片别名
            this.ruleForm.img_size = '' //图片大小
            this.ruleForm.img_url = '' //图片地址
            this.logoUrl = '' //图片展示图
            console.log("添加",this.ruleForm);

        },
        // 弹出层相关方法
        // 提交表单
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    console.log('submit!');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
            if (this.dialogName === "添加") {
                // 直接从 data 中获取参数
                if(this.ruleForm.website_id == 'undefind' || this.ruleForm.website_id == ''){
                    this.ruleForm.website_id = 0;
                }
                const data = {
                    img_alias: this.ruleForm.img_alias,
                    img_url: this.ruleForm.img_url,
                    website_id: this.ruleForm.website_id ?? 0,
                    img_size: this.imageInfo.size,
                };
                console.log("添加", data);
                // 直接传递 data 作为参数，而不是 {data}
                this.$store.dispatch('module/addStaticResource', data).then(res => {
                    console.log("66666666666666666",res.data);
                    if (res.code === 200) {
                        this.$message({
                            message: '添加成功',
                            type:'success'
                        });
                        this.dialogTableVisible = false;
                        this.getData();
                    } else if (res.code === 0) {
                        this.$message({
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch(error => {
                    console.error('添加失败:', error);
                    this.$message({
                        message: '添加过程中出现错误，请重试',
                        type: 'error'
                    });
                });
            }

            if (this.website_id == '') {
                this.$message({
                    message: '请输入并选择网站名称',
                    type: 'error'
                })
                this.dialogVisible = true
            }
            if (this.dialogName == "编辑") {
                updateComponent({
                    id: this.activeid,
                    img_alias: this.ruleForm.img_alias,
                }).then(data => {
                    console.log(data);
                    if (data.code == 200) {
                        this.$message({
                            message: '编辑成功',
                            type: 'success'
                        })
                        this.dialogTableVisible = false
                    }
                    if (data.code == 0) {
                        this.$message({
                            message: data.message,
                            type: 'error'
                        })
                        this.dialogTableVisible = true
                    }
                    this.getData()
                })
            }

        },
        //取消添加或编辑
        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;
            }
          
            // 解析图片信息
            this.imageInfo.name = file.name;
            this.imageInfo.size = this.formatFileSize(file.size); // 新增格式化方法
            this.imageInfo.type = file.type.split('/')[1].toUpperCase(); // 获取文件类型（JPG/PNG）
          
            const formData = new FormData();
            formData.append('file', file);
          
            this.$store.dispatch('pool/uploadFile', formData).then(res => {
              this.logoUrl = res.data.imgUrl;
              this.ruleForm.img_url = res.data.imgUrl;
            }).catch(() => {
              this.$message({ type: 'info', message: '网络错误，请重试！' });
            });
          
            return false;
        },
          
        // 新增文件大小格式化方法
        formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const units = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(1024));
        return `${parseFloat((bytes / Math.pow(1024, i)).toFixed(2))} ${units[i]}`;
        },
        handleDelete() {
            // 删除图片
            this.logoUrl = ''; // 清空图片 URL
        },

        //搜索部分的输入关键词下拉框
        selectWebSite(value) {
            this.webSiteName_id = value
        },

        //添加 / 编辑弹窗中输入关键词下拉框 
        // 判断是否已经关联了网站
        detectionWebSite(value) {
            console.log(value);
            this.website_id = value
            console.log(this.website_id);

        },


    },
    mounted() {
        this.getData()
        this.getList()
    },
}
</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;
    }
    .listViewBtn {
        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: 16px;
    }
}

// 弹出层内容
.dialogText {
    margin: 0 7px 0 3px;
    padding-bottom: 1px;
    padding: 30px 60px 1px 20px;
    background-color: #f5f7fb;

    .el-cascader--medium {
        font-size: 14px;
        line-height: 36px;
        width: 100%;
    }

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

// 弹出层按钮
.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;
}
/* 可选：添加弹框内图片样式 */
.el-dialog__body {
    padding: 30px !important;
    text-align: center;
  }
</style>