<template>
    <Breadcrumb pageTitle="审核列表"></Breadcrumb>
    <div class="space"></div>
    <el-card v-loading="loading">
        <el-header>
            <div class="action-bar-container">
                <el-space class="action-bar-item-container action-bar-action-left">
                    <el-button-group class="ml-4">
                        <!-- <el-button type="primary" :icon="Refresh" @click="resetFilterAndRefreshTableList">刷新</el-button> -->
                        <el-button type="primary" :icon="Box" @click="doBatchRollback" v-if="showBatchListing">批量打回</el-button>
                        <el-button type="primary" :icon="Box" @click="doBatchListing" v-if="showBatchListing">批量上线</el-button>
                        <el-button type="primary" :icon="Box" @click="doUnBatchListing" v-if="showBatchListing">批量下架</el-button>
                    </el-button-group>
                </el-space>
                <el-space class="action-bar-item-container action-bar-action-right">
                    <div class="action-bar-item" v-if="showModifyUserFilter">
                        <span class="action-bar-name">维护人：</span>
                        <el-select v-model="filters.modifyuser" style="width: 110px" @change="onModifyUserSelectChange" :disabled="modifyUserSelectDisabled">
                            <el-option
                                v-for="item in filterConfig.modifyUserList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </div>
                    <div class="action-bar-item">
                        <span class="action-bar-name">爬虫状态：</span>
                        <el-select v-model="filters.state" placeholder="爬虫状态" style="width: 110px" @change="onStateSelectChange">
                            <el-option
                                v-for="item in filterConfig.stateOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </div>
                    <!-- <div class="action-bar-item">
                        <span class="action-bar-name">认领状态：</span>
                        <el-select v-model="filters.claimtype" placeholder="认领状态" style="width: 110px" @change="onClaimSelectChange">
                            <el-option
                                v-for="item in filterConfig.claimOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                :disabled="item.disabled"
                            />
                        </el-select>
                    </div> -->
                    <div class="action-bar-item">
                        <el-input v-model="filters.search" placeholder="按照站点、爬虫代码搜索" @keydown.enter="onInputSearch" />
                    </div>
                    <div class="action-bar-item">
                        <el-button type="primary" :icon="Search" @click="onInputSearch">搜索</el-button>
                    </div>
                </el-space>
            </div>
        </el-header>
        <el-main>
            <el-table ref="spiderTable" :data="listState.list" stripe :row-style="getRowStyle" @selection-change="handleSelectionChange" v-loading="listState.loading">
                <el-table-column type="selection" width="55" :selectable="tableRowSelectable" v-if="isAdmin" />
                <el-table-column prop="site" label="网站" align="left" show-overflow-tooltip></el-table-column>
                <el-table-column prop="channel" label="栏目" align="left" show-overflow-tooltip></el-table-column>
                <el-table-column prop="code" label="代码" align="left" show-overflow-tooltip></el-table-column>
                <el-table-column prop="stateText" label="爬虫状态" width="80" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="claimText" label="认领状态" width="100" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="href" label="栏目地址" show-overflow-tooltip></el-table-column>
                <el-table-column prop="modifyuser" label="维护人" width="80" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" width="160" align="center">
                    <template #default="scope">
                  <!-- <el-tooltip content="标注" placement="top">
                            <el-button size="small" :class="{ active: scope.row._action_clicked_mark }" @click="tableEvents.handleDataTag(scope.row)">
                                <el-icon><Link /></el-icon>
                            </el-button>
                        </el-tooltip>-->
                        <el-tooltip content="编辑" placement="top">
                            <el-button size="small" :class="{ active: scope.row._action_clicked_edit }" @click="tableEvents.handleEdit(scope.$index, scope.row)">
                                <el-icon><Edit /></el-icon>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="调试" placement="top">
                            <el-button size="small" :class="{ active: scope.row._action_clicked_debug }" @click="tableEvents.handleDebug(scope.$index, scope.row)">
                                <el-icon><SetUp /></el-icon>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="验证" placement="top">
                            <el-button size="small" :class="{ active: scope.row._action_clicked_verify }" @click="tableEvents.handleVerify(scope.$index, scope.row)">
                                <el-icon><Aim /></el-icon>
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="功能" width="160" align="center">
                    <template #default="scope">
                        <!-- 管理员：上线和退回 -->
                        <template v-if="tableActionShow.adminGroup(scope.row)">
                            <el-tooltip content="下架" placement="top" v-if="tableActionShow.downCode(scope.row)">
                                <el-button size="small" :class="{ active: scope.row._action_clicked_down_code }" :disabled="actionButtonDisabled.adminDownCode(scope.row)" @click="tableEvents.adminDownCode(scope.$index, scope.row)">
                                  <el-icon><CircleCloseFilled /></el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="打回" placement="top" v-if="tableActionShow.adminReject(scope.row)">
                              <el-button size="small" :class="{ active: scope.row._action_clicked_reject_code }" :disabled="actionButtonDisabled.adminReject(scope.row)" @click="tableEvents.adminReject(scope.$index, scope.row)">
                                <el-icon><CircleClose /></el-icon>
                              </el-button>
                            </el-tooltip>
                            <el-tooltip content="上线" placement="top" v-if="tableActionShow.adminSubmit(scope.row)">
                                <el-button size="small" :class="{ active: scope.row._action_clicked_submit }" :disabled="actionButtonDisabled.adminSubmit(scope.row)" @click="tableEvents.adminSubmit(scope.$index, scope.row)">
                                    <el-icon><UploadFilled /></el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="退回" placement="top" v-if="tableActionShow.adminRollback(scope.row)">
                                <el-button size="small" :class="{ active: scope.row._action_clicked_rollback }" @click="tableEvents.adminRollback(scope.$index, scope.row)">
                                    <el-icon><DArrowLeft /></el-icon>
                                </el-button>
                            </el-tooltip>
                        </template>
                        <!-- 审核人员：通过和打回，管理员也有此功能 -->
                        <el-tooltip content="通过" placement="top" v-if="tableActionShow.reviewerGroup(scope.row)">
                            <el-button size="small" :class="{ active: scope.row._action_clicked_submit }" :disabled="actionButtonDisabled.reviewerSubmit(scope.row)" @click="tableEvents.reviewerSubmit(scope.$index, scope.row)">
                                <el-icon><CircleCheck /></el-icon>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="打回" placement="top" v-if="!actionButtonDisabled.reviewerRollback(scope.row)">
                            <el-button size="small" :class="{ active: scope.row._action_clicked_rollback }" @click="tableEvents.reviewerRollback(scope.$index, scope.row)">
                                <el-icon><CircleClose /></el-icon>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="退回" placement="top" v-if="tableActionShow.reviewerRollback2(scope.row)">
                          <el-button size="small" :class="{ active: scope.row._action_clicked_reject_code }" @click="tableEvents.adminRollback(scope.$index, scope.row)">
                            <el-icon><DArrowLeft /></el-icon>
                          </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <div class="space"></div>
            <div class="pagination-container">
                <el-pagination align="right" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="listState.pageNum" :page-sizes="[10, 20, 30, 40]" :page-size="listState.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="listState.total">
                </el-pagination>
            </div>
        </el-main>
    </el-card>
    <EditSpider
        ref="editSpiderDialog"
        from="reviewList"
        @custom-event="dialogEvents.editSpiderConfigSaveEvent"
        @data-tag="editDialogMarkClick($event)"
    />
    <RunSpiderDialog from="reviewList" ref="runSpiderDialog" />
    <VerifySpider ref="verifySpiderDialog" />
    <el-dialog v-model="dialog.rollbackReason" title="选择退回原因" width="500">
      <el-form>
        <el-form-item label="退回原因">
          <el-select v-model="filters.rollbackReason" placeholder="请选择">
            <el-option v-for="item in filterConfig.rollbackOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.rollbackReason = false">取消</el-button>
          <el-button type="primary" @click="tableEvents.confirmRollbackReason(currentEditRow)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, reactive, watch } from 'vue'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus'
