<template>
  <view class="content-box">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="选择工单"
      background-color="#157A2C"
      color="#fff"
      @clickLeft="back"
    ></uni-nav-bar>

    <view class="top-wrapper">
      <uni-section>
        <uni-easyinput
          prefixIcon="search"
          v-model="searchForm.code"
          placeholder="生产工单号"
        ></uni-easyinput>
      </uni-section>
      <image
        class="menu_icon"
        src="~@/static/pda/menu.svg"
        @click="showFilter = true"
      ></image>
      <button class="search_btn" @click="handleSearch">搜索</button>
    </view>

    <scroll-view scroll-y class="list_box">
      <u-list @scrolltolower="loadMore">
        <u-list-item v-for="item in orderList" :key="item.id">
          <view class="order-item" :class="{ selected: isSelected(item) }">
            <view class="order-checkbox">
              <checkbox
                :checked="isSelected(item)"
                @click.stop="toggleSelect(item)"
                color="#157A2C"
              />
            </view>
            <view class="order-content" @click="toggleSelect(item)">
              <view class="order-header">
                <text class="order-code">{{ item.code }}</text>
              </view>

              <view class="order-row">
                <text class="label">计划编号:</text>
                <text class="value">{{ item.productionPlanCode }}</text>
              </view>

              <view class="order-row">
                <text class="label">产品名称:</text>
                <text class="value">{{ item.productName }}</text>
              </view>

              <view class="order-row">
                <text class="label">产品编码:</text>
                <text class="value">{{ item.productCode }}</text>
              </view>

              <view class="order-row">
                <text class="label">牌号:</text>
                <text class="value">{{ item.brandNo }}</text>
              </view>

              <view class="order-row">
                <text class="label">批次号:</text>
                <text class="value">{{ item.batchNo }}</text>
              </view>

              <view class="order-row">
                <text class="label">规格:</text>
                <text class="value">{{ item.specification }}</text>
              </view>

              <view class="order-row">
                <text class="label">型号:</text>
                <text class="value">{{ item.model }}</text>
              </view>

              <view class="order-row">
                <text class="label">要求生产数量:</text>
                <text class="value">{{ item.formingNum }}{{ item.unit }}</text>
              </view>

              <view class="order-row">
                <text class="label">计划开始时间:</text>
                <text class="value">{{ item.planStartTime }}</text>
              </view>
            </view>
          </view>
        </u-list-item>

        <u-list-item v-if="orderList.length === 0">
          <view class="empty-wrapper">
            <u-empty iconSize="150" textSize="32" text="暂无工单数据"></u-empty>
          </view>
        </u-list-item>

        <u-list-item>
          <view style="height: 120rpx"></view>
        </u-list-item>
      </u-list>
    </scroll-view>

    <view class="footer-btns">
      <view class="footer-left">
        <checkbox
          :checked="isAllSelected"
          @click="toggleSelectAll"
          color="#157A2C"
        />
        <text class="select-all-text">全选</text>
      </view>
      <view class="footer-right">
        <u-button class="btn-cancel" @click="handleCancel">取消</u-button>
        <u-button type="success" class="btn-confirm" @click="handleConfirm"
          >确定({{ selectedList.length }})</u-button
        >
      </view>
    </view>

    <SearchPopup mode="top" v-if="showFilter">
      <template v-slot:list>
        <view class="search_list">
          <u-form
            labelPosition="left"
            :model="searchForm"
            labelWidth="180"
            labelAlign="left"
          >
            <u-form-item label="产品名称:" borderBottom>
              <input
                v-model="searchForm.productName"
                placeholder="请输入产品名称"
                class="order-input"
              />
            </u-form-item>
          </u-form>
        </view>
      </template>

      <template v-slot:operate>
        <view class="operate_box">
          <u-button
            size="small"
            class="u-reset-button reset-btn"
            @click="filterCancel"
            >重置</u-button
          >
          <u-button
            type="success"
            size="small"
            class="u-reset-button confirm-btn"
            @click="filterConfirm"
            >确定</u-button
          >
        </view>
      </template>
    </SearchPopup>
  </view>
</template>

<script>
import { produceOrder } from "@/api/entrust/index";
import SearchPopup from "../../components/searchPopup.vue";

let isEnd = false;

