<template>
  <view class="page-container">
    <uni-nav-bar
      statusBar="true"
      left-icon="back"
      title="工单交接"
      background-color="#157A2C"
      color="#fff"
      @clickLeft="back"
    ></uni-nav-bar>

    <!-- 搜索栏 -->
    <view class="search-wrapper">
      <view class="search-bar">
        <view class="search-input-box">
          <uni-icons type="search" size="18" color="#999"></uni-icons>
          <input
            v-model="searchForm.code"
            placeholder="请输入生产工单号搜索"
            placeholder-class="search-placeholder"
            class="search-input"
            confirm-type="search"
            @confirm="doSearch"
          />
        </view>
        <view class="search-actions">
          <view class="filter-btn" @click="showFilter = true">
            <uni-icons type="settings" size="20" color="#666"></uni-icons>
          </view>
          <view class="search-btn" @click="doSearch">
            <text class="search-btn-text">搜索</text>
          </view>
        </view>
      </view>
    </view>

    <!-- Tab状态筛选 -->
    <view class="tab-bar">
      <view
        v-for="tab in tabList"
        :key="tab.value"
        class="tab-item"
        :class="{ 'tab-item--active': activeTab === tab.value }"
        @click="switchTab(tab.value)"
      >
        <text class="tab-text">{{ tab.label }}</text>
        <view v-if="activeTab === tab.value" class="tab-line"></view>
      </view>
    </view>

    <!-- 列表区域 -->
    <view class="list-container">
      <u-list @scrolltolower="loadMore">
        <view v-for="(item, index) in list" :key="item.id" class="order-card">
          <!-- 卡片头部 -->
          <view class="card-header" @click="handleDetail(item)">
            <view class="header-left">
              <view class="serial-num">{{ index + 1 }}</view>
              <text class="order-code">{{ item.code || "暂无编码" }}</text>
            </view>
            <view class="status-tag" :class="'status-tag--' + item.status">
              <text class="status-text">{{ getStatusText(item.status) }}</text>
            </view>
          </view>

          <!-- 卡片内容 -->
          <view class="card-body" @click="handleDetail(item)">
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">交接类型</text>
                <text class="info-value">{{ getTypeName(item.type) }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">交接时间</text>
                <text class="info-value">{{ item.initiateTime || "-" }}</text>
              </view>
            </view>
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">生产工单号</text>
                <text class="info-value">{{ item.workOrderCode || "-" }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">产品名称</text>
                <text class="info-value">{{ item.categoryName || "-" }}</text>
              </view>
            </view>
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">批次号</text>
                <text class="info-value">{{ item.batchNo || "-" }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">工序名称</text>
                <text class="info-value">{{
                  item.initiateTaskName || "-"
                }}</text>
              </view>
            </view>
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">交接数量</text>
                <text class="info-value highlight">{{
                  item.handoverNuM || 0
                }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">交接重量</text>
                <text class="info-value highlight">{{
                  item.handoverWeight || 0
                }}</text>
              </view>
            </view>
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">交接班组</text>
                <text class="info-value">{{ item.acceptTeamName || "-" }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">交接人</text>
                <text class="info-value">{{ item.acceptName || "-" }}</text>
              </view>
            </view>
          </view>

          <!-- 卡片底部操作 -->
          <view class="card-footer" v-if="showActions(item)" @click.stop>
            <view
              v-if="item.status == 1"
              class="action-btn action-btn--primary"
              @click="handleAccept(item)"
            >
              接收
            </view>
            <view
              v-if="isEditable(item.status)"
              class="action-btn action-btn--primary"
              @click="handleEdit(item)"
            >
              编辑
            </view>
            <view
              v-if="isEditable(item.status)"
              class="action-btn action-btn--danger"
              @click="handleDelete(item)"
            >
              删除
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading && list.length > 0" class="loading-more">
          <u-loading-icon size="24"></u-loading-icon>
          <text class="loading-text">加载中...</text>
        </view>
        <view v-if="isEnd && list.length > 0" class="loading-more">
          <text class="loading-text">没有更多了</text>
        </view>
        <view v-if="!loading && list.length === 0" class="empty-state">
          <u-empty iconSize="150" textSize="32" text="暂无交接单数据"></u-empty>
        </view>
        <view style="height: 20rpx"></view>
      </u-list>
    </view>

    <!-- 筛选弹窗 -->
    <u-popup :show="showFilter" mode="top" @close="showFilter = false">
      <view class="filter-popup">
        <view class="filter-title">筛选条件</view>
        <view class="filter-form">
          <view class="filter-item">
            <text class="filter-label">交接类型</text>
            <view class="filter-select">
              <view
                v-for="opt in handoverTypeOptions"
                :key="opt.value"
                class="select-tag"
                :class="{ 'select-tag--active': searchForm.type === opt.value }"
                @click="
                  searchForm.type =
                    searchForm.type === opt.value ? '' : opt.value
                "
              >
                {{ opt.label }}
              </view>
            </view>
          </view>
        </view>
        <view class="filter-actions">
          <view class="filter-btn-reset" @click="resetFilter">重置</view>
          <view class="filter-btn-confirm" @click="confirmFilter">确定</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { handoverPage, deleteHandover } from "@/api/pda/workOrderHandover.js";

const STATUS_TEXT = {
  0: "待提交",
  1: "待接收",
  2: "已接收",
  3: "已驳回",
};

const TYPE_MAP = {
  1: "物品移交",
  2: "班次交接",
};

const EDITABLE_STATUS = [0, 3];

export default {
  data() {
    return {
      list: [],
      loading: false,
      refreshing: false,
      isEnd: false,
      page: 1,
      pageSize: 20,
      activeTab: "",
      showFilter: false,
      searchForm: {
        code: "",
        type: "",
      },
      tabList: [
        { label: "全部", value: "" },
        { label: "待提交", value: 0 },
        { label: "待接收", value: 1 },
        { label: "已接收", value: 2 },
        { label: "已驳回", value: 3 },
      ],
      handoverTypeOptions: [
        { label: "物品移交", value: 1 },
        { label: "班次交接", value: 2 },
      ],
    };
  },

  onLoad() {
    this.loadData();
  },

  onShow() {
    // 从详情页返回时刷新列表
    if (this._hasShown) {
      this.refreshList();
    }
    this._hasShown = true;
  },

  methods: {
    back() {
      uni.navigateBack();
    },

    getStatusText(status) {
      return STATUS_TEXT[status] || "未知";
    },

    getTypeName(type) {
      return TYPE_MAP[type] || "-";
    },

    isEditable(status) {
      return EDITABLE_STATUS.includes(Number(status));
    },

    showActions(item) {
      return item.status == 1 || this.isEditable(item.status);
    },

    switchTab(value) {
      if (this.activeTab === value) return;
      this.activeTab = value;
      this.refreshList();
    },

    doSearch() {
      this.refreshList();
    },

    resetFilter() {
      this.searchForm.type = "";
    },

    confirmFilter() {
      this.showFilter = false;
      this.refreshList();
    },

    refreshList() {
      this.page = 1;
      this.list = [];
      this.isEnd = false;
      this.loadData();
    },

    onRefresh() {
      this.refreshing = true;
      this.page = 1;
      this.list = [];
      this.isEnd = false;
      this.loadData().finally(() => {
        this.refreshing = false;
      });
    },

    loadMore() {
      if (this.loading || this.isEnd) return;
      this.page++;
      this.loadData();
    },

    async loadData() {
      if (this.loading) return;
      this.loading = true;

      try {
        const params = {
          pageNum: this.page,
          size: this.pageSize,
        };

        if (this.searchForm.code) {
          params.code = this.searchForm.code;
        }
        if (this.searchForm.type !== "" && this.searchForm.type !== null) {
          params.type = this.searchForm.type;
        }
        if (this.activeTab !== "" && this.activeTab !== null) {
          params.status = this.activeTab;
        }

        const res = await handoverPage(params);
        const newList = res.list || res.records || [];

        if (this.page === 1) {
          this.list = newList;
        } else {
          this.list = [...this.list, ...newList];
        }

        const total = res.count || res.total || 0;
        this.isEnd = this.list.length >= total;
      } catch (e) {
        console.error("加载交接单列表失败", e);
        if (this.page > 1) this.page--;
      } finally {
        this.loading = false;
      }
    },

    handleDetail(item) {
      uni.navigateTo({
        url: `/pages/pda/work_order_handover/detail/detail?id=${item.id}&status=${item.status}&mode=detail`,
      });
    },

    handleEdit(item) {
      uni.navigateTo({
        url: `/pages/pda/work_order_handover/detail/detail?id=${item.id}&status=${item.status}&mode=edit`,
      });
    },

    handleAccept(item) {
      uni.navigateTo({
        url: `/pages/pda/work_order_handover/detail/detail?id=${item.id}&status=${item.status}&mode=accept`,
      });
    },

    handleDelete(item) {
      uni.showModal({
        title: "提示",
        content: "确定删除该交接单？",
        success: async (res) => {
          if (res.confirm) {
            try {
              await deleteHandover([item.id]);
              uni.showToast({ title: "删除成功", icon: "success" });
              this.refreshList();
            } catch (e) {
              uni.showToast({
                title: (e && e.message) || "删除失败",
                icon: "none",
              });
            }
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f6f7;
  overflow: hidden;
}

/* 搜索栏 */
.search-wrapper {
  padding: 16rpx 24rpx;
  background-color: #fff;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.search-input-box {
  flex: 1;
  display: flex;
  align-items: center;
  height: 72rpx;
  background-color: #f5f6f7;
  border-radius: 36rpx;
  padding: 0 24rpx;
  gap: 12rpx;
}

.search-input {
  flex: 1;
  height: 72rpx;
  font-size: 28rpx;
  color: #333;
}

.search-placeholder {
  color: #c0c0c0;
  font-size: 26rpx;
}

.search-actions {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  gap: 12rpx;
}

.filter-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f6f7;
  border-radius: 50%;

  &:active {
    opacity: 0.7;
  }
}

.search-btn {
  height: 64rpx;
  padding: 0 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #157a2c;
  border-radius: 32rpx;

  &:active {
    opacity: 0.85;
  }
}

.search-btn-text {
  color: #fff;
  font-size: 26rpx;
  white-space: nowrap;
}

/* Tab栏 */
.tab-bar {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 0 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  flex-shrink: 0;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0 16rpx;
  position: relative;
}

.tab-text {
  font-size: 26rpx;
  color: #666;
}

.tab-item--active .tab-text {
  color: #157a2c;
  font-weight: 600;
}

.tab-line {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 48rpx;
  height: 4rpx;
  background: #157a2c;
  border-radius: 2rpx;
}

/* 列表容器 */
.list-container {
  overflow: hidden;

  /deep/ .u-list {
    height: 100% !important;
  }
}

/* 工单卡片 */
.order-card {
  margin: 20rpx 24rpx 0;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

/* 卡片头部 */
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 24rpx 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.serial-num {
  width: 40rpx;
  height: 40rpx;
  line-height: 40rpx;
  border-radius: 50%;
  background: #157a2c;
  color: #fff;
  text-align: center;
  font-size: 24rpx;
  flex-shrink: 0;
}

.order-code {
  margin-left: 16rpx;
  font-size: 32rpx;
  font-weight: 500;
  color: #157a2c;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-tag {
  flex-shrink: 0;
  margin-left: 16rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;

  &--0 {
    background: #fff7e6;
    .status-text {
      color: #fa8c16;
    }
  }
  &--1 {
    background: #e6f7ff;
    .status-text {
      color: #1890ff;
    }
  }
  &--2 {
    background: #f6ffed;
    .status-text {
      color: #52c41a;
    }
  }
  &--3 {
    background: #fff1f0;
    .status-text {
      color: #f5222d;
    }
  }
}

.status-text {
  font-size: 26rpx;
}

/* 卡片内容 */
.card-body {
  padding: 16rpx 24rpx;
}

.info-row {
  display: flex;
  margin-bottom: 8rpx;
}

.info-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 8rpx 0;
  min-width: 0;
}

.info-label {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 4rpx;
  line-height: 1.4;
}

.info-value {
  font-size: 30rpx;
  color: #333;
  word-break: break-all;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  &.highlight {
    color: #157a2c;
    font-weight: 600;
  }
}

/* 卡片底部操作 */
.card-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 16rpx 24rpx;
  border-top: 1rpx solid #f0f0f0;
  gap: 16rpx;
}

.action-btn {
  padding: 12rpx 36rpx;
  border-radius: 32rpx;
  font-size: 28rpx;
  line-height: 1.4;

  &--primary {
    background: #157a2c;
    color: #fff;

    &:active {
      opacity: 0.85;
    }
  }

  &--danger {
    background: #fff;
    color: #f5222d;
    border: 1rpx solid #f5222d;

    &:active {
      opacity: 0.85;
    }
  }
}

/* 加载状态 */
.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0 40rpx;
  gap: 10rpx;
}

.loading-text {
  font-size: 24rpx;
  color: #999;
}

.empty-state {
  margin-top: 20vh;
}

/* 筛选弹窗 */
.filter-popup {
  padding: 32rpx 32rpx 48rpx;
  padding-top: calc(var(--status-bar-height, 44px) + 88rpx + 32rpx);
  background: #fff;
}

.filter-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 32rpx;
}

.filter-form {
  margin-bottom: 40rpx;
}

.filter-item {
  margin-bottom: 24rpx;
}

.filter-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 16rpx;
  display: block;
}

.filter-select {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.select-tag {
  padding: 12rpx 32rpx;
  border-radius: 32rpx;
  font-size: 26rpx;
  color: #666;
  background: #f5f6f7;

  &--active {
    color: #157a2c;
    background: rgba(21, 122, 44, 0.1);
    border: 1rpx solid #157a2c;
  }

  &:active {
    opacity: 0.85;
  }
}

.filter-actions {
  display: flex;
  gap: 24rpx;
}

.filter-btn-reset {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  color: #666;
  background: #f5f6f7;

  &:active {
    opacity: 0.85;
  }
}

.filter-btn-confirm {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  color: #fff;
  background: #157a2c;

  &:active {
    opacity: 0.85;
  }
}
</style>