import { BrowserOpenURL, EventsOn } from "../../wailsjs/runtime"
import { VerifySpiderConfig, ServerActionUpdateCodeState, ServerActionCurrentOpenTab } from "../../wailsjs/go/main/App"
import Breadcrumb from "../components/Breadcrumb.vue"
import EditSpider from "../components/spider/EditSpider.vue"
import RunSpiderDialog from "../components/spider/RunSpiderDialog.vue"
import VerifySpider from "../components/spider/VerifySpider.vue"
import { useReviewListFiltersWithRole } from '../composables/filter-options'
import { USER_ROLE_ADMIN, USER_ROLE_DEVELOPER, USER_ROLE_REVIEWER } from '../data/user'
import { Refresh, Search, Box } from '@element-plus/icons-vue'
import { rollbackReasonList } from "../data/index.js";

const router = useRouter();
const store = useStore();
const spiderTable = ref(null)

const { stateOptions, claimOptions } = useReviewListFiltersWithRole()

const loading = ref(false)

const filterConfig = reactive({
    // 爬虫状态备选项
    stateOptions: stateOptions,
    // 认领状态备选项
    claimOptions: claimOptions,
    // 维护人备选项
    modifyUserList: [
        {
            label: '全部',
            value: '-1',
        }
    ],
    rollbackOptions: rollbackReasonList
})


