<template>
    <el-main>
        <el-card shadow="never">
            <template #header>
                <span>剪辑师申请审核</span>
            </template>

            <el-table v-loading="loading" :data="list">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="real_name" label="真实姓名" min-width="100" show-overflow-tooltip />
                <el-table-column label="行业" min-width="140" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ idsToLabelText(row.trade, tradeLabelMap) }}
                    </template>
                </el-table-column>
                <el-table-column label="风格" min-width="140" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ idsToLabelText(row.style, styleLabelMap) }}
                    </template>
                </el-table-column>
                <el-table-column prop="card" label="身份证" min-width="160" show-overflow-tooltip />
                <el-table-column prop="phone" label="手机号" width="130" />
                <el-table-column prop="wechat" label="微信号" min-width="120" show-overflow-tooltip />
                <el-table-column label="作品链接" min-width="160">
                    <template #default="{ row }">
                        <el-link v-if="row.works" :href="row.works" target="_blank" type="primary">打开</el-link>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag size="small" :type="applyStatusType(row.status)">
                            {{ applyStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="审核备注" min-width="120" show-overflow-tooltip />
                <el-table-column label="申请时间" min-width="170">
                    <template #default="{ row }">
                        {{ formatDispTime(row.created_at) }}
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" min-width="170">
                    <template #default="{ row }">
                        {{ formatDispTime(row.updated_at) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <div class="table-row-actions">
                            <template v-if="isPending(row)">
                                <el-button type="success" size="small" @click="openRemark(row, 'agree')">同意</el-button>
                                <el-button type="danger" size="small" plain @click="openRemark(row, 'refuse')">拒绝</el-button>
                            </template>
                            <span v-else class="muted">已处理</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pager">
                <el-pagination
                    background
                    layout="total, prev, pager, next, sizes"
                    :total="total"
                    :current-page="query.page"
                    :page-size="query.limit"
                    :page-sizes="[5, 10, 20, 50]"
                    @current-change="handlePageChange"
                    @size-change="handleSizeChange"
                />
            </div>
        </el-card>

        <el-dialog v-model="remarkDialog" :title="remarkTitle" width="420px" destroy-on-close @closed="resetRemark">
            <el-input v-model="remark" type="textarea" :rows="4" placeholder="请输入备注（必填）" maxlength="200" show-word-limit />
            <template #footer>
                <el-button @click="remarkDialog = false">取消</el-button>
                <el-button type="primary" :loading="submitting" @click="submitRemark">确定</el-button>
            </template>
        </el-dialog>
    </el-main>
</template>

<script>
export default {
    name: "CutterApply",
    data() {
        return {
            loading: false,
            submitting: false,
            list: [],
            total: 0,
            query: { page: 1, limit: 10 },
            remarkDialog: false,
            remarkTitle: "",
            remark: "",
            remarkAction: "",
            currentRow: null,
            /** 行业标签 id -> 名称（type=1） */
            tradeLabelMap: {},
            /** 风格标签 id -> 名称（type=2） */
            styleLabelMap: {}
        };
    },
    created() {
        this.loadLabelMaps();
        this.getList();
    },
    methods: {
        buildLabelMap(raw) {
            const arr = Array.isArray(raw) ? raw : raw?.list || raw?.data || [];
            const map = {};
            for (const item of arr) {
                const id = item?.id;
                if (id == null) continue;
                map[Number(id)] = item.label_name ?? item.name ?? String(id);
            }
            return map;
        },
        async loadLabelMaps() {
            try {
                const [tradeRes, styleRes] = await Promise.all([
                    this.$API.cutter.labelList.get(1),
                    this.$API.cutter.labelList.get(2)
                ]);
                if (tradeRes.code === 1) {
                    this.tradeLabelMap = this.buildLabelMap(tradeRes.data);
                }
                if (styleRes.code === 1) {
                    this.styleLabelMap = this.buildLabelMap(styleRes.data);
                }
            } catch (e) {
                console.error(e);
            }
        },
        idsToLabelText(ids, map) {
            if (ids == null) return "-";
            const list = Array.isArray(ids) ? ids : [ids];
            if (!list.length) return "-";
            return list
                .map((id) => {
                    const n = Number(id);
                    const name = map[n];
                    return name != null && name !== "" ? name : String(id);
                })
                .join("、");
        },
        /** 后端为日期字符串 "2026-04-29 12:17:09" 或时间戳 */
        formatDispTime(val) {
            if (val === undefined || val === null || val === "") return "-";
            if (typeof val === "string" && /^\d{4}-\d{2}-\d{2}/.test(val.trim())) {
                return val.trim();
            }
            const num = Number(val);
            if (!Number.isFinite(num) || num <= 0) return String(val);
            const sec = num > 1e12 ? Math.floor(num / 1000) : num;
            return this.$TOOL.getTime(sec, "YYYY-MM-DD HH:mm:ss");
        },
        applyStatusText(status) {
            const n = Number(status);
            const map = { 0: "待审核", 1: "已通过", 2: "已拒绝" };
            return map[n] !== undefined ? map[n] : status === undefined || status === null ? "-" : String(status);
        },
        applyStatusType(status) {
            const n = Number(status);
            if (n === 1) return "success";
            if (n === 2) return "danger";
            return "warning";
        },
        isPending(row) {
            const s = row.status;
            return s === undefined || s === null || Number(s) === 0;
        },
        async getList() {
            this.loading = true;
            try {
                const res = await this.$API.cutter.applyList.get(this.query);
                if (res.code !== 1) {
                    this.$message.error(res.msg || "获取申请列表失败");
                    return;
                }
                const data = res.data || {};
                this.list = data.list || data.data || [];
                this.total = Number(data.count ?? data.total ?? this.list.length ?? 0);
            } finally {
                this.loading = false;
            }
        },
        handlePageChange(page) {
            this.query.page = page;
            this.getList();
        },
        handleSizeChange(limit) {
            this.query.limit = limit;
            this.query.page = 1;
            this.getList();
        },
        openRemark(row, action) {
            this.currentRow = row;
            this.remarkAction = action;
            this.remarkTitle = action === "agree" ? "同意申请" : "拒绝申请";
            this.remark = "";
            this.remarkDialog = true;
        },
        resetRemark() {
            this.currentRow = null;
            this.remarkAction = "";
            this.remark = "";
        },
        async submitRemark() {
            const text = (this.remark || "").trim();
            if (!text) {
                this.$message.warning("请填写备注");
                return;
            }
            if (!this.currentRow) return;
            this.submitting = true;
            try {
                const id = this.currentRow.id;
                const body = { remark: text };
                const res =
                    this.remarkAction === "agree"
                        ? await this.$API.cutter.applyAgreed.post(id, body)
                        : await this.$API.cutter.applyRefuse.post(id, body);
                if (res.code !== 1) {
                    this.$message.error(res.msg || "操作失败");
                    return;
                }
                this.$message.success(res.msg || "操作成功");
                this.remarkDialog = false;
                this.getList();
            } finally {
                this.submitting = false;
            }
        }
    }
};
</script>

<style scoped>
.pager {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}
.muted {
    color: var(--el-text-color-secondary);
    font-size: 12px;
}
</style>
