<script setup lang="ts">
import {ref, onMounted,reactive} from "vue";
import { useRoute } from "vue-router";
import myAxios from "../../api/myAxios";
import {message} from "ant-design-vue";

// 表格列定义
const columns = [
  {
    title: '推广码ID',
    dataIndex: 'id',
    width: 80,
    key: 'id',
    align: 'center'
  },
  {
    title: '信息Key',
    dataIndex: 'promoCodeInfoKey',
    key: 'promoCodeInfoKey',
    width: 120,
    align: 'center'
  },
  {
    title: '推广链接',
    dataIndex: 'promoCodeLink',
    key: 'promoCodeLink',
    width: 200,
    align: 'center'
  },
  {
    title: '项目ID',
    dataIndex: 'projectId',
    key: 'projectId',
    width: 100,
    align: 'center'
  },
  {
    title: '状态',
    dataIndex: 'promoCodeStatus',
    key: 'promoCodeStatus',
    width: 100,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 100,
    align: 'center'
  }
];

// 接口数据类型
interface PromoCode {
  id: number;
  promoCodeInfoKey: string;
  promoCodeLink: string;
  projectId: number;
  promoCodeStatus: boolean;
}

const route = useRoute();
const projectId = ref<string | number>("");
const tableData = ref<PromoCode[]>([]);
const loading = ref(false);
const searchId = ref("");