// 选择器数据(用来重置)
const defaultFilters = {
    // 搜索
    search: '',
    // 爬虫状态(审核员默认待审核1，管理员默认已通过3)
    state: 1,
    // 维护人
    modifyuser: '-1',
    // 认领状态
    claimtype: -1,
    rollbackReason: undefined,
}
// 选择器数据
const filters = reactive({
    // 搜索
    search: '',
    // 爬虫状态(审核员默认待审核1，管理员默认已通过3)
    state: 1,
    // 维护人
    modifyuser: '-1',
    // 认领状态
    claimtype: -1,
    rollbackReason: undefined,
})

// 列表数据
const listState = reactive({
    loaded: false,
    loading: false,
    pageNum: 1, // 页码
    pageSize: 10, // 每页多少条
    total: 0, // 返回的总数据条数
    list: [ // 数据列表
        // {
        //     code: '爬虫代码', 
        //     site: '网站',
        //     channel: '栏目',
        //     href: '栏目地址',
        //     modifyuser: '维护人',
        //     _id: 'asfasf',
        // },
    ],
    // 已选中列表
    selected: [],
})
// 列表默认数据(用来重置)
const defaultListState = {
    loaded: false,
    loading: false,
    pageNum: 1,
    pageSize: 10,
    total: 0,
    list: [],
}

const dialog = reactive({
  rollbackReason: false
})

// 当前编辑的row的数据
const currentEditRow = ref({})
// 上一个点击的row的数据
const prevClickedRow = ref({})

// 用户身份标识
const userRole = computed(() => store.getters.userRole)
// 是否展示维护人模块(管理员和审核员展示)
const showModifyUserFilter = computed(() => [USER_ROLE_ADMIN, USER_ROLE_REVIEWER].includes(userRole.value))

// 实现待认领不能和维护人同时筛选
// 是否禁用维护人模块(待认领筛选下，禁用维护人筛选模块)
const modifyUserSelectDisabled = computed(() => filters.claimtype === 0)
// 是否禁用待认领筛选(维护人不为全部，则禁用待认领的选中)
// const stopWatch = watch(() => filters.modifyuser, (n) => {
//     const target = filterConfig.claimOptions.find(i => i.value === 0)
//     if (target) {
//         if (n === defaultFilters.modifyuser) {
//             // 解除禁用待认领
//             target.disabled = false
//         } else {
//             // 禁用待认领
//             target.disabled = true
//         }
//     } else {
//         stopWatch()
//     }
// })
const isReviewer = computed(() => [USER_ROLE_REVIEWER].includes(userRole.value))
const isAdmin = computed(() => [USER_ROLE_ADMIN].includes(userRole.value))
const showBatchListing = computed(() => isAdmin.value)

const changeFilterDefaultValue = () => {
    // 根据用户身份
    // 爬虫状态(审核员默认待审核1，管理员默认已通过3)
    if ([USER_ROLE_ADMIN].includes(userRole.value)) {
        // 管理员
        filters.state = 3
        defaultFilters.state = 3
    }
}
changeFilterDefaultValue()

