<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";
import {downLoadImage} from "../../api/ImageUrl.ts";

// 表格列定义
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 originalTableData = ref<PromoCode[]>([]);
const displayData = ref<PromoCode[]>([]);
const loading = ref(false);
const searchId = ref("");
const previewVisible = ref(false);
const previewImage = 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) {
      const data = Array.isArray(response.data) ? response.data : [];
      originalTableData.value = data;
      displayData.value = data;
    } else {
      message.error(response.message || "获取数据失败");
      originalTableData.value = [];
      displayData.value = [];
    }
  } catch (err) {
    console.error("查询错误:", err);
    message.error("数据加载失败，请重试");
    originalTableData.value = [];
    displayData.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 = () => {
  const value = searchId.value.trim();

  if (!value) {
    message.warning("请输入有效的推广码ID");
    return;
  }

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


  const result = originalTableData.value.filter(item => item.id === id);

  if (result.length === 0) {
    message.warning("未找到匹配的推广码ID");
  }


  displayData.value = result;
};

// 重置搜索
const reset = () => {
  searchId.value = "";
  displayData.value = originalTableData.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 () => {

  if (fileList.value.length > 0) {
    const imageUrl = await handleUpload();
    if (!imageUrl) {
      message.error('图片上传失败，无法提交');
      return;
    }
    addFormState.promoCodeImage = imageUrl;
  }

  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);

      Object.assign(addFormState, {
        promoCodeInfoKey: '',
        promoCodeLink: '',
        promoCodeImage: '',
        promoCodeStatus: false,
        projectId: Number(projectId.value)
      });
      fileList.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('删除成功');
      // 刷新数据
      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 () => {

  if (fileList.value.length > 0) {
    const imageUrl = await handleUpload();
    if (!imageUrl) {
      message.error('图片上传失败，无法提交');
      return;
    }

    editFormState.promoCodeImage = imageUrl;
  }

  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);

      fileList.value = [];
    } else {
      message.error(res.message || '编辑失败');
    }
  } catch (error) {
    message.error('编辑请求失败');
  }
};


const router = useRouter();


const goBack = () => {
  router.go(-1);
};


const fileList = ref<any[]>([]);
const uploading = ref(false);


const handleUpload = async () => {
  const formData = new FormData();
  fileList.value.forEach(file => {
    formData.append('file', file);
  });
  formData.append('biz', 'project'); // 添加biz参数

  try {
    uploading.value = true;
    const storedToken = localStorage.getItem('token');
    const res:any = await myAxios.post(
        "/file/upload",
        formData,
        {
          headers: {
            'Authorization': storedToken,
            'AflatScript': 'required',
            'Content-Type': 'multipart/form-data'
          }
        }
    );

    if (res.code === 1) {
      message.success('上传成功');

      addFormState.promoCodeImage = res.data;
      return res.data;
    } else {
      message.error(res.message || '上传失败');
      return null;
    }
  } catch (error) {
    console.error('上传失败:', error);
    message.error('上传失败');
    return null;
  } finally {
    uploading.value = false;
  }
};

const beforeUpload = (file: any) => {

  const isImage = file.type.includes('image');
  if (!isImage) {
    message.error('只能上传图片文件!');
    return false;
  }


  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
    return false;
  }


  fileList.value = [file];
  return false; // 手动上传
};

// 清除文件
const clearFile = () => {
  fileList.value = [];
};

// 添加批量选择相关状态
const selectedRowKeys = ref<number[]>([]); // 存储选中的行ID
const batchDeleteLoading = ref(false); // 批量删除加载状态

// 行选择配置
const rowSelection = {
  selectedRowKeys,
  onChange: (selectedKeys: number[]) => {
    selectedRowKeys.value = selectedKeys;
  },
};

