<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam" :data-callback="dataCallback">
      <template #tableHeader>
        <div class="table-header">
          <el-button type="primary" @click="handleAdd"> 新增 </el-button>
        </div>
      </template>
      <template #name="{ row }">
        <span>{{ row.name || "--" }}</span>
      </template>
      <template #performanceTypeLabel="{ row }">
        <span>{{ row.performanceTypeLabel || "--" }}</span>
      </template>
      <template #frequencyLabel="{ row }">
        <span>{{ row.frequencyLabel || "--" }}</span>
      </template>
      <template #shelfStatus="{ row }">
        <span>{{ row.onlineStatusLabel }}</span>
      </template>
      <template #auditStatusLabel="{ row }">
        <span>{{ row.auditStatusLabel }}</span>
      </template>
      <template #submitTime="{ row }">
        <span>{{ row.submitTime || "--" }}</span>
      </template>
      <template #operation="scope">
        <el-button link type="primary" @click="handleDetail(scope.row)"> 查看详情 </el-button>
        <!-- 已通过 + 已上线：编辑、下线、删除 -->
        <template v-if="scope.row.auditStatus === 1 && scope.row.shelfStatus === 1">
          <el-button link type="primary" @click="handleEdit(scope.row)"> 编辑 </el-button>
          <el-button link type="primary" @click="handleShelfToggle(scope.row, 0)"> 下线 </el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"> 删除 </el-button>
        </template>
        <!-- 已通过 + 已下线：编辑、上线、删除 -->
        <template v-else-if="scope.row.auditStatus === 1 && scope.row.shelfStatus === 0">
          <el-button link type="primary" @click="handleEdit(scope.row)"> 编辑 </el-button>
          <el-button link type="primary" @click="handleShelfToggle(scope.row, 1)"> 上线 </el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"> 删除 </el-button>
        </template>
        <!-- 已驳回：编辑、删除、查看拒绝原因 -->
        <template v-else-if="scope.row.auditStatus === 2">
          <el-button link type="primary" @click="handleEdit(scope.row)"> 编辑 </el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"> 删除 </el-button>
          <el-button v-if="scope.row.auditReason" link type="primary" @click="handleViewReason(scope.row)">
            查看拒绝原因
          </el-button>
        </template>
      </template>
    </ProTable>
    <!-- 删除确认 -->
    <el-dialog v-model="deleteDialogVisible" title="提示" width="500px">
      <div style="padding: 20px 0">确定要删除该演出吗？</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false"> 取消 </el-button>
          <el-button type="primary" @click="confirmDelete"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看拒绝原因 -->
    <el-dialog v-model="reasonDialogVisible" title="查看拒绝原因" width="600px">
      <div class="reject-reason-content">
        <div class="reject-reason-item">
          <div class="reject-reason-label">演出名称：</div>
          <div class="reject-reason-value">
            {{ currentReasonData.name || "--" }}
          </div>
        </div>
        <div class="reject-reason-item">
          <div class="reject-reason-label">拒绝原因：</div>
          <div class="reject-reason-value reject-reason-text">
            {{ currentReasonData.reason || "暂无拒绝原因" }}
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="reasonDialogVisible = false"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="performance">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import type { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { localGet } from "@/utils";
import {
  getPerformancePage,
  transformPerformanceListResponse,
  deletePerformance,
  setPerformanceOnlineStatus,
  type PerformanceRow
} from "@/api/modules/performance";

const router = useRouter();
const proTable = ref<ProTableInstance>();
const deleteDialogVisible = ref(false);
const deletingItem = ref<PerformanceRow | null>(null);
const reasonDialogVisible = ref(false);
const currentReasonData = ref<{ name: string; reason: string }>({ name: "", reason: "" });

const initParam = reactive({
  storeId: localGet("createdId") || ""
});

const columns: ColumnProps<PerformanceRow>[] = [
  { type: "index", label: "序号", width: 60 },
  {
    prop: "name",
    label: "名称",
    search: { el: "input", props: { placeholder: "请输入" } }
  },
  {
    prop: "performanceType",
    label: "类型",
    search: {
      el: "select",
      props: { placeholder: "请选择" }
    },
    enum: [
      { label: "特邀演出", value: 0 },
      { label: "常规演出", value: 1 }
    ],
    fieldNames: { label: "label", value: "value" }
  },
  { prop: "frequencyLabel", label: "频次" },
  {
    prop: "shelfStatus",
    label: "在线状态",
    search: { el: "select", props: { placeholder: "请选择" } },
    enum: [
      { label: "上线", value: 1 },
      { label: "下线", value: 0 }
    ],
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "auditStatus",
    label: "审核状态",
    search: {
      el: "select",
      props: { placeholder: "请选择" }
    },
    enum: [
      { label: "待审核", value: 0 },
      { label: "已通过", value: 1 },
      { label: "已驳回", value: 2 }
    ],
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "startCreatedTime",
    label: "提交开始时间",
    isShow: false,
    search: {
      el: "date-picker",
      props: {
        type: "datetime",
        valueFormat: "YYYY-MM-DD HH:mm:ss",
        placeholder: "请选择开始时间"
      }
    }
  },
  {
    prop: "endCreatedTime",
    label: "提交结束时间",
    isShow: false,
    search: {
      el: "date-picker",
      props: {
        type: "datetime",
        valueFormat: "YYYY-MM-DD HH:mm:ss",
        placeholder: "请选择结束时间"
      }
    }
  },
  {
    prop: "submitTime",
    label: "提交时间"
  },
  { prop: "operation", label: "操作", fixed: "right", width: 280 }
];

// 搜索区增加「在线状态」「提交时间」：在线状态用现有 enum 列即可；提交时间用自定义 search 或两字段
// 若后端支持提交时间范围，可在 initParam 或列上增加 search
const getTableList = (params: any) => {
  const query: any = {
    storeId: initParam.storeId,
    pageNum: params.pageNum ?? 1,
    pageSize: params.pageSize ?? 10,
    performanceName: params.name ?? undefined,
    reviewStatus: params.auditStatus,
    performanceType: params.performanceType,
    onlineStatus: params.shelfStatus,
    startCreatedTime: params.startCreatedTime ?? undefined,
    endCreatedTime: params.endCreatedTime ?? undefined
  };
  return getPerformancePage(query);
};

const dataCallback = (payload: any) => {
  return transformPerformanceListResponse(payload);
};

const handleAdd = () => {
  router.push({ path: "/performance/edit" });
};

const handleEdit = (row: PerformanceRow) => {
  router.push({ path: "/performance/edit", query: { id: String(row.id) } });
};

const handleDetail = (row: PerformanceRow) => {
  router.push({ path: "/performance/edit", query: { id: String(row.id), mode: "detail" } });
};

const handleDelete = (row: PerformanceRow) => {
  deletingItem.value = row;
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  if (!deletingItem.value) return;
  try {
    const res: any = await deletePerformance(deletingItem.value.id);
    if (res?.code === 200) {
      ElMessage.success("删除成功");
      deleteDialogVisible.value = false;
      deletingItem.value = null;
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || "删除失败");
    }
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败");
  }
};