const editSpiderDialog = ref(null)
const runSpiderDialog = ref(null)
const verifySpiderDialog = ref(null)

// 取消prevClicked的高亮
const cancelOtherHighlight = () => {
    for (const key in prevClickedRow.value) {
        if (key.includes('_action_clicked')) {
            prevClickedRow.value[key] = false
        }
    }
}
// 页面按钮点击高亮
const onlyClickHighlight = (row, key) => {
    cancelOtherHighlight()
    row[key] = true
    prevClickedRow.value = row
}

const getRowStyle = ({ row }) => {
    return row.selected ? { backgroundColor: '#F7F7F7' } : {};
};

const handleSelectionChange = (r) => {
    listState.selected = r
}

// 计算爬虫状态
const calcStateText = (state) => {
    const target = filterConfig.stateOptions.find(r => r.value === state)
    if (target) {
        return target.label
    } else {
        return ''
    }
}
// 计算认领状态
const calcClaimText = (state) => {
    const target = filterConfig.claimOptions.find(r => r.value === state)
    if (target) {
        return target.label
    } else {
        return ''
    }
}
// 获取列表数据
async function getTableList() {
    listState.loading = true
    try {
        const r = await store.dispatch('rulesList/getCodeList', {
            modifyuser: filters.modifyuser, // 维护人
            state: filters.state, // 爬虫状态
            search: filters.search, // 搜索内容
            claimtype: filters.claimtype,
            pageType: 'reviewlist',
            pageSize: listState.pageSize,
            pageNum: listState.pageNum
        });
        const { data, err, msg } = r
        if (data) {
            listState.total = data.total || 0
            if (Array.isArray(data.list)) {
                const sList = data.list.map(t => {
                    return {
                        ...t,
                        stateText: calcStateText(t.state),
                        claimText: calcClaimText(t.claimtype),
                        // 操作按钮是否点击过
                        _action_clicked_mark: false,
                        _action_clicked_edit: false,
                        _action_clicked_debug: false,
                        _action_clicked_verify: false,
                        _action_clicked_down_code: false,
                        _action_clicked_reject_code: false,
                        _action_clicked_submit: false,
                        _action_clicked_rollback: false,
                    }
                })

                listState.list = sList || []
            }
        }
    } catch (error) {
        listState.loaded = true
    } finally {
        listState.loading = false
    }
}

// 重置列表数据
const resetListState = () => {
    Object.assign(listState, defaultListState)
}
// 重置选择器数据
const resetFilterState = () => {
    Object.assign(filters, defaultFilters)
}

// 刷新列表(不重置选择器)
function refreshTableList() {
    resetListState()
    getTableList()
}
// 刷新列表(并重置选择器)
function resetFilterAndRefreshTableList() {
    resetFilterState()
    refreshTableList()
}

getTableList()

const handleSizeChange = (val) => {
    listState.pageSize = val;
    listState.pageNum = 1;
    getTableList()
};

const handleCurrentChange = (val) => {
    listState.pageNum = val;
    getTableList()
};

// 获取维护人列表
const getModifyUserList = async () => {
    const r = await store.dispatch('rulesList/getModifyUserList')
    const { data, err, msg } = r
    if (data) {
        if (Array.isArray(data.list)) {
            const arr = filterConfig.modifyUserList
            const reqArr = data.list.map(r => {
                return {
                    label: r.s_name,
                    value: r.s_name,
                }
            })
            filterConfig.modifyUserList = arr.concat(reqArr)
        }
    }
}
getModifyUserList()

const onModifyUserSelectChange = () => {
    refreshTableList()
}
const onStateSelectChange = () => {
    refreshTableList()
}
const onInputSearch = () => {
    refreshTableList()
}
const onClaimSelectChange = () => {
    refreshTableList()
}

// 保存完成后(不刷新优化)，同步更新表单内的数据
const refreshRowData = (code, payload) => {
    const target = listState.list.find(item => item.code === code)
    if (target) {
        if (target.cssmark) {
            Object.assign(target.cssmark, payload)
        } else {
            target.cssmark = payload            
        }
    }
}
// 更新编辑弹窗数据
const refreshAndAsyncEditDialog = (key, value) => {
    editSpiderDialog.value.refreshPageData(key, value)
}

