<script setup lang="ts">
import {ref, onMounted,reactive} from "vue";
import {useRoute, useRouter} 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: '推广码图片',
    dataIndex: 'promoCodeImage',
    key: 'promoCodeImage',
    width: 150,
    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;
  promoCodeImage: 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 previewVisible = ref(false);
const previewImage = ref("");

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"
          }
        }
    );
    console.log(response);

    if (response.code === 1) {
      // 修改这里：判断data是否为null或undefined
      if (response.data) {
        tableData.value = [response.data]; // 单个结果转为数组
      } else {
        tableData.value = []; // 设置为空数组
        message.info("未找到对应的推广码数据");
      }
    } else {
      message.error(response.message || "未找到推广码");
      tableData.value = [];
    }
  } catch (err) {
    console.error("查询错误:", err);
    message.error("查询失败，请检查网络");
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 主查询方法
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) {
      // 修改这里：确保data是数组，即使为null也转为空数组
      tableData.value = Array.isArray(response.data) ? response.data : [];
    } else {
      message.error(response.message || "获取数据失败");
      tableData.value = [];
    }
  } catch (err) {
    console.error("查询错误:", 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);
  }
});




// 处理搜索
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 handlePreview = (imageUrl: string) => {
  previewImage.value = imageUrl;
  previewVisible.value = true;
};

// 新增推广码表单相关状态
const addDrawerVisible = ref(false);
const addFormState = reactive({
  promoCodeInfoKey: '',
  promoCodeLink: '',
  promoCodeImage: '',
  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,
          promoCodeImage: addFormState.promoCodeImage,
          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: '',
        promoCodeImage: '',
        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: '',
  promoCodeImage: '',
  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.promoCodeImage = response.data.promoCodeImage;
      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,
          promoCodeImage: editFormState.promoCodeImage,
          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('编辑请求失败');
  }
};


//返回上一级
const router = useRouter();

// 返回上一级方法
const goBack = () => {
  router.go(-1); // 返回上一页
};



</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"
              class="custom-search"
          />
        </a-form-item>
        <a-button class="custom-button" @click="reset">重置搜索</a-button>
        <a-button class="custom-button" @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: 1000, y: 550 }"
      :loading="loading"
      bordered
      rowKey="id"
      locale="{ emptyText: '暂无数据' }"
  >
    <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 === 'promoCodeImage'">
        <a-image
            v-if="record.promoCodeImage"
            :width="80"
            :src="record.promoCodeImage"
            :preview="false"
            @click="handlePreview(record.promoCodeImage)"
        />
        <span v-else>无图片</span>
      </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>
    <template #footer>
      <div class="table-footer">
        <a-button @click="goBack" class="back-button">返回</a-button>
      </div>
    </template>
  </a-table>

  <!-- 图片预览模态框 -->
  <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
    <img alt="预览图片" style="width: 100%" :src="previewImage" />
  </a-modal>

  <!-- 新增推广码抽屉 -->
  <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="推广码图片URL">
        <a-input v-model:value="addFormState.promoCodeImage" placeholder="请输入图片URL" />
      </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 class="custom-button" 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="推广码图片URL">
        <a-input v-model:value="editFormState.promoCodeImage" />
      </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;
}

.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;
}

/* 新增表格页脚样式 */
.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.back-button {
  margin-right: 16px;
}

/* 调整分页器位置 */
:deep(.ant-table-pagination.ant-pagination) {
  margin: 0;
}



/*橙色按钮*/

.custom-button {
  background-color: #ffa940;
  border-color: #ffa940;
  color: #fff;
}

.custom-button:hover,
.custom-button:focus {
  background-color: #ffa940;
  border-color: #ffa940;
  color: #fff;
}

.custom-button[disabled] {
  background-color: #ffa940;
  border-color: #ffa940;
  opacity: 0.6;
  color: #fff;
}

/* 危险按钮样式 */
.custom-button.ant-btn-dangerous {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.custom-button.ant-btn-dangerous:hover,
.custom-button.ant-btn-dangerous:focus {
  background-color: #ff7875;
  border-color: #ff7875;
}

/* 保持原有的其他样式不变 */
.search-box {
  margin-bottom: 10px;
}

.custom-search :deep(.ant-input-search-button) {
  background-color: #ffa940;
  border-color: #ffa940;
}

.custom-search :deep(.ant-input-search-button:hover),
.custom-search :deep(.ant-input-search-button:focus) {
  background-color: #fa8c16;
  border-color: #fa8c16;
}

/* 保持输入框原有样式不变 */
.custom-search :deep(.ant-input) {
  border-right-color: #ffa940;
}
</style>