<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";
import router from "../../router";

// 修改表格列定义
const columns = [
  {
    title: '项目通知ID',
    dataIndex: 'id',
    width: 20,
    key: 'id',
    fixed: 'left',
    align: 'center'
  },
  {
    title: '通知标题',
    dataIndex: 'notificationTitle',
    key: 'notificationTitle',
    width: 30,
    fixed: 'left',
    align: 'center'
  },
  {
    title: '通知内容',
    dataIndex: 'notificationContent',
    key: 'notificationContent',
    width: 150,
    align: 'center'
  },
  {
    title: '项目ID',
    dataIndex: 'projectId',
    key: 'projectId',
    width: 70,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 100,
    align: 'center'
  }
];

// 修改接口数据类型
interface ProjectNotification {
  id: number;
  notificationTitle: string;
  notificationContent: string;
  projectId: number;
}

const route = useRoute();
const projectId = ref<string | number>("");
const tableData = ref<ProjectNotification[]>([]);
const loading = ref(false);
const error = ref("");
const searchId = ref("");
// 新增搜索处理方法
const handleIdSearch = async (value: string) => {
  if (!value.trim()) {
    message.warning("请输入有效的项目明细ID");
    return;
  }

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

  await queryDetailById(id);
};
// 新增根据明细ID查询的方法
const queryDetailById = async (id: string | number) => {
  const storedToken = localStorage.getItem('token');
  try {
    loading.value = true;
    const response:any = await myAxios.post(
        "/projectNotification/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 reset = () => {
  searchId.value = "";
  // 重置时重新加载原始项目数据
  if (projectId.value) {
    getNotifications (projectId.value);
  }
};
// 初始化逻辑
if (typeof route.query.id === "string") {
  projectId.value = route.query.id;
}

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

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



// 修改初始化逻辑
onMounted(() => {
  if (projectId.value) {
    getNotifications(projectId.value);
  }
});


// 修改编辑相关代码
const drawerVisible = ref(false);
const formState = reactive({
  id: 0,
  notificationTitle: '',
  notificationContent: '',
  projectId: 0
});

const updateNotification = async (id: number) => {
  try {
    const storedToken = localStorage.getItem('token');
    const res:any = await myAxios.post(
        "/projectNotification/queryById", // 假设存在单个查询接口
        { id },
        {
          headers: {
            Authorization: storedToken,
            "Content-Type": "application/json"
          }
        }
    );

    if (res.code === 1) {
      Object.assign(formState, res.data);
      drawerVisible.value = true;
    }
  } catch (error) {
    message.error('获取通知详情失败');
  }
};

// 修改提交方法
const handleSubmit = async () => {
  try {
    const storedToken = localStorage.getItem('token');
    const res:any = await myAxios.post(
        "/projectNotification/update",
        { ...formState },
        {
          headers: {
            Authorization: storedToken,
            "Content-Type": "application/json"
          }
        }
    );

    if (res.code === 1) {
      message.success('更新成功');
      drawerVisible.value = false;
      await getNotifications(projectId.value);
    }
  } catch (error) {
    message.error('更新失败');
  }
};
onMounted(getNotifications)

//删除操作
const deleteNotification = async (id: number) => {
  try {
    const storedToken = localStorage.getItem('token');
    const res: any = await myAxios.post(
        "/projectNotification/delete",
        { id },
        {
          headers: {
            Authorization: storedToken,
            'AfterScript': 'required-script'
          }
        }
    );

    if (res.code === 1) {
      message.success('删除成功');
      if (projectId.value) {
        await getNotifications (projectId.value);
      }
    } else {
      message.error(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    message.error('删除操作失败');
  }
};

const goAddProjectNotice=()=>{
  router.push('/addprojectNotice')
}
</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="goAddProjectNotice">新增项目通知</a-button>
        <a-button class="custom-button" @click="reset">重置搜索</a-button>
      </a-space>
    </a-form>
  </div>
  <!-- 修改表格模板 -->
  <a-table
      :columns="columns"
      :data-source="tableData"
      :scroll="{ x: 1200, y: 450 }"
      :loading="loading"
      bordered
      rowKey="id"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <a-space :size="8">
          <a-button size="small" danger @click="deleteNotification(record.id)">
            删除
          </a-button>
          <a-button size="small" @click="updateNotification(record.id)">
            编辑
          </a-button>
        </a-space>
      </template>
    </template>
  </a-table>

  <!-- 修改抽屉表单 -->
  <a-drawer
      title="编辑项目通知"
      placement="right"
      :visible="drawerVisible"
      @close="drawerVisible = false"
      width="600"
  >
    <a-form
        :model="formState"
        layout="vertical"
        @finish="handleSubmit"
    >
      <a-form-item
          label="通知标题"
          name="notificationTitle"
          :rules="[{ required: true, message: '请输入标题' }]"
      >
        <a-input v-model:value="formState.notificationTitle" />
      </a-form-item>

      <a-form-item
          label="通知内容"
          name="notificationContent"
          :rules="[{ required: true, message: '请输入内容' }]"
      >
        <a-textarea
            v-model:value="formState.notificationContent"
            :rows="6"
            style="width: 100%"
        />
      </a-form-item>

      <a-form-item>
        <a-button class="custom-button" html-type="submit">提交</a-button>
        <a-button style="margin-left: 10px" @click="drawerVisible = 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);
}

.error-alert {
  padding: 1rem;
  background: #ffe3e3;
  color: #ff4444;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 0.8rem;
  margin-top: 1rem;
}

.error-icon {
  display: inline-block;
  width: 1.2rem;
  height: 1.2rem;
  border-radius: 50%;
  background: #ff4444;
  color: white;
  text-align: center;
  line-height: 1.2rem;
  font-weight: bold;
}

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

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


/*橙色按钮*/

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