// 打开编辑弹窗(如果传数据了，则恢复数据)
const openEditDialog = (row) => {
    editSpiderDialog.value.dialogVisible = true
    if (row) {
        editSpiderDialog.value.setPageData({
            ...row,
            ...row.cssmark,
        })
    }
}

// 管理员身份  待审核和未通过。通过打回按钮显示不能点
// 管理员身份  已通过，只有上线，其他不展示
// 管理员   已上线。只有退回按钮


// 操作按钮组的显示隐藏控制
const tableActionShow = {
    reviewerGroup(row) {
        // 已通过、已下架和已上线的不展示
        const canOnline = row.state === 3 // 已通过
        const alreadyOffline = row.state === 6 // 已下架
        const alreadyOnline = row.state === 11 // 已上线
        const pass = canOnline || alreadyOffline || alreadyOnline
        return !pass
    },
    adminGroup(row) {
        if (isAdmin.value) {
            return true
        } else {
            return false
        }
    },
    adminSubmit(row) {
        // 只有审核通过或者下架的才能上线，否则不展示
        const canOnline = row.state === 3 || row.state === 6
        return canOnline
    },
    downCode(row) {
        // 下架按钮，只有已上线爬虫展示
        return row.state === 11
    },
    adminReject(row) {
      // 下架按钮，只有已上线爬虫展示
      return row.state === 11
    },
    adminRollback(row) {
        // 只有已上线，才展示退回
        return row.state === 11
    },
    reviewerRollback2(row) {
        return isReviewer.value
    }
}
const actionButtonDisabled = {
    reviewerSubmit(row) {
        // 只有待审核的才能点击
        let canClick = false
        if (isAdmin.value) {
            canClick = row.state === 1 || row.state === 3
        } else {
            canClick = row.state === 1
        }

        return !canClick
    },
    reviewerRollback(row) {
        return this.reviewerSubmit(row)
    },
    reviewerRollback2(row) {
      return this.reviewerSubmit(row)
    },
    adminSubmit(row) {
        // 只有审核通过才能上线，否则不展示
        const canOnline = row.state === 3 || row.state === 6
        return !canOnline
    },
    adminDownCode(row) {
        return row.state !== 11
    },
    adminReject(row) {
      return row.state !== 11
    }
}

const dialogEvents = {
    editSpiderConfigSaveEvent: async function (data) {
        // 整理数据结构
        // [{ query: {code: 'code'}, set: {} }, {query:{},set:{}}]
        const rowData = data._originData
        const payload = data.value
        const code = rowData.code
        const updateRule = [
            {
                query: { code: code },
                set: {
                    cssmark: payload,
                }
            }
        ]
        const params = {
            stype: 'save',
            update: updateRule
        }
        try {
            const r = await store.dispatch('rulesList/editCodeItem', params)
            const { msg, err } = r
            if (err === 1) {
                refreshRowData(code, payload)
                ElMessage({
                    message: msg || '保存成功',
                    type: 'success',
                    duration: 3000,
                })
                // getTableList()
            } else {
                ElMessage({
                    message: msg || '保存失败',
                    type: 'error',
                    duration: 3000,
                })
            }
        } catch (error) {
            ElMessage({
                message: '保存失败',
                type: 'error',
                duration: 3000,
            })
        }
    },
}

const getMarkWithRow = row => {
    const baseInfo = {
        code: row.code,
        site: row.site,
        channel: row.channel,
        href: row.href,
        modifyuser: row.modifyuser,
    }

    if (row.cssmark) {
        return {
            ...row.cssmark,
            ...baseInfo,
        }
    } else {
        return baseInfo
    }
}

const getLuaParams = row => {
    const baseInfo = {
        code: row.code,
        site: row.site,
        channel: row.channel,
        modifyuser: row.modifyuser,
        claimtime: row.claimtime,
        recovertime: row.recovertime,
        priority: row.priority,
        spiderimportant: row.spiderimportant,
        modifytime: row.modifytime,
    }
    return baseInfo
}

