<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: 2000, y: 550 }"
      :loading="loading"
      :pagination="pagination"
      bordered
      rowKey="id"
      @change="handleTableChange"
  >
    <template #bodyCell="{ column, record }">
      <!-- 项目图片 -->
      <template v-if="column.key === 'projectImage'">
        <a-avatar :src="downLoadImage+record.projectImage" shape="square" :size="64"/>
      </template>
      <template v-if="column.key === 'currentPromotionCount'">
        {{record.currentPromotionCount }}人
      </template>
      <template v-if="column.key === 'projectSettlementCycle'">
        T+{{record.projectSettlementCycle}}
      </template>
      <template v-if="column.key === 'maxPromoterCount'">
        {{record.maxPromoterCount}}人
      </template>
      <template v-if="column.key === 'projectPrice'">
        ¥{{record.projectPrice }}
      </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-tag
              size="small"
              :color="record.isShelves ? 'orange' : 'red'"
              @click="toggleShelves(record)"
          >
            {{ record.isShelves ? '去下架' : '去上架' }}
          </a-tag>
          <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, Modal } from "ant-design-vue";
import {downLoadImage} from "../../api/ImageUrl.ts";
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: 10,
    key: 'id',
    fixed: 'left',
    align: 'center',
    sorter: true,
    sortDirections: ['ascend', 'descend']
  },

  {
    title: '项目图片',
    dataIndex: 'projectImage',
    key: 'projectImage',
    width: 10,
    fixed: 'left',
    align: 'center'
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    width: 15,
    key: 'projectName',
    fixed: 'left',
    align: 'center'
  },
  {
    title: '项目价格',
    dataIndex: 'projectPrice',
    width: 20,
    key: 'projectPrice',
    align: 'center',
    sorter: true,
    sortDirections: ['ascend', 'descend']
  },
  {
    title: '当前推广人数',
    dataIndex: 'currentPromotionCount',
    width: 20,
    key: 'currentPromotionCount',
    align: 'center',
    sorter: true,
    sortDirections: ['ascend', 'descend']
  },
  {
    title: '结算周期',
    dataIndex: 'projectSettlementCycle',
    key: 'projectSettlementCycle',
    width: 10,
    align: 'center',
    sorter: true,
    sortDirections: ['ascend', 'descend']
  },
  {
    title: '最大推广人数',
    dataIndex: 'maxPromoterCount',
    key: 'maxPromoterCount',
    width: 20,
    align: 'center',
    sorter: true,
    sortDirections: ['ascend', 'descend']
  },
  {
    title: '项目状态',
    dataIndex: 'projectStatus',
    key: 'projectStatus',
    width: 20,
    align: 'center'
  },
  {
    title: '是否上架',
    dataIndex: 'isShelves',
    key: 'isShelves',
    width: 20,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 40,
    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(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 params = {
      ...searchParams.value,

      fuzzyQuery: true,
      fuzzyField: 'projectName'
    };

    const res:any = await myAxios.post("/project/page",
        params,
        { 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, _: any, sorter: any) => {

  let sortField = "id";
  let sortOrder = "ascend";
  if (sorter.field) {
    sortField = sorter.field;
    sortOrder = sorter.order;
  }
  searchParams.value = {
    ...searchParams.value,
    current: pag.current,
    pageSize: pag.pageSize,
    sortField: sortField,
    sortOrder: sortOrder
  };


  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 = (id: number) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除该项目吗？删除后数据将无法恢复！',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      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('删除操作失败');
      }
    },
    onCancel() {

    },
  });
};

// 重置按钮
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>


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