<template>
  <div class="container">
    <!-- 搜索和筛选区域 -->
    <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-form-item label="收益来源">
            <a-select
                v-model:value="revenueSourceFilter"
                style="width: 120px"
                @change="applyFilters"
            >
              <a-select-option value="all">全部</a-select-option>
              <a-select-option :value="false">推广码</a-select-option>
              <a-select-option :value="true">抽成</a-select-option>
            </a-select>
          </a-form-item>
          <a-button class="custom-button" @click="reset">重置搜索</a-button>

          <a-button class="custom-button" @click="showModal">新增项目明细</a-button>
          <a-button class="custom-button" @click="goBack">返回</a-button>
        </a-space>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <a-table
        :dataSource="paginatedData"
        :columns="columns"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        bordered
    >
      <template #bodyCell="{ column, record }">
        <!-- 格式化金额显示 -->
        <template v-if="column.dataIndex === 'settlementRevenue'">
          ¥{{ record.settlementRevenue.toFixed(2) }}
        </template>

        <!-- 收益来源列 -->
        <template v-if="column.dataIndex === 'revenueSource'">
          <a-tag v-if="record.revenueSource" color="orange">抽成</a-tag>
          <a-tag v-else color="green">推广码</a-tag>
        </template>

        <!-- 操作列 -->
        <template v-if="column.key === 'action'">
          <a-space :size="8">
            <a-button size="small" danger @click="deleteRecord(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增项目明细弹窗 -->
    <a-modal
        v-model:visible="visible"
        title="新增项目明细"
        @ok="handleAdd"
        @cancel="handleCancel"
    >
      <a-form :model="form">
        <a-form-item label="项目明细名称" required>
          <a-input v-model:value="form.projectDetailName" />
        </a-form-item>
        <a-form-item label="结算数量" :rules="[{ required: true, message: '请输入结算数量' }]" required>
          <a-input-number
              v-model:value="form.settlementQuantity"
              min="0"
              :precision="0"
              style="width: 100%"
              placeholder="请输入格式为1"
          />
        </a-form-item>

        <a-form-item label="结算收益" :rules="[{ required: true, message: '请输入结算收益' }]" required>
          <a-input-number
              v-model:value="form.settlementRevenue"
              min="0"
              :precision="2"
              style="width: 100%"
              placeholder="请输入格式为0.01"
          />
        </a-form-item>
        <a-form-item label="作业时间" required>
          <a-date-picker v-model:value="form.workTime" format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="结算时间" required>
          <a-date-picker v-model:value="form.settlementTime" format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="推广码申请ID">
          <a-input-number v-model:value="form.promoCodeApplyId" disabled/>
        </a-form-item>
        <a-form-item label="项目ID">
          <a-input-number v-model:value="form.projectId" disabled/>
        </a-form-item>
        <a-form-item label="用户ID">
          <a-input-number v-model:value="form.userId" disabled/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import type { TableProps } from 'ant-design-vue';
import myAxios from '../../api/myAxios.ts';
import { message } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import router from '../../router';
import dayjs from 'dayjs';


interface SettlementRecord {
  id: number;
  projectDetailName: string;
  settlementQuantity: number;
  settlementRevenue: number;
  settlementTime: string;
  workTime: string;
  revenueSource: boolean;
}


// 表格列定义
const columns = ref([
  {
    title: '项目结算记录ID',
    dataIndex: 'id',
    key: 'id',
    width: 100,
    align: 'center',
  },
  {
    title: '项目明细名称',
    dataIndex: 'projectDetailName',
    key: 'projectDetailName',
    width: 120,
    align: 'center',
  },
  {
    title: '结算数量',
    dataIndex: 'settlementQuantity',
    key: 'settlementQuantity',
    width: 120,
    align: 'center',
  },
  {
    title: '结算收益',
    dataIndex: 'settlementRevenue',
    key: 'settlementRevenue',
    width: 120,
    align: 'center',
  },
  {
    title: '结算时间',
    dataIndex: 'settlementTime',
    key: 'settlementTime',
    width: 120,
    align: 'center',
  },
  {
    title: '作业时间',
    dataIndex: 'workTime',
    key: 'workTime',
    width: 120,
    align: 'center',
  },
  {
    title: '收益来源',
    dataIndex: 'revenueSource',
    key: 'revenueSource',
    width: 120,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 100,
    align: 'center',
  },
]);
const allData = ref<SettlementRecord[]>([]); // 存储所有数据
const filteredData = ref<SettlementRecord[]>([]); // 存储过滤后的数据
const loading = ref(false);
const searchId = ref(''); // 新增搜索ID绑定
const originalData = ref<SettlementRecord[]>([]); // 存储原始数据


const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
});


const route = useRoute();
const idFromRoute = route.query.id as string | undefined;
const projectIdFromRoute = route.query.projectId as string | undefined;
const userIdFromRoute = route.query.userId as string | undefined;


