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

    <view class="tab-bar">
      <view
        class="tab-item"
        :class="{ active: tabValue === '1' }"
        @click="handleTabClick('1')"
      >
        受托任务
      </view>
      <view
        class="tab-item"
        :class="{ active: tabValue === '2' }"
        @click="handleTabClick('2')"
      >
        预处理任务
      </view>
    </view>

    <view class="list_box">
      <u-list @scrolltolower="loadMore">
        <u-list-item v-for="item in list" :key="item.id">
          <view class="list-item" @click="goDetail(item)">
            <view class="item-header">
              <view class="item-code">{{ item.code }}</view>
              <view class="item-status">
                <text class="status-tag" :class="getStatusClass(item.status)">{{
                  getStatusText(item.status)
                }}</text>
              </view>
            </view>

            <view class="item-row">
              <text class="label">类型:</text>
              <text class="value">{{ getTypeText(item.type) }}</text>
            </view>

            <view class="item-row">
              <text class="label">名称:</text>
              <text class="value">{{ item.name }}</text>
            </view>

            <view class="item-row">
              <text class="label">紧急程度:</text>
              <text class="value">{{
                item.priority == 1 ? "一般" : "紧急"
              }}</text>
            </view>

            <view class="item-row">
              <text class="label">请托数量:</text>
              <text class="value"
                >{{ item.totalCount }}{{ item.measuringUnit }}</text
              >
            </view>

            <view class="item-row">
              <text class="label">接收数量:</text>
              <text class="value"
                >{{ item.receiveQuantity || 0 }}{{ item.measuringUnit }}</text
              >
            </view>

            <view class="item-row">
              <text class="label">请托工厂:</text>
              <text class="value">{{ item.applyFactoriesName }}</text>
            </view>

            <view class="item-row">
              <text class="label">收货状态:</text>
              <text class="value">
                <text
                  class="status-tag"
                  :class="getSendStatusClass(item.sendStatus)"
                  >{{ getSendStatusText(item.sendStatus) }}</text
                >
              </text>
            </view>

            <view class="item-row">
              <text class="label">审批状态:</text>
              <text class="value">
                <text
                  class="status-tag"
                  :class="getApprovalStatusClass(item.approvalStatus)"
                  >{{ getApprovalStatusText(item.approvalStatus) }}</text
                >
              </text>
            </view>

            <view class="item-row">
              <text class="label">转换状态:</text>
              <text class="value">
                <text
                  class="status-tag"
                  :class="getChangeTypeClass(item.changeType)"
                  >{{ getChangeTypeText(item.changeType) }}</text
                >
              </text>
            </view>

            <view class="item-footer">
              <text class="time">{{ item.createTime }}</text>
            </view>

            <view
              class="item-actions"
              v-if="
                canReceive(item) ||
                canViewReceiveDetail(item) ||
                canViewSendDetail(item) ||
                canViewReceiveOrder(item)
              "
            >
              <button
                v-if="canReceive(item)"
                class="action-btn btn-success"
                @click.stop="handleReceive(item)"
              >
                收货
              </button>
              <button
                v-if="canViewSendDetail(item)"
                class="action-btn btn-order"
                @click.stop="handleSendDetail(item)"
              >
                发货详情
              </button>
              <button
                v-if="canViewReceiveDetail(item)"
                class="action-btn btn-info"
                @click.stop="handleReceiveDetail(item)"
              >
                收货详情
              </button>
              <button
                v-if="canViewReceiveOrder(item)"
                class="action-btn btn-primary"
                @click.stop="handleConvertOrder(item)"
              >
                转生产订单
              </button>
            </view>
          </view>
        </u-list-item>

        <u-list-item v-if="list.length === 0">
          <view class="empty-wrapper">
            <u-empty iconSize="150" textSize="32" text="暂无数据"></u-empty>
          </view>
        </u-list-item>
      </u-list>
    </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>
              <picker
                mode="selector"
                :range="typeList"
                range-key="label"
                @change="typeChange"
              >
                <view class="picker-value">{{ currentType || "全部" }}</view>
              </picker>
            </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 { getList } from "@/api/beEntrust/index.js";
