<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam" :data-callback="dataCallback">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="Download" @click="exportInfoExcel(scope)"> 导出 </el-button>
      </template>
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <!-- 审批通过和拒绝按钮仅在状态为0时显示 -->
        <template v-if="scope.row.status === '0'">
          <el-button type="primary" link @click="changeTypes(scope.row, 'pass')"> 审核通过 </el-button>
          <el-button type="primary" link @click="changeTypes(scope.row, '')"> 审核拒绝 </el-button>
        </template>
        <el-button type="primary" link @click="toDetail(scope.row)"> 查看详情 </el-button>
      </template>
    </ProTable>

    <el-dialog v-model="dialogFormVisible" title="审核拒绝" width="500">
      <el-form :model="form">
        <el-form-item label="" label-width="0">
          <el-input v-model="form.comment" autocomplete="off" type="textarea" maxlength="200" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog"> 取消 </el-button>
          <el-button type="primary" @click="handleSubmit"> 驳回 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="voucherManagement">
import { ref, reactive, onMounted, onActivated } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { Download } from "@element-plus/icons-vue";
import { audit, exportExcelStaffConfig, getStaffConfigList } from "@/api/modules/staffConfig";

const router = useRouter();
const dialogFormVisible = ref(false);
const form = reactive({
  comment: ""
});

const rowData = ref<any>();

const statusEnum = [
  { value: "0", label: "待审核" },
  { value: "1", label: "审核通过" },
  { value: "2", label: "审核拒绝" }
];
// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// 定义 filterValues
const filterValues = reactive({});

const getStatusObj = (statusValue: string) => {
  const statusObj = statusEnum.find(item => item.value === statusValue);
  if (statusObj) {
    filterValues.status = statusObj;
  } else {
    filterValues.status = "";
  }
  return statusObj;
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 页面加载时触发查询
onMounted(() => {
  proTable.value?.getTableList();
});

// 从其他页面返回时触发查询
onActivated(() => {
  proTable.value?.getTableList();
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.records,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  return getStaffConfigList(newParams);
};

// 跳转详情页
const toDetail = row => {
  router.push(`/store/voucherManagementDetail?id=${row.id}`);
};

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: "index", fixed: "left", label: "序号", width: 130 },
  { prop: "storeName", label: "所属店铺" },
  { prop: "name", label: "名称" },
  { prop: "description", label: "描述" },
  {
    prop: "status",
    label: "状态",
    render: scope => {
      const statusObj = getStatusObj(scope.row.status);
      return statusObj ? statusObj.label : "未知状态";
    },
    search: {
      el: "select"
    },
    enum: statusEnum,
    fieldNames: { label: "label", value: "value" }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

const changeTypes = (row: any, status: string) => {
  rowData.value = row;
  if (status === "pass") {
    handleChangeStatus(row, "1");
  } else {
    form.comment = "";
    dialogFormVisible.value = true;
  }
};

const handleChangeStatus = async (row: any, status: string) => {
  try {
    let res = await audit({ id: row.id, status: status, rejectionReason: form.comment });
    if (res.code === 200) {
      proTable.value?.getTableList();
      if (status === "2") closeDialog();
      ElMessage.success("审核成功");
    }
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

// 导出信息
const exportInfoExcel = async scope => {
  let res;
  // 获取原始状态值（可能为数字、字符串或 undefined）
  const rawStatus = proTable.value.searchParam.status;
  // 转换为字符串（处理 undefined/null 为 "" 或保留原始字符串）
  const statusParam = rawStatus !== undefined && rawStatus !== null ? String(rawStatus) : undefined;
  // 将筛选条件作为参数传递给后台
  res = await exportExcelStaffConfig({ status: statusParam });
  if (res.code === 200) {
    if (!res.data) {
      ElMessage.error("暂无可下载数据");
      return;
    }
    const exportFile = document.createElement("a");
    exportFile.style.display = "none";
    exportFile.download = `代金券管理.xlsx`;
    exportFile.href = `${res.data}?timestamp=${new Date().getTime()}`; // 添加时间戳防止缓存
    document.body.appendChild(exportFile);
    exportFile.click();
    document.body.removeChild(exportFile);
    ElMessage.success("下载成功");
  }
};

// 弹窗提交
const handleSubmit = () => {
  if (!form.comment) {
    ElMessage.error("请输入审批意见");
    return;
  }
  handleChangeStatus(rowData.value, "2");
};
// 关闭弹窗;
const closeDialog = () => {
  dialogFormVisible.value = false;
  form.comment = "";
};
</script>

<style lang="scss" scoped>
// 在组件样式中添加
.date-range {
  display: block; // 确保换行生效
  padding: 0 8px; // 可选：增加内边距
  word-wrap: break-word; // 长单词内换行
  white-space: normal; // 允许自然换行
}
</style>
