<template>
    <div class="main-content12">
        <div class="elementWrap">
            <div>
                <!-- page header -->
                <div class="pageheader"> 
                    <div class="pageheader-left"> 
                        <span class="pagetitle">站点列表</span>
                        <GuipButton @click="showAddGroup" type="ignore">
                            <svg-icon :size="16" :path="require('@/assets/site/addIcon.svg')" :color="'#8A9099'" :hoverColor="'#006AFF'" />新增分组
                        </GuipButton>
                        <el-form>
                            <GuipSelect v-model="currentGroup" :options="siteGroups" defaultValue="选项1"  labelKey="name" valueKey="id" style="margin-bottom: 0px;" clearable />
                        </el-form>
                    </div> 
                    <GuipButton size="table" @click="addNewSite">新增站点</GuipButton> 
                </div>

                <!-- page content -->
                <el-form>
                    <GuipTable :tableData="filteredSites" ref="multipleTable" @selectChange="handleSelectionChange" autoColumn="true" :loading="tableLoading">

                        <el-table-column prop="short_name" label="站点简称">
                            <template slot-scope="scope">
                                <div class="flex cell_render">
                                    <el-link :href="scope.row.domain" target="_blank" class="black">{{ scope.row.short_name }}</el-link>
                                    <svg-icon :size="16" :path="require('@/assets/site/form_link.svg')" :color="'#8A9099'" :hoverColor="'#006AFF'" />
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="regtime" label="注册时间"></el-table-column>

                        <el-table-column prop="group" label="站点分组">
                            <template #default="{ row,$index }">
                                <el-popover v-model="row.showPopover" 
                                            placement="top" 
                                            trigger="manual" :append-to-body="false"  :visible-arrow="true"
                                            popper-class="custom-popover">

                                    <div class="group_select">
                                        <GuipSelect v-model="selected_group" :options="siteGroups" defaultValue="站点分组" labelKey="name" valueKey="id" placeholder="请选择分组" @change="addSiteGroupIndex(row)" />
                                    </div>
                                    <template #reference>
                                        <div class="flex cell_render" @click="groupSetting(row, $index)">
                                            <span v-if="row.group">{{ row.group }}</span>
                                            <span class="gray" v-else>未分组</span>
                                            <svg-icon :size="16" :path="currentIcon" :color="'#8A9099'" :hoverColor="'#006AFF'" />
                                        </div>
                                    </template>
                                </el-popover>
                            </template>
                        </el-table-column>

                        <el-table-column prop="phone_services" label="手机服务">
                            <template slot="header">
                                <div class="flex cell_render">
                                    <span>手机服务</span>
                                </div>
                                <el-popover placement="bottom" trigger="click">
                                    <el-select v-model="currentPhoneService" clearable placeholder="请选择" >
                                        <el-option v-for="item in phoneServices" :key="item.id" :label="item.value" :value="item.id"></el-option>
                                    </el-select>
                                    <el-image class="ml-4 mt-6" :src="fitlerIcon" slot="reference"></el-image>
                                </el-popover>
                            </template>
                            <template slot-scope="scope">
                                <span v-if="scope.row.phone_services">{{ scope.row.phone_services }}</span>
                                <span class="gray" v-else>一</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="config_progress_status_desc" label="状态">
                            <template slot-scope="scope">
                                <div class="flex cell_render">
                                    <span class="green" v-if="scope.row.config_progress_status == 5">{{ scope.row.config_progress_status_desc }}</span>
                                    <div class="flex cell_render" v-else>
                                        <span class="red">{{ scope.row.config_progress_status_desc }}</span>
                                        <svg-icon :size="16" :path="require('@/assets/site/more.svg')" :color="'#8A9099'" :hoverColor="'#006AFF'" @click="toggleIcon" />
                                    </div>
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" fixed="right">
                            <el-link type="primary" :href="serviceListUrl" target="_blank" class="mr-16">服务列表</el-link>
                            <el-link type="primary" :href="siteSettingUrl" target="_blank">站点设置</el-link>
                        </el-table-column>

                    </GuipTable>

                    <!-- 新增分组 --->
                    <GuipDialog :dialogVisible="addGroupDialogVisible" title="新增分组" :show-close-button="false"
                        :show-cancel-button="showCancelButton" @confirm="addGroup" @cancel="cancleAddGroup"
                        @close="closeAddGroup" @addGroupDialogVisibleChange="addGroupDialogVisibleChange">
                        <div>
                            <GuipInput ref="GuipInput" addClass="w510" v-model="groupname" label="分组名称" prop="groupid" placeholder="请输入分组名称" />
                        </div>
                    </GuipDialog>
                </el-form>
            </div>
            <Footer></Footer>
        </div>
    </div>