const editDialogMarkClick = (row) => {
    // 自定义关闭时间
    ElMessage({
        message: `${row.site} ${row.channel} ${row.href}`,
        showClose: true,
        duration: 3000,
    });
    BrowserOpenURL(row.href)
}

// table的按钮事件集合
const tableEvents = {
    handleDataTag(row) {
        onlyClickHighlight(row, '_action_clicked_mark')
        // 自定义关闭时间
        editDialogMarkClick(row)
    },
    handleEdit: (index, row) => {
        currentEditRow.value = row
        onlyClickHighlight(row, '_action_clicked_edit')
        prevClickedRow.value = row
        ElMessage({
            message: `${row.site} ${row.channel} ${row.href}`,
            showClose: true,
            duration: 3000,
        });
        const mark = getMarkWithRow(row)
        ServerActionCurrentOpenTab(mark)
        openEditDialog(row)
    },
    handleDebug(index, row) {
        onlyClickHighlight(row, '_action_clicked_debug')
        runSpiderDialog.value.dialogVisible = true
        runSpiderDialog.value.setPageData(row)
        // router.push({
        //     path: '/run'
        // });
    },
    handleVerify(index, row) {
        onlyClickHighlight(row, '_action_clicked_verify')
        loading.value = true
        if (!row.cssmark) {
            loading.value = false
            return ElMessage({
                message: '没有找到标注信息',
                type: 'error',
                duration: 3000,
            })
        }
        const mark = getMarkWithRow(row)
        VerifySpiderConfig(mark).then(r => {
            if (r.err === 1 && r.ret) {
                verifySpiderDialog.value.setPageData(true, {
                  ret: r.ret,
                  row
                })
            } else {
                return ElMessage({
                    message: r.msg || '验证异常',
                    type: 'error',
                    duration: 3000,
                })
            }
        }).finally(() => {
            loading.value = false
        })
    },
    // 操作按钮-----
    updateCodeStateAction(rowArr, info) {
        const luaArr = []
        if (Array.isArray(rowArr) && rowArr.length > 0) {
            rowArr.forEach(row => {
                const lua = getLuaParams(row)
                lua.state = info.state
                lua.reason = info.reason
                luaArr.push(lua)
            })
        } else {
            return console.error('至少选中1个操作内容')
        }
        if (!info.stype) {
            return console.error('没有找到关键参数stype')
        }
        const param = {
            stype: info.stype,
        }

        ServerActionUpdateCodeState({ lua: luaArr, param }).then(r => {
            if (r.err === 1) {
                ElMessage({
                    message: r.msg || info.successTip,
                    type: 'success',
                    duration: 3000,
                })
                getTableList()
            } else {
                return ElMessage({
                    message: r.msg || info.errorTip,
                    type: 'error',
                    duration: 3000,
                })
            }
        })
    },
    // 上线和批量上线操作 stateText=up
    // 下架和批量下架操作 stateText=down
    batchListing(list = [], stateText = 'up') {
        const stateMap = {
            up: {
                code: 11,
                text: '上线',
            },
            down: {
                code: 6,
                text: '下架',
            },
        }
        const stateInfo = stateMap[stateText]
        if (!stateInfo) {
            return console.error('未定义的stateText')
        }
        let info = {
            successTip: `${stateInfo.text}成功`,
            errorTip: `${stateInfo.text}失败`,
        }
        if (!Array.isArray(list)) return
        if (list.length <= 0) {
            return console.error('至少选中一个可操作对象')
        }
        if (list.length > 1) {
            info = {
                successTip: `批量${stateInfo.text}成功`,
                errorTip: `批量${stateInfo.text}失败`,
            }
        }
        const luaArr = list.map(r => {
            const lua = getLuaParams(r)
            lua.state = r.state
            return lua
        })
        const param = {
            stype: stateInfo.text
        }
        ServerActionUpdateCodeState({ lua: luaArr, param }).then(r => {
            if (r.err === 1) {
                ElMessage({
                    message: r.msg || info.successTip,
                    type: 'success',
                    duration: 3000,
                })
                getTableList()
            } else {
                return ElMessage({
                    message: r.msg || info.errorTip,
                    type: 'error',
                    duration: 3000,
                })
            }
        })
    },
    // 审核打回
    reviewerRollback(_, row) {
        onlyClickHighlight(row, '_action_clicked_rollback')
        ElMessageBox.prompt('请输入打回原因', '审核打回', {
            confirmButtonText: '确认打回',
            cancelButtonText: '取消',
            inputPattern: /^.+$/, // 非空
            inputErrorMessage: '不能为空',
        })
        .then(({ value }) => {
            this.updateCodeStateAction([row], {
                reason: value,
                stype: '打回',
                state: 2,
                successTip: '打回成功',
                errorTip: '打回失败',
            })
        })
    },
    // 审核通过
    reviewerSubmit(_, row) {
        onlyClickHighlight(row, '_action_clicked_submit')
        ElMessageBox.confirm('确认通过？', '提示',
            {
                customClass: 'j-confirm-message-box',
                type: 'warning',
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                showCancelButton: false,
            }
        ).then(() => {
            this.updateCodeStateAction([row], {
                state: 3,
                stype: '通过',
                successTip: '通过成功',
                errorTip: '通过失败',
            })
        })
    },
    // 管理上线
    adminSubmit(_, row) {
        onlyClickHighlight(row, '_action_clicked_submit')
        ElMessageBox.confirm('确认上线？', '提示',
            {
                customClass: 'j-confirm-message-box',
                type: 'warning',
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                showCancelButton: false,
            }
        ).then(() => {
            this.batchListing([row], 'up')
        })
    },
    // 管理控制下架
    adminDownCode(_, row) {
        onlyClickHighlight(row, '_action_clicked_down_code')
        ElMessageBox.confirm('确认下架？', '提示',
            {
                customClass: 'j-confirm-message-box',
                type: 'warning',
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                showCancelButton: false,
            }
        ).then(() => {
            this.batchListing([row], 'down')
        })
    },
    // 管理退回
    adminRollback(_, row) {
        onlyClickHighlight(row, '_action_clicked_rollback')
        currentEditRow.value = row
        // ElMessageBox.confirm('确认退回？', '提示',
        //     {
        //         customClass: 'j-confirm-message-box',
        //         type: 'warning',
        //         confirmButtonText: '确认',
        //         cancelButtonText: '取消',
        //         showCancelButton: false,
        //     }
        // ).then(() => {
        //     tableEvents.confirmAdminRollback(row)
        // })
        dialog.rollbackReason = true
    },
    confirmRollbackReason(row) {
      if (!filters.rollbackReason) {
        return ElMessage({
          message: '请选择退回原因',
          type: 'error',
          duration: 3000,
        })
      }
      dialog.rollbackReason = false
      tableEvents.confirmAdminRollback(row)
    },
    confirmAdminRollback: function (row) {
      this.updateCodeStateAction([row], {
        state: 12,
        stype: '退回',
        reason: filters.rollbackReason,
        successTip: '退回成功',
        errorTip: '退回失败',
      })
    },
    // 管理员打回
    adminReject(_, row) {
      onlyClickHighlight(row, '_action_clicked_reject_code')
      ElMessageBox.prompt('请输入打回原因', '打回', {
        confirmButtonText: '确认打回',
        cancelButtonText: '取消',
        inputPattern: /^.+$/, // 非空
        inputErrorMessage: '不能为空',
      })
      .then(({ value }) => {
        this.updateCodeStateAction([row], {
          reason: value,
          stype: '打回',
          state: 2,
          successTip: '打回成功',
          errorTip: '打回失败',
        })
      })
    }
}