// 主查询方法
const getPromoCodes = async (id: string | number) => {
  const storedToken = localStorage.getItem('token');
  try {
    loading.value = true;
    const response:any = await myAxios.post(
        "/promoCode/queryByPid",
        { id },
        {
          headers: {
            Authorization: storedToken,
            "Content-Type": "application/json"
          }
        }
    );
    console.log(response)
    if (response.code === 1) {
      tableData.value = response.data;
    } else {
      message.error(response.message || "获取数据失败");
      tableData.value = [];
    }
  } catch (err) {
    message.error("数据加载失败，请重试");
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 初始化逻辑
if (typeof route.query.id === "string") {
  projectId.value = route.query.id;
}

onMounted(() => {
  if (projectId.value) {
    getPromoCodes(projectId.value);
  }
});

// 新增：按推广码ID查询
const queryPromoCodeById = async (id: number) => {
  const storedToken = localStorage.getItem('token');
  try {
    loading.value = true;
    const response:any = await myAxios.post(
        "/promoCode/queryById",
        { id },
        {
          headers: {
            Authorization: storedToken,
            "Content-Type": "application/json"
          }
        }
    );

    if (response.code === 1) {
      tableData.value = [response.data]; // 单个结果转为数组
    } else {
      message.error(response.message || "未找到推广码");
      tableData.value = [];
    }
  } catch (err) {
    message.error("查询失败，请检查网络");
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleIdSearch = (value: string) => {
  if (!value.trim()) {
    message.warning("请输入有效的推广码ID");
    return;
  }

  const id = Number(value);
  if (isNaN(id)) {
    message.warning("ID必须为数字");
    return;
  }

  queryPromoCodeById(id);
};

// 重置搜索
const reset = () => {
  searchId.value = "";
  if (projectId.value) {
    getPromoCodes(projectId.value); // 重新加载项目数据
  }
};


// 新增推广码表单相关状态
const addDrawerVisible = ref(false);
const addFormState = reactive({
  promoCodeInfoKey: '',
  promoCodeLink: '',
  projectId: 0,
  promoCodeStatus: false
});

// 打开新增表单
const openAddDrawer = () => {
  addFormState.projectId = Number(projectId.value); // 自动关联当前项目
  addDrawerVisible.value = true;
};

// 提交新增请求
const handleAddSubmit = async () => {
  try {
    const storedToken = localStorage.getItem('token');
    const res:any = await myAxios.post(
        "/promoCode/add",
        {
          promoCodeInfoKey: addFormState.promoCodeInfoKey,
          promoCodeLink: addFormState.promoCodeLink,
          projectId: addFormState.projectId,
          promoCodeStatus: addFormState.promoCodeStatus
        },
        {
          headers: {
            Authorization: storedToken,
            "Content-Type": "application/json"
          }
        }
    );

    if (res.code === 1) {
      message.success('新增成功');
      addDrawerVisible.value = false;
      await getPromoCodes(projectId.value); // 刷新列表
      // 重置表单（保留项目ID）
      Object.assign(addFormState, {
        promoCodeInfoKey: '',
        promoCodeLink: '',
        promoCodeStatus: false,
        projectId: Number(projectId.value)
      });
    } else {
      message.error(res.message || '新增失败');
    }
  } catch (error) {
    message.error('新增请求失败');
  }
};

// 绑定新增按钮点击事件
const goAddCode = () => {
  openAddDrawer();
};

//删除操作
const deletePromoCode = async (id: number) => {
  try {
    const storedToken = localStorage.getItem('token');
    const res:any = await myAxios.post(
        "/promoCode/delete", // 根据接口文档的路径
        { id }, // 请求参数
        {
          headers: {
            Authorization: storedToken,
            "Content-Type": "application/json"
          }
        }
    );

    if (res.code === 1) {
      message.success('删除成功');
      // 根据当前查看模式刷新
      if (searchId.value) {
        await queryPromoCodeById(Number(searchId.value));
      } else {
        await getPromoCodes(projectId.value);
      }
    } else {
      message.error(res.message || '删除失败');
    }
  } catch (error) {
    message.error('删除操作失败');
  }
};

//编辑
// 编辑相关状态
const editDrawerVisible = ref(false);
const editFormState = reactive({
  id: 0,
  promoCodeInfoKey: '',
  promoCodeLink: '',
  projectId: 0,
  promoCodeStatus: false
});
const getPromoCodeDetail = async (id: number) => {
  const storedToken = localStorage.getItem('token');
  try {
    const response:any = await myAxios.post(
        "/promoCode/queryById",
        { id },
        {
          headers: {
            Authorization: storedToken,
            "Content-Type": "application/json"
          }
        }
    );
    if (response.code === 1) {
      editFormState.id = response.data.id;
      editFormState.promoCodeInfoKey = response.data.promoCodeInfoKey;
      editFormState.promoCodeLink = response.data.promoCodeLink;
      editFormState.projectId = response.data.projectId;
      editFormState.promoCodeStatus = response.data.promoCodeStatus;
    } else {
      message.error(response.message || "获取编辑数据失败");
    }
  } catch (err) {
    message.error("获取编辑数据失败，请重试");
  }
};

const handleEdit = async (id: number) => {
  await getPromoCodeDetail(id);
  editDrawerVisible.value = true;
};

const handleEditSubmit = async () => {
  try {
    const storedToken = localStorage.getItem('token');
    const res:any = await myAxios.post(
        "/promoCode/update",
        {
          id: editFormState.id,
          promoCodeInfoKey: editFormState.promoCodeInfoKey,
          promoCodeLink: editFormState.promoCodeLink,
          projectId: editFormState.projectId,
          promoCodeStatus: editFormState.promoCodeStatus
        },
        {
          headers: {
            Authorization: storedToken,
            "Content-Type": "application/json"
          }
        }
    );
    if (res.code === 1) {
      message.success('编辑成功');
      editDrawerVisible.value = false;
      await getPromoCodes(projectId.value);
    } else {
      message.error(res.message || '编辑失败');
    }
  } catch (error) {
    message.error('编辑请求失败');
  }
};
</script>

<template>
  <!-- 修改后的搜索框 -->
  <div class="search-box">
    <a-form layout="inline">
      <a-space>
        <a-form-item label="推广码ID">
          <a-input-search
              style="width: 300px"
              placeholder="输入推广码ID进行查询"
              enter-button
              @search="handleIdSearch"
              v-model:value="searchId"
          />
        </a-form-item>
        <a-button type="primary" @click="reset">重置搜索</a-button>
        <a-button type="primary" @click="goAddCode">新增推广码</a-button>
        <a-form-item label="当前项目ID">
          <a-tag color="blue">{{ projectId }}</a-tag>
        </a-form-item>
      </a-space>
    </a-form>
  </div>


  <!-- 数据表格 -->
  <a-table
      :columns="columns"
      :data-source="tableData"
      :scroll="{ x: 800, y: 450 }"
      :loading="loading"
      bordered
      rowKey="id"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'promoCodeStatus'">
        <a-tag :color="record.promoCodeStatus ? 'red' : 'green'">
          {{ record.promoCodeStatus ? '占用' : '空闲' }}
        </a-tag>
      </template>

      <template v-if="column.key === 'action'">
        <a-space :size="8">
          <a-button
              size="small"
              danger
              @click="deletePromoCode(record.id)"
              :loading="loading"
          >
            删除
          </a-button>
          <!-- 编辑按钮（需实现对应方法） -->
          <a-button size="small" @click="handleEdit(record.id)">
            编辑
          </a-button>
        </a-space>
      </template>
    </template>
  </a-table>

  <!-- 新增推广码抽屉 -->
  <a-drawer
      title="新增推广码"
      placement="right"
      :visible="addDrawerVisible"
      @close="addDrawerVisible = false"
      width="600"
  >
    <a-form
        :model="addFormState"
        layout="vertical"
        @finish="handleAddSubmit"
    >
      <a-form-item label="信息Key">
        <a-input v-model:value="addFormState.promoCodeInfoKey" />
      </a-form-item>

      <a-form-item label="推广链接">
        <a-input v-model:value="addFormState.promoCodeLink" />
      </a-form-item>

      <a-form-item label="状态">
        <a-select v-model:value="addFormState.promoCodeStatus">
          <a-select-option :value="false">空闲</a-select-option>
          <a-select-option :value="true">占用</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="项目ID">
        <a-input-number
            v-model:value="addFormState.projectId"
            :disabled="true"
        />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit">提交</a-button>
        <a-button style="margin-left: 10px" @click="addDrawerVisible = false">
          取消
        </a-button>
      </a-form-item>
    </a-form>
  </a-drawer>

  <!-- 编辑推广码抽屉 -->
  <a-drawer
      title="编辑推广码"
      placement="right"
      :visible="editDrawerVisible"
      @close="editDrawerVisible = false"
      width="600"
  >
    <a-form
        :model="editFormState"
        layout="vertical"
        @finish="handleEditSubmit"
    >
      <a-form-item label="ID">
        <a-input v-model:value="editFormState.id" :disabled="true" />
      </a-form-item>
      <a-form-item label="信息Key">
        <a-input v-model:value="editFormState.promoCodeInfoKey" />
      </a-form-item>
      <a-form-item label="推广链接">
        <a-input v-model:value="editFormState.promoCodeLink" />
      </a-form-item>
      <a-form-item label="状态">
        <a-select v-model:value="editFormState.promoCodeStatus">
          <a-select-option :value="false">空闲</a-select-option>
          <a-select-option :value="true">占用</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="项目ID">
        <a-input-number
            v-model:value="editFormState.projectId"
            :disabled="true"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">提交</a-button>
        <a-button style="margin-left: 10px" @click="editDrawerVisible = false">
          取消
        </a-button>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<style scoped>
.search-box {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

:deep(.ant-table-thead) {
  background-color: #fafafa !important;
  font-weight: 600;
}

:deep(.ant-table-row:hover) {
  background-color: #fafafa !important;
}
</style>