// 批量删除方法
const batchDelete = async () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请至少选择一条记录');
    return;
  }

  try {
    batchDeleteLoading.value = true;
    const storedToken = localStorage.getItem('token');
    const res:any = await myAxios.post(
        "/promoCode/delBatch",
        { ids: selectedRowKeys.value }, // 发送选中ID数组
        {
          headers: {
            Authorization: storedToken,
            "Content-Type": "application/json"
          }
        }
    );

    if (res.code === 1) {
      message.success(`成功删除 ${selectedRowKeys.value.length} 条记录`);

      await getPromoCodes(projectId.value);

      selectedRowKeys.value = [];
    } else {
      message.error(res.message || '批量删除失败');
    }
  } catch (error) {
    message.error('批量删除操作失败');
  } finally {
    batchDeleteLoading.value = false;
  }
};
</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"
              type="number"
              class="custom-search"
              min="0"
          />
        </a-form-item>
        <a-button class="custom-button" @click="reset">重置搜索</a-button>
        <a-button class="custom-button" @click="goAddCode">新增推广码</a-button>
        <a-button @click="goBack" class="custom-button">返回</a-button>

        <!-- 添加批量删除按钮 -->
        <a-popconfirm
            title="确定要删除选中的推广码吗？"
            @confirm="batchDelete"
            ok-text="确定"
            cancel-text="取消"
        >
          <a-button
              class="custom-button"
              type="danger"
              :disabled="selectedRowKeys.length === 0"
              :loading="batchDeleteLoading"
          >
            批量删除 ({{ selectedRowKeys.length }})
          </a-button>
        </a-popconfirm>

        <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="displayData"
      :scroll="{ x: 1000, y: 550 }"
      :loading="loading"
      bordered
      rowKey="id"
      locale="{ emptyText: '暂无数据' }"
      :row-selection="rowSelection"
  >
    <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="downLoadImage+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>
  </a-table>

  <!-- 图片预览模态框 -->
  <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
    <img alt="预览图片" style="width: 100%" :src="downLoadImage+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" required>
        <a-input v-model:value="addFormState.promoCodeInfoKey" />
      </a-form-item>

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

      <a-form-item label="推广码图片" required>
        <a-upload
            :file-list="fileList"
            :before-upload="beforeUpload"
            :remove="clearFile"
            list-type="picture-card"
            accept="image/*"
            :max-count="1"
        >
          <div v-if="fileList.length < 1">
            <plus-outlined />
            <div class="ant-upload-text">上传图片</div>
          </div>
        </a-upload>
        <div v-if="addFormState.promoCodeImage">
          已上传图片:
          <a :href="addFormState.promoCodeImage" target="_blank">查看</a>
        </div>
      </a-form-item>

      <a-form-item label="状态">
        <a-input-number
           value="空闲"
            :disabled="true"
        />
      </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"
            :loading="uploading"
        >
          提交
        </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" required>
        <a-input v-model:value="editFormState.promoCodeInfoKey" />
      </a-form-item>
      <a-form-item label="推广链接" required>
        <a-input v-model:value="editFormState.promoCodeLink" />
      </a-form-item>
      <a-form-item label="推广码图片" required>
        <a-upload
            :file-list="fileList"
            :before-upload="beforeUpload"
            :remove="clearFile"
            list-type="picture-card"
            accept="image/*"
            :max-count="1"
        >
          <div v-if="fileList.length < 1">
            <plus-outlined />
            <div class="ant-upload-text">上传图片</div>
          </div>
        </a-upload>
        <div v-if="editFormState.promoCodeImage">
          当前图片:
          <a :href="editFormState.promoCodeImage" target="_blank">查看</a>
        </div>
      </a-form-item>
      <a-form-item label="状态">
        <a-tag>
          {{ editFormState.promoCodeStatus ? '占用' : '空闲' }}
        </a-tag>
      </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
            class="custom-button"
            html-type="submit"
            :loading="uploading"
        >
          提交
        </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;
}


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

:deep(.ant-upload-select-picture-card i) {
  font-size: 32px;
  color: #999;
}

:deep(.ant-upload-select-picture-card .ant-upload-text) {
  margin-top: 8px;
  color: #666;
}


</style>