<template>
  <view>
    <AppNavbar
      title="合作记录"
      left-icon="search"
      @left-click="openSearchPanel"
    />

    <view
      class="page records-page"
      :class="{ 'records-page-empty': records.length === 0 }"
    >
      <AtFloatLayout
        title="搜索合作记录"
        :is-opened="isSearchPanelVisible"
        :scroll-y="false"
        @close="closeSearchPanel"
      >
        <view class="search-menu-panel">
          <view class="filter-row">
            <text class="filter-title">品牌</text>
            <view class="filter-control">
              <AtInput
                v-model:value="query.brand"
                name="brand"
                class="filter-input"
                placeholder="请输入品牌"
              />
            </view>
          </view>
          <view class="filter-row">
            <text class="filter-title">结款状态</text>
            <view class="filter-tags">
              <AtTag
                v-for="item in settlementStatusOptions"
                :key="item.value"
                :class="getFilterTagClass(query.settlementStatus, item.value)"
                @click="updateSettlementStatus(item.value)"
              >
                {{ item.label }}
              </AtTag>
            </view>
          </view>
          <view class="filter-row">
            <text class="filter-title">完成状态</text>
            <view class="filter-tags">
              <AtTag
                v-for="item in taskStatusOptions"
                :key="item.value"
                :class="getFilterTagClass(query.taskStatus, item.value)"
                @click="updateTaskStatus(item.value)"
              >
                {{ item.label }}
              </AtTag>
            </view>
          </view>
          <view class="button-row filter-actions">
            <AtButton
              class="btn btn-plain filter-action-btn"
              @click="resetSearch"
              >重置</AtButton
            >
            <AtButton
              class="btn btn-primary filter-action-btn"
              @click="applySearch"
              >搜索</AtButton
            >
          </view>
        </view>
      </AtFloatLayout>

      <view class="records-content">
        <view
          v-for="record in records"
          :key="record.recordId"
          class="record-shell"
        >
          <AtSwipeAction
            class="record-swipe-action"
            :auto-close="true"
            :options="recordActionOptions(record.recordId)"
            @click="handleRecordActionClick"
          >
            <AtCard class="record-card" @click="openDetail(record.recordId)">
              <view class="record-card-head">
                <text class="record-title">{{ recordTitle(record) }}</text>
                <view class="record-settlement-tags">
                  <AtTag
                    v-for="tag in settlementTags(record)"
                    :key="tag.type"
                    :class="tag.className"
                    size="small"
                  >
                    {{ tag.text }}
                  </AtTag>
                </view>
              </view>
              <view class="record-info-row">
                <AtTag size="small">{{
                  record.cooperationPlatform || "未填写平台"
                }}</AtTag>
                <AtTag v-if="record.retainedMethod" size="small">{{
                  record.retainedMethod
                }}</AtTag>
                <view class="record-deadline">
                  <AtIcon value="calendar" size="14" />
                  <text>{{ record.deadline || "-" }}</text>
                </view>
              </view>
              <view class="record-progress">
                <view class="progress-head">
                  <text>笔记</text>
                  <text
                    >{{ record.completedTasksNum }}/{{ record.tasksNum }}</text
                  >
                </view>
                <AtProgress
                  :percent="taskProgressPercent(record)"
                  :stroke-width="6"
                  :color="taskProgressColor(record)"
                  :is-hide-percent="true"
                />
              </view>
            </AtCard>
          </AtSwipeAction>
        </view>

        <AtLoadMore
          v-if="records.length === 0"
          class="empty"
          status="noMore"
          no-more-text="暂无合作记录"
        />
        <AtButton v-if="hasMore" class="btn load-more" @click="loadMore"
          >加载更多</AtButton
        >
      </view>

      <view class="records-fab">
        <AtFab size="small" @click="openAddForm">
          <AtIcon value="add" size="20" color="#fff" />
        </AtFab>
      </view>

      <AppTabBar />
    </view>
  </view>
</template>

<script setup lang="ts">
import Taro, { useDidShow, usePullDownRefresh } from "@tarojs/taro";
import { computed, reactive, ref } from "vue";
import {
  deleteCollaborationRecordApi,
  getCollaborationRecordListApi,
  type CollaborationRecordDTO,
  type CollaborationRecordQuery,
  type SettlementStatusDTO,
  type SettlementStatusValue,
  type TaskStatusValue
} from "@/api/collaboration";
import { isLoggedIn, redirectToLogin } from "@/utils/auth";
import AppNavbar from "@/components/AppNavbar.vue";
import AppTabBar from "@/custom-tab-bar/index.vue";
import { themeTokens } from "@/theme/tokens";

interface SettlementTag {
  type: string;
  text: string;
  className: string;
}

interface RecordSearchQuery {
  brand: string;
  settlementStatus: SettlementStatusValue | "";
  taskStatus: TaskStatusValue | "";
}

interface RecordActionOption {
  text: string;
  action: "edit" | "delete";
  recordId: number;
  style: Record<string, string>;
}

