<template>
  <!-- 搜索框 -->
  <div class="search-box">
    <a-form layout="inline">
      <a-space>
        <a-form-item label="项目名称">
          <a-input-search
              style="width: 300px"
              placeholder="请输入项目名称"
              enter-button
              @search="handleProjectSearch"
              v-model:value="searchProjectName"
              class="custom-search"
          />
        </a-form-item>
        <a-button class="custom-button" @click="goAddProject">新增项目</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: 2500, y: 550 }"
      :loading="loading"
      :pagination="pagination"
      bordered
      rowKey="id"
      @change="handleTableChange"
  >
    <template #bodyCell="{ column, record }">
      <!-- 项目图片 -->
      <template v-if="column.key === 'projectImage'">
<!--        <a-avatar :src="`http://localhost:3456/file/download/view/project-`+record.projectImage" shape="square" :size="64"/>-->
        <a-avatar :src="record.projectImage" shape="square" :size="64"/>
      </template>

      <!-- 项目状态 -->
      <template v-if="column.key === 'projectStatus'">
        <a-tag :color="getStatusColor(record.projectStatus)">
          {{ getStatusText(record.projectStatus) }}
        </a-tag>
      </template>

      <!-- 是否上架 -->
      <template v-if="column.key === 'isShelves'">
        <a-tag :color="record.isShelves ? 'green' : 'red'">
          {{ record.isShelves ? '已上架' : '已下架' }}
        </a-tag>
      </template>

      <!-- 操作列 -->
      <template v-if="column.key === 'action'">
        <a-space :size="8">
          <a-button
              size="small"
              :type="record.isShelves ? 'dashed' : 'primary'"
              @click="toggleShelves(record)"
          >
            {{ record.isShelves ? '去下架' : '去上架' }}
          </a-button>
          <a-button
              size="small"
              danger
              @click="deleteProject(record.id)"
          >
            删除
          </a-button>
          <a-button
              size="small"
              type="link"
              @click="showDetails(record.id)"
          >
            详情
          </a-button>
          <a-button
              size="small"
              type="link"
              @click="moneyDetails(record.id)"
          >
            项目明细
          </a-button>
          <a-button
              size="small"
              type="link"
              @click="projectNotice(record.id)"
          >
            项目通知
          </a-button>
          <a-button
              size="small"
              type="link"
              @click="promotionCode(record.id)"
          >
            推广码
          </a-button>
        </a-space>
      </template>
    </template>
  </a-table>




</template>

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

import router from "../../router";


const loading = ref(false);
const total = ref(0);

const searchProjectName = ref(""); // 改为项目名称搜索参数
const searchParams = ref({
  current: 1,
  pageSize: 10,
  sortField: "id",
  sortOrder: "ascend",
  userRole: null,
  projectName: "" // 新增项目名称查询参数
});


const getStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    running: '项目运行',
    full: '人数已满',
    paused: '项目暂停'
  };
  return statusMap[status] || '未知状态';
};


const getStatusColor = (status: string) => {
  const colorMap: { [key: string]: string } = {
    running: 'blue',
    full: 'orange',
    paused: 'red'
  };
  return colorMap[status] || 'gray';
};

//用户表
const columns = [
  {
    title: '项目ID',
    dataIndex: 'id',
    width: 20,
    key: 'id',
    fixed: 'left',
    align: 'center'
  },

  {
    title: '头像',
    dataIndex: 'projectImage',
    key: 'projectImage',
    width: 20,
    fixed: 'left',
    align: 'center'
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    width: 30,
    key: 'projectName',
    fixed: 'left',
    align: 'center'
  },
  {
    title: '项目价格',
    dataIndex: 'projectPrice',
    width: 30,
    key: 'projectPrice',
    align: 'center'
  },
  {
    title: '当前推广人数',
    dataIndex: 'currentPromotionCount',
    width: 40,
    key: 'currentPromotionCount',
    align: 'center'
  },
  {
    title: '结算周期',
    dataIndex: 'projectSettlementCycle',
    key: 'projectSettlementCycle',
    width: 30,
    align: 'center'
  },
  {
    title: '最大推广人数',
    dataIndex: 'maxPromoterCount',
    key: 'maxPromoterCount',
    width: 70,
    align: 'center'
  },
  {
    title: '项目状态',
    dataIndex: 'projectStatus',
    key: 'projectStatus',
    width: 40,
    align: 'center'
  },
  {
    title: '是否上架',
    dataIndex: 'isShelves',
    key: 'isShelves',
    width: 40,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 70,
    align: 'center'
  }
];
// 新增上架/下架操作
const toggleShelves = async (record: any) => {
  try {
    const storedToken = localStorage.getItem('token');
    const res: any = await myAxios.post(
        "/project/shelves",
        {
          id: record.id,
        },
        { headers: { Authorization: storedToken } }
    );

    if (res.code === 1) {
      message.success('状态更新成功');
      // 使用 Object.assign 触发响应式更新
      Object.assign(record, { isShelves: !record.isShelves });
      // 或重新获取数据（推荐）
      await getProjectList();
    }else {
      message.error(res.message || '操作失败');
    }
  } catch (error) {
    console.error('操作失败:', error);
    message.error('状态更新失败');
  }
};

