<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="90" />
                <el-table-column label="任务ID" width="90">
                    <template #default="{ row }">
                        {{ row.task_id ?? row.tid ?? "-" }}
                    </template>
                </el-table-column>
                <el-table-column label="用户" min-width="140" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.user?.nickname || row.uid || row.user_id || "-" }}
                    </template>
                </el-table-column>
                <el-table-column label="任务标题" min-width="160" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.task?.title || "-" }}
                    </template>
                </el-table-column>
                <el-table-column label="任务金额" width="100">
                    <template #default="{ row }">
                        {{ row.task?.price ?? "-" }}
                    </template>
                </el-table-column>
                <el-table-column label="审核地址" min-width="180" show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-link v-if="shareHref(row.audit_url)" :href="shareHref(row.audit_url)" type="primary" target="_blank">
                            打开
                        </el-link>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="成品地址" min-width="180" show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-link v-if="shareHref(row.finish_url)" :href="shareHref(row.finish_url)" type="primary" target="_blank">
                            打开
                        </el-link>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="120">
                    <template #default="{ row }">
                        <el-tag :type="statusType(row.status)" size="small">
                            {{ statusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="备注" min-width="140" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.remark || row.reject_remark || "-" }}
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" min-width="170" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ formatTime(row.created_at || row.add_time || row.create_time) }}
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" min-width="170" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ formatTime(row.updated_at || row.update_time) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="288" fixed="right">
                    <template #default="{ row }">
                        <div class="table-row-actions">
                            <el-button type="info" size="small" @click="showDetail(row)">详情</el-button>
                            <el-button v-if="canAudit(row)" type="success" size="small" @click="affirmOrder(row)">通过</el-button>
                            <el-button v-if="canAudit(row)" type="danger" size="small" @click="openRemark(row, 'reject')">拒绝</el-button>
                            <el-button v-if="canSettle(row)" type="warning" size="small" @click="openRemark(row, 'settle')">结算</el-button>
                        </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="detailDialog" title="订单详情" width="680px" destroy-on-close>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="订单ID">{{ detail.id ?? "-" }}</el-descriptions-item>
                <el-descriptions-item label="任务ID">{{ detail.task_id ?? detail.tid ?? "-" }}</el-descriptions-item>
                <el-descriptions-item label="用户">{{ detail.user?.nickname || detail.uid || detail.user_id || "-" }}</el-descriptions-item>
                <el-descriptions-item label="任务标题">{{ detail.task?.title || "-" }}</el-descriptions-item>
                <el-descriptions-item label="状态">{{ statusText(detail.status) }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatTime(detail.created_at || detail.add_time || detail.create_time) }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ formatTime(detail.updated_at || detail.update_time) }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ detail.remark || detail.reject_remark || "-" }}</el-descriptions-item>
                <el-descriptions-item label="审核地址" :span="2">
                    <el-link v-if="shareHref(detail.audit_url)" :href="shareHref(detail.audit_url)" type="primary" target="_blank">
                        {{ shareHref(detail.audit_url) }}
                    </el-link>
                    <span v-else>{{ detail.audit_url || "-" }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="成品地址" :span="2">
                    <el-link v-if="shareHref(detail.finish_url)" :href="shareHref(detail.finish_url)" type="primary" target="_blank">
                        {{ shareHref(detail.finish_url) }}
                    </el-link>
                    <span v-else>{{ detail.finish_url || "-" }}</span>
                </el-descriptions-item>
            </el-descriptions>
        </el-dialog>

        <el-dialog v-model="remarkDialog" :title="remarkTitle" width="420px" destroy-on-close @closed="resetRemark">
            <el-input v-model="remark" type="textarea" :rows="4" :placeholder="remarkPlaceholder" 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>
import { resolveExternalShareUrl } from "@/utils/extractBaiduPan";

const STATUS_MAP = {
    "-1": "未通过",
    0: "待制作",
    1: "待验收",
    2: "待交付",
    3: "待结算",
    4: "已结算"
};

export default {
    name: "CutterOrderList",
    data() {
        return {
            loading: false,
            submitting: false,
            list: [],
            total: 0,
            query: { page: 1, limit: 10 },
            detailDialog: false,
            detail: {},
            remarkDialog: false,
            remarkTitle: "",
            remarkPlaceholder: "",
            remark: "",
            remarkAction: "",
            currentRow: null
        };
    },
    created() {
        this.getList();
    },
    methods: {
        shareHref(raw) {
            return resolveExternalShareUrl(raw);
        },
        statusText(status) {
            if (status == null || status === "") return "-";
            const key = String(status);
            return STATUS_MAP[key] ?? STATUS_MAP[status] ?? key;
        },
        statusType(status) {
            const n = Number(status);
            if (n === -1) return "danger";
            if (n === 1 || n === 4) return "success";
            return "warning";
        },
        canAudit(row) {
            return Number(row.status) === 1;
        },
        canSettle(row) {
            return Number(row.status) === 3;
        },
        formatTime(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");
        },
        async getList() {
            this.loading = true;
            try {
                const res = await this.$API.cutter.orderList.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();
        },
        async showDetail(row) {
            const id = row.id;
            if (id == null) return;
            const res = await this.$API.cutter.orderInfo.get(id);
            if (res.code !== 1) {
                this.$message.error(res.msg || "获取详情失败");
                return;
            }
            this.detail = res.data || {};
            this.detailDialog = true;
        },
        async affirmOrder(row) {
            const id = row?.id;
            if (id == null) {
                this.$message.error("缺少订单ID");
                return;
            }
            try {
                await this.$confirm("确认通过该订单吗？", "提示", {
                    type: "warning",
                    confirmButtonText: "确认",
                    cancelButtonText: "取消"
                });
            } catch (e) {
                return;
            }
            const res = await this.$API.cutter.orderAffirm.post(id);
            if (res.code !== 1) {
                this.$message.error(res.msg || "操作失败");
                return;
            }
            this.$message.success(res.msg || "操作成功");
            this.getList();
        },
        openRemark(row, action) {
            this.currentRow = row;
            this.remarkAction = action;
            this.remark = "";
            if (action === "settle") {
                this.remarkTitle = "订单结算";
                this.remarkPlaceholder = "请输入结算备注（必填）";
            } else {
                this.remarkTitle = "订单拒绝";
                this.remarkPlaceholder = "请输入拒绝理由（必填）";
            }
            this.remarkDialog = true;
        },
        resetRemark() {
            this.currentRow = null;
            this.remarkAction = "";
            this.remark = "";
            this.remarkTitle = "";
            this.remarkPlaceholder = "";
        },
        async submitRemark() {
            if (!this.currentRow) return;
            const id = this.currentRow.id;
            if (id == null) {
                this.$message.error("缺少订单ID");
                return;
            }
            const remark = (this.remark || "").trim();
            if (!remark) {
                this.$message.warning(this.remarkAction === "settle" ? "请填写结算备注" : "请填写拒绝理由");
                return;
            }
            this.submitting = true;
            try {
                let res;
                if (this.remarkAction === "settle") {
                    res = await this.$API.cutter.orderSettle.post(id, { remark });
                } else {
                    res = await this.$API.cutter.orderReject.post(id, { remark });
                }
                if (res.code !== 1) {
                    this.$message.error(res.msg || "操作失败");
                    return;
                }
                this.$message.success(res.msg || (this.remarkAction === "settle" ? "结算成功" : "操作成功"));
                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>