export default {
  components: {
    SearchPopup,
  },
  data() {
    return {
      searchForm: {
        code: "",
        productName: "",
        statusList: ["4", "5"],
      },
      orderList: [],
      selectedList: [],
      preSelectedIds: [],
      pageNum: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      hasMore: true,
      showFilter: false,
    };
  },

  computed: {
    isAllSelected() {
      return (
        this.orderList.length > 0 &&
        this.selectedList.length === this.orderList.length
      );
    },
  },

  onLoad(options) {
    if (options.selectedIds) {
      this.preSelectedIds = options.selectedIds.split(",");
    }
    this.loadData();
  },

  methods: {
    async loadData(isRefresh = false) {
      if (this.loading) return;

      if (isRefresh) {
        this.pageNum = 1;
        this.orderList = [];
        this.hasMore = true;
      }

      if (!this.hasMore) return;

      this.loading = true;
      isEnd = false;

      try {
        const res = await produceOrder({
          pageNum: this.pageNum,
          size: this.pageSize,
          ...this.searchForm,
        });

        if (this.pageNum === 1) {
          this.orderList = [];
        }

        if (res.list && res.list.length > 0) {
          this.orderList.push(...res.list);
          this.total = res.total;
          isEnd = this.orderList.length >= this.total;
          this.hasMore = !isEnd;

          // Auto-select pre-selected items
          if (this.preSelectedIds.length > 0) {
            this.orderList.forEach((item) => {
              if (
                this.preSelectedIds.includes(String(item.id)) &&
                !this.isSelected(item)
              ) {
                this.selectedList.push(item);
              }
            });
          }
        } else {
          isEnd = true;
          this.hasMore = false;
        }
      } catch (error) {
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    loadMore() {
      if (isEnd) return;
      this.pageNum++;
      this.loadData();
    },

    handleSearch() {
      this.loadData(true);
    },

    filterConfirm() {
      this.showFilter = false;
      this.loadData(true);
    },

    filterCancel() {
      this.searchForm.productName = "";
      this.showFilter = false;
      this.loadData(true);
    },

    isSelected(item) {
      return this.selectedList.some((selected) => selected.id === item.id);
    },

    toggleSelect(item) {
      const index = this.selectedList.findIndex(
        (selected) => selected.id === item.id,
      );
      if (index > -1) {
        this.selectedList.splice(index, 1);
      } else {
        this.selectedList.push(item);
      }
    },

    toggleSelectAll() {
      if (this.isAllSelected) {
        this.selectedList = [];
      } else {
        this.selectedList = [...this.orderList];
      }
    },

    handleCancel() {
      uni.navigateBack();
    },

    handleConfirm() {
      if (this.selectedList.length === 0) {
        uni.showToast({
          title: "请选择工单",
          icon: "none",
        });
        return;
      }

      // 通过事件总线或页面栈传递数据
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage) {
        prevPage.$vm.receiveOrder(this.selectedList);
      }

      uni.navigateBack();
    },
  },
};
</script>

<style lang="scss" scoped>
.content-box {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $page-bg;
}

.top-wrapper {
  background-color: #fff;
  display: flex;
  width: 750rpx;
  padding: 16rpx 32rpx;
  align-items: center;
  gap: 16rpx;
  flex-shrink: 0;

  /deep/.uni-section {
    margin-top: 0px;
  }

  /deep/.uni-section-header {
    padding: 0px;
  }

  .search_btn {
    width: 120rpx;
    height: 70rpx;
    line-height: 70rpx;
    padding: 0 24rpx;
    background: $theme-color;
    font-size: 32rpx;
    color: #fff;
    margin: 0;
  }

  .menu_icon {
    width: 44rpx;
    height: 44rpx;
  }
}

.list_box {
  flex: 1;
  height: 0;

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

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin: 16rpx 24rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  border: 2rpx solid transparent;
  transition: all 0.3s;
  display: flex;
  gap: 16rpx;

  &.selected {
    border-color: $theme-color;
    background-color: rgba(21, 122, 44, 0.06);
  }

  .order-checkbox {
    display: flex;
    align-items: flex-start;
    padding-top: 4rpx;
  }

  .order-content {
    flex: 1;
  }

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .order-code {
      font-size: 32rpx;
      font-weight: bold;
      color: $theme-color;
    }
  }

  .order-row {
    display: flex;
    margin-bottom: 16rpx;
    font-size: 28rpx;

    .label {
      color: #999;
      min-width: 220rpx;
    }

    .value {
      flex: 1;
      color: #333;
      word-break: break-all;
    }
  }
}

.empty-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 25vh;
}

.footer-btns {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx 32rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.08);
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;

  .footer-left {
    display: flex;
    align-items: center;
    gap: 12rpx;

    .select-all-text {
      font-size: 28rpx;
      color: #333;
    }
  }

  .footer-right {
    display: flex;
    gap: 20rpx;
  }

  /deep/ .u-button {
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 30rpx;
    min-width: 160rpx;
    white-space: nowrap;
  }

  .btn-cancel {
    background-color: #fff;
    color: #666;
    border: 1rpx solid #e0e0e0;
  }
}

.search_list {
  min-height: 100rpx;
  padding: 24rpx 32rpx;

  .form-input {
    padding: 12rpx 16rpx;
    border: 1rpx solid #e0e0e0;
    border-radius: 6rpx;
    font-size: 28rpx;
  }
}

.operate_box {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx 32rpx;
  gap: 24rpx;

  .reset-btn {
    flex: 1;
    height: 72rpx;
    border-radius: 36rpx;
    font-size: $uni-font-size-sm;
  }

  .confirm-btn {
    flex: 1;
    height: 72rpx;
    border-radius: 36rpx;
    font-size: $uni-font-size-sm;
  }
}

.order-input {
  flex: 1;
  padding: 20rpx 16rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  min-height: 80rpx;
  background-color: #fff;
}
</style>