interface ProjectRecord {
  // 这里根据实际数据结构定义属性
  superHostList?: string[];
  // 其他属性...
}
// 项目名称搜索方法
const handleProjectSearch = async () => {
  // 将搜索参数同步到分页查询参数
  searchParams.value.projectName = searchProjectName.value;
  searchParams.value.current = 1; // 重置到第一页
  await getProjectList();
};
//用户分页查询
const getProjectList = async () => {
  loading.value = true;
  try {
    const storedToken = localStorage.getItem('token');
    if (!storedToken) throw new Error('未找到登录信息');

    const res:any = await myAxios.post("/project/page",
        {
          ...searchParams.value,
          projectName: searchParams.value.projectName
        },
        { headers: { Authorization: storedToken } }
    );
    console.log(res)
    if (res.code === 1 && res.data && Array.isArray(res.data.records)) {
      tableData.value = res.data.records.map((item: ProjectRecord)  => ({
        ...item,
        superUserList: item.superHostList? item.superHostList.join(', ') : '无'
      }));
      // 同步总条数到分页组件
      total.value = res.data.total;
      pagination.value.total = res.data.total; // 新增此行
      pagination.value.current = searchParams.value.current; // 同步当前页
    } else {
      message.error(res.message || '请求失败');
    }
  } catch (error) {
    console.error("请求失败:", error);
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

onMounted(getProjectList);
//分页

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  pageSizeOptions: ['10', '20', '50', '100']
});
const handleTableChange = (pag: any, _filters: any, sorter: any) => {
  // 处理排序参数
  const sortParams = Array.isArray(sorter) ? sorter[0] : sorter;

  searchParams.value = {
    ...searchParams.value,
    current: pag.current,
    pageSize: pag.pageSize,
    sortField: sortParams?.field || 'id',
    sortOrder: sortParams?.order
        ? sortParams.order === 'ascend' ? 'ascend' : 'descend'
        : 'ascend'
  };

  // 同步到分页组件
  pagination.value = {
    ...pagination.value,
    current: pag.current,
    pageSize: pag.pageSize
  };

  getProjectList();
};

// ID查询方法
interface Project {
  id: number;
  projectName: string;
  projectImage: string;
  projectSettlementCycle: number;
  maxPromoterCount: number;
  projectStatus: string;
  projectDescription: string;
  settlementDesc: string;
  // 其他可能存在的属性根据实际情况补充
}

const tableData = ref<Project[]>([]);

// 删除项目
const deleteProject = async (id: number) => {
  try {
    const storedToken = localStorage.getItem('token');
    const res:any = await myAxios.post(
        "/project/delete",
        { id },
        {
          headers: {
            Authorization: storedToken,
            'AfterScript': 'required-script' // 统一添加请求头
          }
        }
    );

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



// 重置按钮
const reset = () => {
  searchProjectName.value = "";
  searchParams.value = {
    current: 1,
    pageSize: 10,
    sortField: "id",
    sortOrder: "ascend",
    userRole: null,
    projectName: ""
  };
  getProjectList();
};

//去新增项目
const goAddProject=()=>{
  router.push('/addproject')
}

const showDetails=(id:string)=>{
  router.push({
    path:'/projectDetail',
    query:{
      id:String(id)
    }
  })
}
//去项目明细
const moneyDetails=(id:string)=>{
  router.push({
    path:'/moneyDetail',
    query:{
      id:String(id)
    }
  })
}

//去项目通知
const projectNotice=(id:number)=>{
  router.push({
    path:'/projectNotice',
    query:{
      id:String(id)
    }
  })
}

//去推广码
const promotionCode=(id:number)=>{
  router.push({
    path:'/promotionCode',
    query:{
      id:String(id)
    }
  })
}
</script>

<style scoped>
.action-btn {
  padding: 0 8px;
}
/* 分割线样式 */
:deep(.ant-divider-vertical) {
  border-color: rgba(0, 0, 0, 0.15);
  height: 1.2em;
  margin: 0 4px;
}


:deep(.ant-descriptions-item-label) {
  font-weight: 600;
  width: 120px;
}


.info-card :deep(.ant-card-head) {
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}



/* 角色颜色映射 */
:root {
  --role-user: #87d068;
  --role-admin: #f50;
  --role-boss: #722ed1;
}

.search-box {
  margin-bottom: 10px;
}


/*橙色按钮*/

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