import SearchPopup from "../../components/searchPopup.vue";

let isEnd = false;

export default {
  components: {
    SearchPopup,
  },
  data() {
    return {
      searchForm: {
        type: "",
        name: "",
        applyFactoriesId: "",
      },
      currentType: "",
      typeList: [],
      list: [],
      pageNum: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      hasMore: true,
      showFilter: false,
      tabValue: "1",
    };
  },

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

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

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

    async getTypeList() {
      this.typeList = [
        { label: "全部", value: "" },
        { label: "加工", value: "1" },
        { label: "装配", value: "2" },
      ];
    },

    typeChange(e) {
      const index = e.detail.value;
      this.searchForm.type = this.typeList[index].value;
      this.currentType = this.typeList[index].label;
    },

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

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

      if (!this.hasMore) return;

      this.loading = true;
      isEnd = false;

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

        if (this.tabValue === "2") {
          params.preStatus = 1;
        }

        const res = await getList(params);

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

        if (res.list && res.list.length > 0) {
          this.list.push(...res.list);
          this.total = res.total;
          isEnd = this.list.length >= this.total;
          this.hasMore = !isEnd;
        } else {
          isEnd = true;
          this.hasMore = false;
        }
      } catch (error) {
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    handleTabClick(tab) {
      this.tabValue = tab;
      this.loadData(true);
    },

    handleConvertOrder(item) {
      if (item.sendStatus != 2) {
        uni.showToast({
          title: "请先收货再转生产订单",
          icon: "none",
        });
        return;
      }

      if (item.changeType == 1 || item.changeType == 2) {
        uni.showToast({
          title: "该工单已转换，不能重复转换",
          icon: "none",
        });
        return;
      }

      uni.navigateTo({
        url: `/pages/pda/beEntrust/createOrder/createOrder?id=${item.id}`,
      });
    },

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

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

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

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

    goDetail(item) {
      uni.navigateTo({
        url: `/pages/pda/beEntrust/detail/detail?id=${item.id}`,
      });
    },

    handleReceive(item) {
      uni.navigateTo({
        url: `/pages/pda/beEntrust/goods/goods?id=${item.id}&type=add`,
      });
    },

    handleReceiveDetail(item) {
      uni.navigateTo({
        url: `/pages/pda/beEntrust/goods/goods?id=${item.id}&type=detail`,
      });
    },

    handleSendDetail(item) {
      uni.navigateTo({
        url: `/pages/pda/beEntrust/goods/goods?id=${item.id}&type=send`,
      });
    },

    canReceive(item) {
      return item.approvalStatus == 2 && item.sendStatus == 1;
    },

    canViewReceiveDetail(item) {
      return (
        item.approvalStatus == 2 && item.sendStatus != 1 && item.sendStatus != 5
      );
    },

    canViewReceiveOrder(item) {
      console.log("canViewReceiveOrder", item.changeType);
      return (
        item.approvalStatus == 2 &&
        item.sendStatus == 2 &&
        item.sendStatus != 5 &&
        item.changeType != 1 &&
        item.changeType != 2
      );
    },

    canViewSendDetail(item) {
      return (
        item.approvalStatus == 2 &&
        (item.sendStatus == 3 || item.sendStatus == 4)
      );
    },

    getTypeText(type) {
      const typeMap = {
        1: "加工",
        2: "装配",
      };
      return typeMap[type] || "";
    },

    getStatusText(status) {
      const statusMap = {
        0: "未提交",
        1: "已提交",
        2: "已发布",
        4: "待生产",
        5: "生产中",
        6: "已完成",
        7: "已延期",
        8: "待下达",
      };
      return statusMap[status] || "";
    },

    getStatusClass(status) {
      if (!status || status == 0) return "status-default";
      return "status-success";
    },

    getSendStatusText(sendStatus) {
      const statusMap = {
        0: "未收货",
        1: "已发货",
        2: "已收货",
        3: "受托已发",
        4: "请托已收",
        5: "受托拒收",
        6: "请托拒收",
      };
      return statusMap[sendStatus] || "未收货";
    },

    getSendStatusClass(sendStatus) {
      if (!sendStatus || sendStatus == 0) return "status-default";
      if (sendStatus == 5 || sendStatus == 6) return "status-danger";
      return "status-success";
    },

    getApprovalStatusText(approvalStatus) {
      const statusMap = {
        0: "未提交",
        1: "审核中",
        2: "审核通过",
        3: "审核不通过",
      };
      return statusMap[approvalStatus] || "未提交";
    },

    getApprovalStatusClass(approvalStatus) {
      const classMap = {
        0: "status-default",
        1: "status-warning",
        2: "status-success",
        3: "status-danger",
      };
      return classMap[approvalStatus] || "status-default";
    },

    getChangeTypeText(changeType) {
      const typeMap = {
        0: "未转换",
        1: "已转生产订单",
        2: "已转生产订单",
      };
      return typeMap[changeType] || "未转换";
    },

    getChangeTypeClass(changeType) {
      if (changeType == 1 || changeType == 2) return "status-success";
      return "status-default";
    },
  },
};
</script>