const toggleRow = (rowList = []) => {
    const ignoreSelectable = false
    rowList.forEach(row => {
        spiderTable.value?.toggleRowSelection(
            row,
            undefined,
            ignoreSelectable
        )
    })
}

const tableRowSelectable = (row) => {
    // 待审核(管理员的批量打回)、已通过(管理员的批量上线)、已下架的批量上线或者已上线(管理员的批量下架)的才能选
    return row.state === 1 || row.state === 3 || row.state === 6 || row.state === 11
}

// 批量打回
const confirmBatchRollback = () => {
    // 过滤一下，找到已上线爬虫，仅提交此类爬虫
    let list = []
    let dropList = []
    if (isAdmin.value) {
        // 管理员可以打回待审核和已通过爬虫
        list = listState.selected.filter(v => v.state === 1 || v.state === 3 || v.state === 11)
        dropList = listState.selected.filter(v => !(v.state === 1 || v.state === 3 || v.state === 11))
    } else {
        // 审核员只能打回待审核爬虫
        list = listState.selected.filter(v => v.state === 1)
        dropList = listState.selected.filter(v => v.state !== 1)
    }
    toggleRow(dropList)
    if (list.length <= 0) {
        return ElMessage({
            message: '至少要选中1条有效数据: 当前未选中待审核或者已通过爬虫',
            type: 'error',
            duration: 3000,
        })
    }
    tableEvents.updateCodeStateAction(list, {
        stype: '打回',
        state: 2,
        successTip: '批量打回成功',
        errorTip: '批量打回失败',
    })
}
const doBatchRollback = () => {
    ElMessageBox.confirm('确认批量打回？', '提示',
        {
            customClass: 'j-confirm-message-box',
            type: 'warning',
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            showCancelButton: false,
        }
    ).then(() => {
        confirmBatchRollback()
    })
}