const records = ref<CollaborationRecordDTO[]>([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = 10;
const isSearchPanelVisible = ref(false);
const query = reactive<RecordSearchQuery>({
  brand: "",
  settlementStatus: "",
  taskStatus: ""
});
const settlementStatusOptions = [
  { label: "未结款", value: "UNSETTLED" },
  { label: "未结清", value: "PARTIAL" },
  { label: "已结清", value: "SETTLED" }
];
const taskStatusOptions = [
  { label: "已完成", value: "COMPLETED" },
  { label: "未完成", value: "INCOMPLETE" }
];
const recordActionStyles = {
  edit: {
    borderBottomLeftRadius: "8px",
    borderTopLeftRadius: "8px",
    color: "#fff",
    backgroundColor: themeTokens.color.primary
  },
  delete: {
    borderBottomRightRadius: "8px",
    borderTopRightRadius: "8px",
    color: "#fff",
    backgroundColor: themeTokens.color.danger
  }
};
const hasMore = computed(() => records.value.length < total.value);

useDidShow(() => {
  if (!isLoggedIn()) {
    redirectToLogin();
    return;
  }
  reloadRecords();
});

usePullDownRefresh(async () => {
  await reloadRecords();
  Taro.stopPullDownRefresh();
});

async function reloadRecords() {
  pageNum.value = 1;
  const { data } = await fetchRecords();
  records.value = data.rows || [];
  total.value = Number(data.total || 0);
}

async function loadMore() {
  pageNum.value += 1;
  const { data } = await fetchRecords();
  records.value = [...records.value, ...(data.rows || [])];
}

function fetchRecords() {
  return getCollaborationRecordListApi(buildRecordQuery());
}

function openSearchPanel() {
  isSearchPanelVisible.value = true;
}

function closeSearchPanel() {
  isSearchPanelVisible.value = false;
}

function resetSearch() {
  query.brand = "";
  query.settlementStatus = "";
  query.taskStatus = "";
  isSearchPanelVisible.value = false;
  reloadRecords();
}

function applySearch() {
  isSearchPanelVisible.value = false;
  reloadRecords();
}

function updateSettlementStatus(value: SettlementStatusValue) {
  query.settlementStatus = value;
}

function updateTaskStatus(value: TaskStatusValue) {
  query.taskStatus = value;
}

function getFilterTagClass(currentValue: string, itemValue: string) {
  return [
    "tag",
    "filter-tag",
    currentValue === itemValue ? "filter-tag-active" : ""
  ];
}

function buildRecordQuery() {
  const params: CollaborationRecordQuery = { pageNum: pageNum.value, pageSize };
  if (query.brand) params.brand = query.brand;
  if (query.settlementStatus) params.settlementStatus = query.settlementStatus;
  if (query.taskStatus) params.taskStatus = query.taskStatus;
  return params;
}

function openAddForm() {
  Taro.navigateTo({ url: "/pages/collaboration/form/index" });
}

function openEditForm(recordId: number) {
  Taro.navigateTo({
    url: `/pages/collaboration/form/index?recordId=${recordId}`
  });
}

function recordActionOptions(recordId: number): RecordActionOption[] {
  return [
    { text: "编辑", action: "edit", recordId, style: recordActionStyles.edit },
    {
      text: "删除",
      action: "delete",
      recordId,
      style: recordActionStyles.delete
    }
  ];
}

function handleRecordActionClick(item: RecordActionOption) {
  if (item.action === "edit") {
    openEditForm(item.recordId);
    return;
  }
  deleteRecord(item.recordId);
}

async function deleteRecord(recordId: number) {
  const result = await Taro.showModal({
    title: "删除记录",
    content: "确认删除这条合作记录？"
  });
  if (!result.confirm) return;
  await deleteCollaborationRecordApi(recordId);
  await reloadRecords();
}

function openDetail(recordId: number) {
  Taro.navigateTo({
    url: `/pages/collaboration/detail/index?recordId=${recordId}`
  });
}

function taskProgressPercent(record: CollaborationRecordDTO) {
  const total = Number(record.tasksNum || 0);
  if (total <= 0) return 0;
  return Math.round((record.completedTasksNum / total) * 100);
}

function taskProgressColor(record: CollaborationRecordDTO) {
  if (record.completedTasksNum <= 0) return themeTokens.color.danger;
  if (record.completedTasksNum >= record.tasksNum)
    return themeTokens.color.success;
  return themeTokens.color.info;
}

function recordTitle(record: CollaborationRecordDTO) {
  return `${record.brand || "-"} / ${record.goods || "-"}`;
}

function settlementTags(record: CollaborationRecordDTO) {
  return [
    toSettlementTag("purchase", "拍单", record.purchaseSettlementStatus),
    toSettlementTag("delivery", "快递", record.deliverySettlementStatus),
    toSettlementTag("remuneration", "稿费", record.remunerationSettlementStatus)
  ].filter((tag): tag is SettlementTag => Boolean(tag));
}

function toSettlementTag(
  type: string,
  title: string,
  status?: SettlementStatusDTO
) {
  if (!shouldShowSettlement(status)) return "";
  return {
    type,
    text: `${title}${status.label || "-"}`,
    className: settlementTagClass(status)
  };
}

function shouldShowSettlement(status?: SettlementStatusDTO) {
  return Boolean(
    status && status.status !== "NONE" && status.label !== "无结款项"
  );
}

function settlementTagClass(status: SettlementStatusDTO) {
  const classMap = {
    UNSETTLED: "settlement-tag-danger",
    PARTIAL: "settlement-tag-warning",
    SETTLED: "settlement-tag-success"
  };
  return classMap[status.status] || "";
}
</script>

<style lang="scss">
.records-page {
  padding-bottom: calc($page-bottom-space + env(safe-area-inset-bottom));
  background: $bg-page;
}

.records-page-empty {
  min-height: auto;
}

.records-content {
  padding-bottom: $space-xl;
}

.search-menu-panel {
  box-sizing: border-box;
  display: grid;
  gap: $space-md;
  width: 100%;
  padding: $space-sm 0 0;
}

.filter-row {
  display: flex;
  gap: $space-md;
  align-items: center;
  min-height: 60px;
}

.filter-title {
  flex: 0 0 132px;
  font-size: $font-md;
  color: $text-regular;
}

.filter-control {
  flex: 1;
  min-width: 0;
}

.filter-input.at-input {
  height: 56px;
  min-height: 56px;
  padding: 0 $space-sm;
  margin-left: 0;
  font-size: $font-sm;
  border: 1px solid $border-color-strong;
  border-radius: $radius-sm;
}

.filter-input.at-input .at-input__input,
.filter-input.at-input input {
  font-size: $font-sm;
}

.filter-input.at-input .at-input__input::placeholder,
.filter-input.at-input input::placeholder {
  font-size: $font-sm;
}

.filter-tags {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
  gap: $space-sm;
  align-items: center;
}

.filter-tag.at-tag {
  justify-content: center;
  min-width: 104px;
  height: 56px;
  padding: 0 $space-sm;
  line-height: 56px;
  color: $text-regular;
  background: $bg-soft;
}

.filter-tag-active.at-tag {
  color: $color-white;
  background: $color-primary;
}

.filter-actions {
  padding-top: $space-md;
  margin-top: $space-sm;
  border-top: 1px solid $border-color-light;
}

.filter-action-btn.at-button {
  height: 56px;
  font-size: $font-md;
  line-height: 56px;
}

.record-shell {
  padding: $space-sm 0;
}

.record-swipe-action {
  overflow: hidden;
  border-radius: $radius-md;
}

.record-swipe-action.at-swipe-action {
  background: transparent;
}

.record-swipe-action .at-swipe-action__content {
  overflow: hidden;
  border-radius: $radius-md;
}

.record-card.at-card {
  margin-right: 0;
  margin-left: 0;
}

.record-card {
  min-width: 0;
}

.record-swipe-action .at-swipe-action__options {
  top: 1px;
  bottom: 1px;
  height: auto;
  padding-left: $space-xs;
}

.record-card.at-card .at-card__header {
  display: none;
}

.record-card-head {
  display: flex;
  gap: $space-md;
  align-items: flex-start;
  justify-content: space-between;
  padding-bottom: $space-sm;
  margin-bottom: $space-sm;
  border-bottom: 1px solid $border-color-light;
}

.record-title {
  flex: 1;
  min-width: 0;
  font-size: $font-lg;
  font-weight: 600;
  color: $text-primary;
}

.record-settlement-tags {
  display: flex;
  flex: 0 0 auto;
  flex-wrap: wrap;
  gap: $space-xs;
  justify-content: flex-end;
  max-width: 44%;
}

.record-info-row,
.record-deadline {
  display: flex;
  flex-wrap: wrap;
  gap: $space-xs;
  align-items: center;
}

.record-info-row {
  row-gap: $space-sm;
}

.record-deadline {
  font-size: $font-sm;
  color: $text-secondary;
}

.record-progress {
  margin-top: $space-md;
}

.progress-head {
  display: flex;
  justify-content: space-between;
  margin-bottom: $space-xs;
  font-size: $font-sm;
  color: $text-secondary;
}

.load-more.at-button {
  margin-top: $space-lg;
}

.records-fab {
  position: fixed;
  right: $space-xl;
  bottom: calc($tabbar-height + $space-xl + env(safe-area-inset-bottom));
  z-index: 80;
}

.records-fab .at-fab {
  background: $color-primary;
}

.records-page .at-float-layout {
  z-index: 1100;
}

.records-page .at-float-layout .layout-body {
  min-height: auto;
  max-height: none;
  padding: $space-lg $space-xl calc($space-xl + env(safe-area-inset-bottom));
  overflow: visible;
}

.records-page .at-float-layout .layout-body__content {
  min-height: auto;
  max-height: none;
  overflow: visible;
}

.records-page .at-float-layout .at-float-layout__container {
  min-height: auto;
}
</style>