<style lang="scss">
page {
  height: 100vh;
  overflow: hidden;
}
</style>

<style lang="scss" scoped>
.content-box {
  height: 100vh;
  overflow: hidden;
  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;
  position: sticky;
  top: 88rpx;
  z-index: 99;

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

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

.action-bar {
  background-color: #fff;
  padding: 16rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .action-btn {
    width: 200rpx;
    height: 64rpx;
    line-height: 64rpx;
    padding: 0;
    background: $theme-color;
    font-size: 28rpx;
    color: #fff;
    border-radius: 8rpx;
    margin: 0;
  }
}

.tab-bar {
  display: flex;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;

    &.active {
      color: $theme-color;
      font-weight: bold;

      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 4rpx;
        background-color: $theme-color;
        border-radius: 2rpx;
      }
    }
  }
}

.list_box {
  flex: 1;
  overflow: hidden;
  padding: 16rpx 0;

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

.list-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin: 0 24rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);

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

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

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

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

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

  .item-footer {
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1rpx solid #f0f0f0;

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

  .item-actions {
    display: flex !important;
    justify-content: flex-end !important;
    gap: 12rpx;
    margin-top: 20rpx;
    overflow-x: auto;

    .action-btn {
      flex: 0 0 auto !important;
      width: auto !important;
      border-radius: 32rpx !important;
      height: 56rpx !important;
      line-height: 56rpx !important;
      font-size: 26rpx !important;
      padding: 0 24rpx !important;
      margin: 0 !important;
      border: none !important;
      color: #fff !important;

      &.btn-success {
        background-color: $theme-color !important;
      }

      &.btn-info {
        background-color: #ff8c00 !important;
      }

      &.btn-order {
        background-color: #b23aee !important;
      }

      &.btn-primary {
        background-color: #1a52c3 !important;
      }
    }
  }
}

.status-tag {
  display: inline-block;
  padding: 4rpx 16rpx;
  border-radius: 4rpx;
  font-size: 24rpx;

  &.status-default {
    background-color: #f0f0f0;
    color: #666;
  }

  &.status-warning {
    background-color: #fff7e6;
    color: #faad14;
  }

  &.status-success {
    background-color: rgba(21, 122, 44, 0.1);
    color: $theme-color;
  }

  &.status-danger {
    background-color: #fff1f0;
    color: #ff4d4f;
  }
}

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

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

  .picker-value {
    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;
  }
}
</style>