</template>

<script>

import GuipTable from '@/components/GuipTable.vue';
import Footer from '@/components/Footer.vue';
import SvgIcon from '@/components/SvgIcon.vue';
import GuipSelect from '@/components/GuipSelect.vue';
import GuipButton from '@/components/GuipButton.vue';
import GuipInput from '@/components/GuipInput.vue';
import GuipDialog from '@/components/GuipDialog.vue';

export default {
    name: 'siteList',
    components: {
        Footer,
        GuipTable,
        SvgIcon,
        GuipSelect,
        GuipButton,
        GuipInput,
        GuipDialog,
    },
    data() {
        return {
            // AUTH
            token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NTAwNTM3MjQsIm5iZiI6MTc1MDA1MzcyNCwiZXhwIjoxNzUyNjQ1NzI0LCJ1c2VyIjoic3VidXNlciIsImxvZ2luX3R5cGUiOjAsImFpZCI6IjEifQ.xyIqBLelB-k6jCifgRevBJTyg_Qrm6m1e4OcHhOpepU',
            // 表格加载
            tableLoading: true,
            // 站点列表
            siteList: [],
            // 站点分组
            siteGroups: [],
            // 分组id
            gid: 0,
            // 服务列表url
            serviceListUrl: '/ui',
            // 站点设置url
            siteSettingUrl: '/ui',
            // 新增站点url
            addNewSiteUrl: '/ui',
            popoverFlag:false,
            // 站点分组名称
            selected_group: '',
            isUpIco: false, 
            currentIcon: require('@/assets/site/drop_icon.svg'),
            currentGroup: '',
            fitlerIcon: require('@/assets/site/filter.svg'),
            // 手机服务
            phoneServices: [
                {'id': 0,  value: '不限' },
                {'id': 1,  value: '微信H5' },
                {'id': 2,  value: '小程序' },
            ],
            // 当前选中的手机服务
            currentPhoneService: '',
            // 添加分组弹框显示标识
            addGroupDialogVisible: false,
            // 取消按钮显示
            showCancelButton: true,
            // 确定按钮显示
            groupname: '',
        }
    },
    mounted() {
        this.getSiteList()
        this.getSiteGroups()
    },
    methods: {
        // 获取站点列表
        getSiteList() {
            this.tableLoading = true
            const that = this
            that.siteList = []
            this.$http('POST', '/agentnew/ajax_get_site_list', {
                gid: this.gid,
            },{
                headers:{
                    'Auth': this.token
                }
            }).then(response => {
                this.tableLoading = false
                this.$nextTick(() => {
                    that.siteList = response.data.sitelist
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        // 获取站点分组
        getSiteGroups() {
            const that = this
            that.siteGroups = []
            this.$http('POST', '/agentnew/ajax_get_site_groups', {
                gid: this.gid,
            },{
                headers:{
                    'Auth': this.token
                }
            }).then(response => {
                this.$nextTick(() => {
                    that.siteGroups = response.data
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        // 点击站点分组单元格时触发
        groupSetting(row, index) {
            // 如果已经打开当前行的弹框，则关闭
            if (row.showPopover === true) {
                row['showPopover'] = false;
                // 切换图标
                this.toggleIcon();

                return;
            }

            // 如果存在分组 则显示已设置分组
            if (row.group) {
                this.selected_group = row.group;
            }

            // 关闭其他行的弹框
            this.popoverFlag = true;
            this.siteList.forEach((item, i) => {
                if (i !== index) {
                    item['showPopover'] = false;
                }
            });
            // 打开当前行的弹框
            row['showPopover'] = true;

            // 切换图标
            this.toggleIcon();
        },
        // 保存站点分组
        addSiteGroupIndex(row) {
            this.$http('POST', '/agentnew/ajax_add_site_group_index', {
                groupid: this.selected_group,
                uid: row.uid,
            },{
                headers:{
                    'Auth': this.token
                }
            }).then(response => {
                if (response.status) {
                    // 保存成功弹层提示
                    this.$message.success(response.info);

                    // 更新分组名称
                    this.siteGroups.forEach((item) => {
                        if (item.id === this.selected_group) {
                            row['group'] = item.name; 
                        }
                    });
                    row['groupid'] = this.selected_group; // 更新价格
                    row['showPopover'] = false; // 关闭弹框
                    this.$set(this.siteList, row)
                    this.currentIcon = require('@/assets/site/drop_icon.svg');
                } else {
                    this.$message.error(response.info);
                }
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        // 取消编辑
        cancleGroupIndexSetting(row) {
            // 关闭弹框
            row['showPopover'] = false;
            this.popoverFlag = false
            // row[type + '_popover'] = false; // 关闭弹框
            this.currentIcon = require('@/assets/site/drop_icon.svg');
            this.$Message.info('已取消编辑');
            
        },
        toggleIcon() {
            this.isUpIco = !this.isUpIco; // 切换状态
            
            // 根据状态更新图标和颜色
            if (this.isUpIco) {
                this.currentIcon = require('@/assets/site/up_icon.svg'); // 向上图标
            } else {
                this.currentIcon = require('@/assets/site/drop_icon.svg'); // 向下图标
            }
        },
        // 表格点击、选择
        handleSelectionChange(data) {
            // 多选模式下的时候 data 为数组格式
            // 单选的时候是 对象
            console.log(data, '表格行信息');
        },
        // 弹框相关方法---start
        showAddGroup() {
            this.addGroupDialogVisible = true;
        },
        // 确认按钮事件
        addGroup() {
            this.addGroupDialogVisible = false;

            this.$http('POST', '/agentnew/ajax_add_site_group', {
                name: this.groupname,
            },{
                headers:{
                    'Auth': this.token
                }
            }).then(response => {
                this.$nextTick(() => {
                    if (response.status) {
                        this.$message.success(response.info);
                        // 更新分组
                        this.getSiteGroups()
                        // 清空分组名称
                        this.groupname = ''
                    } else {
                        this.$message.error(response.info);
                    }
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        // 取消按钮事件
        cancleAddGroup() {
            this.addGroupDialogVisible = false;
        },
        // 关闭弹框事件
        closeAddGroup() {
            this.addGroupDialogVisible = false;
        },
        addGroupDialogVisibleChange(data) {
            console.log(data, 'data098908090');
        },
        // 弹框相关方法---end
        addNewSite() {
            window.open(this.addNewSiteUrl, '_blank');
        }
    },
    computed: {
        // 筛选表格数据
        filteredSites() {
            let result = this.siteList;
            if (this.currentGroup) {
                result = result.filter(site => site.groupid == this.currentGroup);
            }

            if (this.currentPhoneService >= 0) {
                if (this.currentPhoneService == 1) {
                    result = result.filter(site => site.is_open_h5 == 1);
                } else if (this.currentPhoneService == 2) {
                    result = result.filter(site => site.is_open_xcx == 1);
                }
            }
            return result;
        }
        
    },
}
</script>
<style lang="scss" scoped>
.elementWrap {
    padding: 32px 36px;
    background: #fff;
}

.pageheader { 
    display: flex; 
    justify-content: space-between; /* 关键属性 */ 
    align-items: center; 
    margin: 16px 0px 16px 0px;
} 
.pageheader-left { 
    display: flex; /* 左侧按钮组也是flex布局 */ 
    gap: 15px; /* 按钮间距 */ 
}

.pagetitle {
    font-size: 18px;
    font-weight: bold;
    line-height: normal;
    letter-spacing: 0.08em;
    color: #1E2226;
    margin-top:8px;
}

.mr-16 {
    margin-right: 16px;
}
.ml-4 {
    margin-left: 4px;
}
.mt-6 {
    margin-top: 6px;
}

.red {
    color: #FF4D4F;
}
.green {
    color: #0DAF49;
}
.black {
    color: #1E2226;
}
.gray {
    color: #8C8C8C;
}

::v-deep .custom-popover {
    position: fixed !important;
    // max-height: 290px;
    // overflow-y: auto;
    margin-top: 0 !important;
    margin-left: 0 !important;
    transform: none !important;
}

</style>