// 执行批量上线
const confirmBatchListing = () => {
    // 过滤一下，找到已通过爬虫，仅提交此类爬虫
    const list = listState.selected.filter(v => v.state === 3 || v.state === 6)
    const dropList = listState.selected.filter(v => !(v.state === 3 || v.state === 6))
    toggleRow(dropList)
    if (list.length <= 0) {
        return ElMessage({
            message: '至少要选中1条有效数据: 当前未选中已通过或已下架爬虫',
            type: 'error',
            duration: 3000,
        })
    }
    // 判断爬虫中是否有其他类型，如果有，将其他类型爬虫取消选中
    tableEvents.batchListing(list, 'up')
}
const doBatchListing = () => {
    ElMessageBox.confirm('确认批量上线？', '提示',
        {
            customClass: 'j-confirm-message-box',
            type: 'warning',
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            showCancelButton: false,
        }
    ).then(() => {
        confirmBatchListing()
    })
}

// 执行批量下架操作
const confirmBatchUnListing = () => {
    // 过滤一下，找到已上线爬虫，仅提交此类爬虫
    const list = listState.selected.filter(v => v.state === 11)
    const dropList = listState.selected.filter(v => v.state !== 11)
    toggleRow(dropList)
    if (list.length <= 0) {
        return ElMessage({
            message: '至少要选中1条有效数据: 当前未选中已上线爬虫',
            type: 'error',
            duration: 3000,
        })
    }
    tableEvents.batchListing(list, 'down')
}
const doUnBatchListing = () => {
    ElMessageBox.confirm('确认批量下架？', '提示',
        {
            customClass: 'j-confirm-message-box',
            type: 'warning',
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            showCancelButton: false,
        }
    ).then(() => {
        confirmBatchUnListing()
    })
}

//Wails事件绑定
EventsOn("spiderConfigChange", data => {
    const { key, css, url } = data
    refreshAndAsyncEditDialog(key, css)
    // 当触发修改时候，同步给客服端一份
    // if (currentEditRow.value && Object.keys(currentEditRow.value).length <= 0) {
    //     const mark = getMarkWithRow(currentEditRow.value)
    //     ServerActionCurrentOpenTab(mark)
    // }
})
</script>

<style lang="scss" scoped>
::v-deep {
    .el-button {
        &.active {
            background-color: var(--el-button-hover-bg-color);
            border-color: var(--el-button-hover-border-color);
            color: var(--el-button-hover-text-color);
            outline: none;
        }
    }
}

.pagination-container {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}
.action-bar-container {
    display: flex;
    justify-content: space-between;
}
.action-bar-item-container {
    
}
.action-bar-item {
    display: flex;
    align-items: center;
}
.action-bar-name {
    font-size: 14px;
    white-space: nowrap;
}
</style>