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

      <button class="search_btn" @click="handleAdd">新增</button>
    </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.beEntrustedFactoriesName }}</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-footer">
              <text class="time">{{ item.createTime }}</text>
            </view>

            <view
              class="item-actions"
              v-if="
                canEdit(item) ||
                canSubmit(item) ||
                canDelete(item) ||
                canSend(item) ||
                canReceive(item) ||
                canViewReceiveDetail(item) ||
                canViewSendDetail(item)
              "
            >
              <button
                v-if="canEdit(item)"
                class="action-btn btn-primary"
                @click.stop="handleEdit(item)"
              >
                编辑
              </button>
              <button
                v-if="canDelete(item)"
                class="action-btn btn-error"
                @click.stop="handleDelete(item)"
              >
                删除
              </button>
              <button
                v-if="canSubmit(item)"
                class="action-btn btn-success"
                @click.stop="handleSubmit(item)"
              >
                提交
              </button>
              <button
                v-if="canSend(item)"
                class="action-btn btn-warning"
                @click.stop="handleSend(item)"
              >
                发货
              </button>
              <button
                v-if="canReceive(item)"
                class="action-btn btn-success"
                @click.stop="handleReceive(item)"
              >
                收货
              </button>
              <button
                v-if="canViewReceiveDetail(item)"
                class="action-btn btn-info"
                @click.stop="handleReceiveDetail(item)"
              >
                收货详情
              </button>
              <button
                v-if="canViewSendDetail(item)"
                class="action-btn btn-order"
                @click.stop="handleSendDetail(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>
              <zxz-uni-data-select
                :localdata="typeList"
                v-model="searchForm.type"
                dataValue="value"
                dataKey="label"
                format="{label}"
              ></zxz-uni-data-select>
            </u-form-item>

            <u-form-item label="请托工厂:" borderBottom>
              <zxz-uni-data-select
                :localdata="factoryList"
                v-model="searchForm.factoriesId"
                dataValue="id"
                dataKey="name"
                format="{name}"
                filterable
              ></zxz-uni-data-select>
            </u-form-item>

            <u-form-item label="受托工厂:" borderBottom>
              <zxz-uni-data-select
                :localdata="beEntrustedFactoryList"
                v-model="searchForm.beEntrustedFactoriesId"
                dataValue="id"
                dataKey="name"
                format="{name}"
                filterable
              ></zxz-uni-data-select>
            </u-form-item>

            <u-form-item label="完成时间:" borderBottom>
              <view class="date-range-wrapper">
                <view
                  class="date-picker-box"
                  @click="showStartPicker = true"
                >
                  <text :class="{ placeholder: !startTimeDisplay }">
                    {{ startTimeDisplay || "开始日期" }}
                  </text>
                </view>
                <text class="date-separator">至</text>
                <view
                  class="date-picker-box"
                  @click="showEndPicker = true"
                >
                  <text :class="{ placeholder: !endTimeDisplay }">
                    {{ endTimeDisplay || "结束日期" }}
                  </text>
                </view>
              </view>
            </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>

    <!-- 开始日期选择器 -->
    <u-datetime-picker
      v-model="startTime"
      :show="showStartPicker"
      mode="date"
      @confirm="confirmStartTime"
      @cancel="showStartPicker = false"
    ></u-datetime-picker>

    <!-- 结束日期选择器 -->
    <u-datetime-picker
      v-model="endTime"
      :show="showEndPicker"
      mode="date"
      @confirm="confirmEndTime"
      @cancel="showEndPicker = false"
    ></u-datetime-picker>
  </view>
</template>

<script>
import { getList, submit, remove } from "@/api/entrust/index.js";
import SearchPopup from "../../components/searchPopup.vue";
import { getFactoryarea } from "@/api/inspectionWork/index";

let isEnd = false;