const handleShelfToggle = async (row: PerformanceRow, onlineStatus: number) => {
  const actionText = onlineStatus === 1 ? "上线" : "下线";
  try {
    await ElMessageBox.confirm(`确定要${actionText}该演出吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
  } catch {
    return;
  }
  try {
    const res: any = await setPerformanceOnlineStatus(row.id, onlineStatus);
    if (res?.code === 200) {
      ElMessage.success(`${actionText}成功`);
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || "操作失败");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

const handleViewReason = (row: PerformanceRow) => {
  currentReasonData.value = {
    name: row.name || "",
    reason: row.auditReason || "暂无原因"
  };
  reasonDialogVisible.value = true;
};
</script>

<style scoped lang="scss">
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 12px 0;
}
.reject-reason-content {
  padding: 20px 0;
  .reject-reason-item {
    display: flex;
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
    .reject-reason-label {
      flex-shrink: 0;
      min-width: 100px;
      font-size: 14px;
      font-weight: 500;
      color: #606266;
    }
    .reject-reason-value {
      flex: 1;
      font-size: 14px;
      color: #303133;
      word-break: break-word;
      &.reject-reason-text {
        min-height: 80px;
        padding: 12px;
        line-height: 1.6;
        white-space: pre-wrap;
        background-color: #f5f7fa;
        border-radius: 4px;
      }
    }
  }
}
</style>