const paginatedData = computed(() => {
  const start = (pagination.current - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  return filteredData.value.slice(start, end);
});

// 获取项目结算记录数据
const fetchData = async () => {
  const storedToken = localStorage.getItem('token');

  try {
    loading.value = true;

    const response: any = await myAxios.post(
        '/projectSettlement/queryByPId',
        { id: idFromRoute },
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: storedToken,
            AfterScript: 'required-script',
          },
        }
    );

    console.log('接口响应:', response);

    if (response.code === 1) {
      allData.value = response.data;
      originalData.value = [...response.data];
      filteredData.value = [...response.data];
      pagination.total = response.data.length;
    } else {
      message.error(response.message || '获取数据失败');
      allData.value = [];
      originalData.value = [];
      filteredData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('请求失败:', error);
    message.error('请求数据失败，请稍后重试');
    allData.value = [];
    originalData.value = [];
    filteredData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// ID搜索处理 - 前端过滤
const handleIdSearch = (value: string) => {
  const idStr = value.trim();
  if (!idStr) {

    reset();
    return;
  }

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


  const result = originalData.value.filter((record) => record.id === id);

  if (result.length > 0) {
    filteredData.value = result;
    pagination.total = result.length;
    pagination.current = 1;
  } else {
    message.info('未找到匹配的记录');
    filteredData.value = [];
    pagination.total = 0;
  }
};

// 重置搜索
const reset = () => {
  searchId.value = '';
  filteredData.value = [...originalData.value];
  pagination.total = originalData.value.length;
  pagination.current = 1;
  revenueSourceFilter.value = 'all';
  applyFilters();
};


const handleTableChange: TableProps['onChange'] = (pag) => {
  if (pag) {
    pagination.current = pag.current!;
    pagination.pageSize = pag.pageSize!;
  }
};


const goBack = () => {
  router.push('/applicationRecord');
};

// 删除记录
const deleteRecord = async (id: number) => {
  const storedToken = localStorage.getItem('token');

  try {
    const response: any = await myAxios.post(
        '/projectSettlement/delete',
        { id },
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: storedToken,
            AfterScript: 'required-script',
          },
        }
    );

    console.log('删除接口响应:', response);

    if (response.code === 1) {
      message.success('删除成功');

      if (searchId.value) {

        handleIdSearch(searchId.value);
      } else {

        await fetchData();
      }
    } else {
      message.error(response.message || '删除失败');
    }
  } catch (error) {
    console.error('删除请求失败:', error);
    message.error('删除数据失败，请稍后重试');
  }
};

onMounted(() => {
  fetchData();
});

const visible = ref(false);
const form = reactive({
  projectDetailName: '',
  settlementQuantity: '',
  settlementRevenue: '',
  workTime: null,
  settlementTime: null,

  promoCodeApplyId: idFromRoute || 0,
  projectId: projectIdFromRoute || 0,
  userId: userIdFromRoute || 0,
});




const showModal = () => {
  visible.value = true;

  form.projectDetailName = '';
  form.settlementQuantity = '';
  form.settlementRevenue ='';
  form.workTime = null;
  form.settlementTime = null;
};
const handleCancel = () => {
  visible.value = false;
};

const handleAdd = async () => {
  if (!form.projectDetailName || !form.settlementQuantity || !form.settlementRevenue || !form.workTime || !form.settlementTime || !form.promoCodeApplyId || !form.projectId || !form.userId) {
    message.error('请填写完整信息');
    return;
  }

  const storedToken = localStorage.getItem('token');

  try {
    const response:any = await myAxios.post(
        '/projectSettlement/add',
        {
          projectDetailName: form.projectDetailName,
          settlementQuantity: form.settlementQuantity,
          settlementRevenue: form.settlementRevenue,
          workTime: dayjs(form.workTime).format('YYYY-MM-DD'),
          settlementTime: dayjs(form.settlementTime).format('YYYY-MM-DD'),
          promoCodeApplyId: form.promoCodeApplyId,
          projectId: form.projectId,
          userId: form.userId,
        },
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: storedToken,
            AfterScript: 'required-script',
          },
        }
    );

    if (response.code === 1) {
      message.success('新增成功');
      visible.value = false;
      await fetchData(); // 刷新数据
    } else {
      message.error(response.message || '新增失败');
    }
  } catch (error) {
    console.error('请求失败:', error);
    message.error('新增数据失败，请稍后重试');
  }
};

const revenueSourceFilter = ref<string | boolean>('all');


const applyFilters = () => {
  let result = [...originalData.value];

  if (searchId.value.trim() !== '') {
    const id = Number(searchId.value.trim());
    if (!isNaN(id)) {
      result = result.filter(record => record.id === id);
    }
  }


  if (revenueSourceFilter.value !== 'all') {
    result = result.filter(record => record.revenueSource === revenueSourceFilter.value);
  }

  filteredData.value = result;
  pagination.total = result.length;
  pagination.current = 1;
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}


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

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


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

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


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