export default {
  components: {
    SearchPopup,
  },
  data() {
    return {
      searchForm: {
        type: "",
        name: "",
        factoriesId: "",
        beEntrustedFactoriesId: "",
        planDeliveryTimeStart: "",
        planDeliveryTimeEnd: "",
      },
      typeList: [],
      factoryList: [],
      beEntrustedFactoryList: [],
      list: [],
      pageNum: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      hasMore: true,
      showFilter: false,
      showStartPicker: false,
      showEndPicker: false,
      startTime: "",
      endTime: "",
      startTimeDisplay: "",
      endTimeDisplay: "",
    };
  },

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

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

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

    async getTypeList() {
      // 获取字典数据
      this.typeList = [
        { label: "加工", value: "1" },
        { label: "装配", value: "2" },
      ];
    },

    async getFactoryList() {
      try {
        const res = await getFactoryarea({
          pageNum: 1,
          size: 999,
          type: 1,
        });
        const list = res?.list || [];
        this.factoryList = [...list];
        this.beEntrustedFactoryList = [...list];
      } catch (error) {
        console.error("获取工厂列表失败", error);
      }
    },

    confirmStartTime(e) {
      const timestamp = e.value;
      const date = new Date(timestamp);
      this.startTime = timestamp;
      this.startTimeDisplay = this.formatDate(date);
      this.searchForm.planDeliveryTimeStart = this.formatDateTime(
        date,
        "00:00:00",
      );
      this.showStartPicker = false;
    },

    confirmEndTime(e) {
      const timestamp = e.value;
      const date = new Date(timestamp);
      this.endTime = timestamp;
      this.endTimeDisplay = this.formatDate(date);
      this.searchForm.planDeliveryTimeEnd = this.formatDateTime(
        date,
        "23:59:59",
      );
      this.showEndPicker = false;
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    formatDateTime(date, time) {
      return `${this.formatDate(date)} ${time}`;
    },

    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 res = await getList({
          pageNum: this.pageNum,
          size: this.pageSize,
          ...this.searchForm,
        });

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

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

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

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

    filterCancel() {
      this.searchForm.type = "";
      this.searchForm.factoriesId = "";
      this.searchForm.beEntrustedFactoriesId = "";
      this.searchForm.planDeliveryTimeStart = "";
      this.searchForm.planDeliveryTimeEnd = "";
      this.startTime = "";
      this.endTime = "";
      this.startTimeDisplay = "";
      this.endTimeDisplay = "";
      this.showFilter = false;
      this.loadData(true);
    },

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

    handleAdd() {
      uni.navigateTo({
        url: "/pages/pda/entrust/create/create?type=add",
      });
    },

    handleEdit(item) {
      uni.navigateTo({
        url: `/pages/pda/entrust/create/create?type=edit&id=${item.id}`,
      });
    },

    handleDelete(item) {
      uni.showModal({
        title: "提示",
        content: "确定要删除该请托单吗？",
        success: async (res) => {
          if (res.confirm) {
            try {
              await remove([item.id]);
              uni.showToast({
                title: "删除成功",
                icon: "success",
              });
              this.loadData(true);
            } catch (error) {
              uni.showToast({
                title: "删除失败",
                icon: "none",
              });
            }
          }
        },
      });
    },

    handleSubmit(item) {
      uni.showModal({
        title: "提示",
        content: "确定要提交该请托单吗？",
        success: async (res) => {
          if (res.confirm) {
            try {
              await submit({
                businessId: item.id,
                beEntrustedDeptId: item.beEntrustedDeptId,
              });
              uni.showToast({
                title: "提交成功",
                icon: "success",
              });
              this.loadData(true);
            } catch (error) {
              uni.showToast({
                title: "提交失败",
                icon: "none",
              });
            }
          }
        },
      });
    },

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

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

    canEdit(item) {
      return (
        (item.status == 0 &&
          item.approvalStatus != 1 &&
          item.approvalStatus != 2) ||
        item.approvalStatus == 3
      );
    },

    canDelete(item) {
      return (
        item.status == 0 && item.approvalStatus != 1 && item.approvalStatus != 2
      );
    },

    canSubmit(item) {
      return item.approvalStatus != 1 && item.approvalStatus != 2;
    },

    canSend(item) {
      return (
        item.approvalStatus == 2 &&
        (item.sendStatus == 0 || !item.sendStatus || item.sendStatus == 5)
      );
    },

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

    canViewReceiveDetail(item) {
      return item.approvalStatus == 2 && item.sendStatus == 4;
    },

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

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

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

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

    getStatusText(status) {
      const statusMap = {
        0: "未提交",
        1: "已提交",
        2: "已发布",
      };
      return statusMap[status] || "";
    },

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

    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";
    },
  },
};
</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: 100%;
  padding: 20rpx 26rpx;
  align-items: center;
  gap: 16rpx;
  flex-shrink: 0;
  box-sizing: border-box;

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

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

  .search_btn {
    flex-shrink: 0;
    padding: 0 26rpx;
    height: 64rpx;
    line-height: 64rpx;
    background: $theme-color;
    font-size: 26rpx;
    border-radius: 8rpx;
    color: #fff;
    white-space: nowrap;
    margin: 0;
  }

  .menu_icon {
    flex-shrink: 0;
    width: 44rpx;
    height: 44rpx;
  }

  .add_btn {
    width: 70rpx;
    height: 70rpx;
    line-height: 70rpx;
    padding: 0;
    background: $theme-color;
    font-size: 48rpx;
    color: #fff;
    border-radius: 50%;
    margin: 0;
  }
}

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

    .item-code {
      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-primary {
        background-color: #2979ff !important;
      }

      &.btn-error {
        background-color: #f56c6c !important;
      }

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

      &.btn-warning {
        background-color: #ff9900 !important;
      }

      &.btn-info {
        background-color: #e0ffff !important;
      }
      &.btn-order {
        background-color: #b23aee !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;

  .date-range-wrapper {
    display: flex;
    align-items: center;
    gap: 12rpx;

    .date-picker-box {
      flex: 1;
      padding: 12rpx 16rpx;
      border: 1rpx solid #e0e0e0;
      border-radius: 6rpx;
      font-size: 28rpx;
      color: #333;
      min-height: 56rpx;
      line-height: 32rpx;

      .placeholder {
        color: #c0c4cc;
      }
    }

    .date-separator {
      font-size: 28rpx;
      color: #666;
    }
  }
}

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