<template>
  <view class="task-list-container">
    <!-- 筛选按钮 -->
    <view class="filter-buttons">
      <button class="filter-btn" type="primary" @click="handleSelectAll">
        {{ isAllSelected ? "取消全选" : "全选" }}
      </button>
      <button class="filter-btn" type="primary" @click="confirmSelection">
        确认领取
      </button>
      <!-- <button class="filter-btn" type="primary" @click="showAreaPicker">
        筛选
      </button> -->
    </view>
    <uni-popup ref="areaPicker" type="bottom">
      <view class="picker-container">
        <view class="picker-header">
          <button class="cancel-btn" @click="cancelArea">取消</button>
          <text>选择区域</text>
          <button class="confirm-btn" @click="confirmArea">确认</button>
        </view>
        <picker-view
          class="picker-view"
          :value="pickerValue"
          @change="onPickerChange"
        >
          <!-- 省级选择 -->
          <picker-view-column>
            <view
              class="picker-item"
              v-for="(item, index) in provinceList"
              :key="index"
            >
              {{ item.name }}
            </view>
          </picker-view-column>
          <!-- 市级选择 -->
          <picker-view-column>
            <view
              class="picker-item"
              v-for="(item, index) in currentCityList"
              :key="index"
            >
              {{ item.name }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
    <!-- 任务列表 -->
    <scroll-view
      scroll-y
      @scrolltolower="loadMore"
      class="task-list"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 空数据提示 -->
      <view v-if="taskList.length === 0" class="empty-container">
        <image src="" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无任务数据</text>
      </view>

      <!-- 任务列表内容 -->
      <template v-else>
        <view
          v-for="(item, index) in taskList"
          @click="handleTaskItem(item)"
          :key="index"
          class="task-item"
        >
          <view class="warehouse-info">
            <view class="info-row">
              <uni-icons type="home" size="24" color="#1976D2"></uni-icons>
              <view class="warehouse-name">
                <view class="labeltext">库区名称:</view>
                <view class="valuetext">{{ item.kqmc }}</view>
              </view>
              <checkbox
                class="check-circle"
                :checked="item.checked"
                @click.stop="handleCheck(item)"
                style="transform: scale(0.8)"
              />
            </view>
            <view class="info-row">
              <uni-icons type="location" size="24" color="#FFA726"></uni-icons>
              <view class="warehouse-address">
                <view class="labeltext">库区地址:</view>
                <view class="valuetext">{{ item.jtdz }}</view>
              </view>
            </view>
          </view>
          <view class="divider"></view>
          <view class="task-status">
            <text>核验仓房数量: {{ item.hyNum || "-" }}</text>
            <text>核验状态: {{ statusflutter(item.hyState) }}</text>
          </view>
        </view>

        <!-- 加载更多提示 -->
        <view class="load-more" v-if="taskList.length > 0">
          <view v-if="loading" class="loading-box">
            <text class="loading-text">加载中...</text>
          </view>
          <view v-else-if="!hasMore" class="bottom-line">
            <text class="line"></text>
            <text class="text">已经到底了</text>
            <text class="line"></text>
          </view>
        </view>
      </template>
    </scroll-view>
  </view>
</template>

<script>
import { getTaskList, getTasks } from "@/api/task";

export default {
  name: "TaskList",
  data() {
    return {
      pageNo: 1,
      pageSize: 10,
      loading: false,
      hasMore: true,
      taskList: [],
      pickerValue: [0, 0], // 省市二级选择的值
      provinceList: [], // 省级列表
      cityList: {}, // 市级列表（以省份code为key）
      currentCityList: [], // 当前选中省份的市级列表
      selectedProvince: null,
      selectedCity: null,
      isAllSelected: false, // 是否全选
      selectedTasks: [], // 存储选中的任务
      isRefreshing: false, // 添加刷新状态
    };
  },
  // 页面加载
  created() {
    this.getTaskList();
    // this.getAreaList(); // 获取省市数据
  },
  methods: {
    // 核验状态(0:待查验,1:查验通过,2:查验不通过3:核验中)
    statusflutter(status) {
      if (status === 0) {
        return "待查验";
      } else if (status === 1) {
        return "查验通过";
      } else if (status === 2) {
        return "查验不通过";
      } else if (status === 3) {
        return "核验中";
      }
    },
    handleTaskItem(item) {
      uni.navigateTo({
        url: "/pages/warehouse-detail-verification/warehouseDetail",
        success: (res) => {
          res.eventChannel.emit("acceptData", {
            taskInfo: JSON.stringify(item),
          });

          // 刷新列表
          res.eventChannel.on("refreshList", (data) => {
            if (data.refresh) {
              // 调用刷新方法，比如重新获取列表数据
              console.log("刷新");
            }
          });
        },
      });
    },
    // 获取任务列表
    async getTaskList() {
      if ((this.loading && !this.isRefreshing) || !this.hasMore) return;

      try {
        this.loading = true;
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          provinceCode: this.selectedProvince?.code,
          cityCode: this.selectedCity?.code,
          listType: 1, // 根据实际需求设置
        };

        const res = await getTaskList(params);

        if (res.code === 0) {
          let list = res.data.records;

          if (list.length === 0) {
          } else {
            list = res.data.records.map((item) => ({
              ...item,
              checked: false, // 添加checked属性
            }));
          }

          // 如果是第一页，直接替换列表
          if (this.pageNo === 1) {
            this.taskList = list;
            this.isAllSelected = false; // 重置全选状态
          } else {
            // 否则追加到现有列表
            this.taskList = [...this.taskList, ...list];
          }

          // 判断是否还有更多数据
          this.hasMore = list.length >= this.pageSize;

          // 如果还有更多数据，页码加1
          if (this.hasMore) {
            this.pageNo++;
          }
        } else {
          uni.showToast({
            title: res.msg || "获取任务列表失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("获取任务列表失败：", error);
        uni.showToast({
          title: "获取任务列表失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },
    // 上拉加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.getTaskList();
      }
    },
    // 重置列表（用于筛选后重新加载）
    resetList() {
      this.pageNo = 1;
      this.hasMore = true;
      this.taskList = [];
      this.getTaskList();
    },
    // 获取省市数据
    async getAreaList() {
      try {
        uni.showLoading({ title: "加载中" });
        const res = await uni.request({
          url: "your-api-url/area/list",
          method: "GET",
        });

        if (res.data) {
          this.provinceList = res.data.provinceList;
          this.cityList = res.data.cityList;
          // 初始化第一个省份的城市列表
          if (this.provinceList.length > 0) {
            this.currentCityList =
              this.cityList[this.provinceList[0].code] || [];
          }
        }
      } catch (error) {
        uni.showToast({
          title: "获取地区数据失败",
          icon: "error",
        });
      } finally {
        uni.hideLoading();
      }
    },
    // 显示区域选择器
    showAreaPicker() {
      this.$refs.areaPicker.open();
    },
    // 取消选择
    cancelArea() {
      this.$refs.areaPicker.close();
      // 重置选择值
      this.pickerValue = [0, 0];
      this.updateCurrentSelection();
    },

    // 选择器值改变
    onPickerChange(e) {
      const values = e.detail.value;

      // 如果省份改变，需要更新市级列表
      if (values[0] !== this.pickerValue[0]) {
        const selectedProvince = this.provinceList[values[0]];
        this.currentCityList = this.cityList[selectedProvince.code] || [];
        values[1] = 0; // 省份改变时，市重置为第一个
      }

      this.pickerValue = values;
      this.updateCurrentSelection();
    },

    // 更新当前选择的省市
    updateCurrentSelection() {
      this.selectedProvince = this.provinceList[this.pickerValue[0]];
      this.selectedCity = this.currentCityList[this.pickerValue[1]];
    },

    // 确认选择区域
    async confirmArea() {
      if (!this.selectedProvince || !this.selectedCity) {
        uni.showToast({
          title: "请选择省市",
          icon: "none",
        });
        return;
      }

      this.$refs.areaPicker.close();
      // 重置列表并重新加载
      this.resetList();
    },
    // 处理全选/取消全选
    handleSelectAll() {
      this.isAllSelected = !this.isAllSelected;
      this.taskList = this.taskList.map((item) => ({
        ...item,
        checked: this.isAllSelected,
      }));
    },

    // 处理单个选择
    handleCheck(item) {
      item.checked = !item.checked;
      // 检查是否全部选中
      this.isAllSelected = this.taskList.every((item) => item.checked);
    },

    // 确认选择
    confirmSelection() {
      // 收集选中的任务
      this.selectedTasks = this.taskList.filter((item) => item.checked);

      if (this.selectedTasks.length === 0) {
        uni.showToast({
          title: "请至少选择一个任务",
          icon: "none",
        });
        return;
      }

      // 处理选中的任务，比如发送到后端
      this.submitSelectedTasks();
    },

    // 提交选中的任务
    async submitSelectedTasks() {
      try {
        // 已选择的任务数组ID
        let kqIds = this.selectedTasks.map((item) => item.kqId);

        const res = await getTasks({ kqIds, listType: 1, hyState: 3 });

        if (res.code === 0) {
          uni.showToast({
            title: "任务领取成功",
            icon: "success",
          });
          // 处理成功后的逻辑，比如刷新列表
          this.resetList();
        } else {
          uni.showToast({
            title: res.msg || "领取失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.showToast({
          title: "提交领取失败",
          icon: "none",
        });
      }
    },

    // 添加下拉刷新处理方法
    async onRefresh() {
      this.isRefreshing = true;
      try {
        // 重置页码和列表状态
        this.pageNo = 1;
        this.hasMore = true;
        // 重新获取数据
        await this.getTaskList();
      } catch (error) {
        uni.showToast({
          title: "刷新失败",
          icon: "none",
        });
      } finally {
        this.isRefreshing = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.task-list-container {
  height: calc(100vh - 100rpx);
}

.filter-buttons {
  display: flex;
  padding: 20rpx;
  gap: 20rpx;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: rgba(255, 255, 255, 0);
  z-index: 99;
  box-sizing: border-box;

  .filter-btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #1976d2;
  }
}

.task-list {
  flex: 1;
  padding: 0 20rpx;
  box-sizing: border-box;
  padding-top: 120rpx;
  background: linear-gradient(#cfddfc 0%, #e6eeff 10%, #fff 100%);
  height: calc(100%);
}

.task-item {
  background: linear-gradient(#fff 0%, #fff 80%, #f4f6fb 100%);
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 10rpx 10rpx rgba(0, 0, 0, 0.1);
}

.warehouse-info {
  .info-row {
    display: flex;
    align-items: start;
    margin-bottom: 20rpx;

    view {
      margin-left: 10rpx;
      font-size: 35rpx;
    }

    .warehouse-name,
    .warehouse-address {
      display: flex;
      width: 80%;
      // flex: 1;
    }

    .labeltext {
      // 文字禁止换行
      white-space: nowrap;
    }

    .valuetext {
      text-align: left;
    }
  }
}

.task-status {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
  color: #666;
  font-size: 28rpx;
}

.check-circle {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  margin-left: auto;

  &.checked {
    background-color: #1976d2;
    border-color: #1976d2;
  }
}

.picker-container {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);

  .picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #eee;

    text {
      font-size: 32rpx;
      color: #333;
    }

    .cancel-btn,
    .confirm-btn {
      margin: 0;
      padding: 10rpx 30rpx;
      font-size: 28rpx;
      border-radius: 8rpx;
    }

    .cancel-btn {
      background-color: #f5f5f5;
      color: #666;
    }

    .confirm-btn {
      background-color: #1976d2;
      color: #fff;
    }
  }

  .picker-view {
    width: 100%;
    height: 400rpx;

    .picker-item {
      line-height: 80rpx;
      text-align: center;
    }
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }

  .empty-text {
    color: #666;
    font-size: 28rpx;
  }
}

.load-more {
  padding: 20rpx 30rpx 40rpx;

  .loading-box {
    text-align: center;

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

  .bottom-line {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 30rpx;

    .line {
      flex: 1;
      height: 1rpx;
      background: #ddd;
    }

    .text {
      color: #999;
      font-size: 24rpx;
      padding: 0 30rpx;
    }
  }
}

.divider {
  height: 1rpx; /* 分割线的高度 */
  background-color: rgba(117, 117, 117, 0.1); /* 分割线的颜色 */
  margin: 10rpx 0; /* 分割线的上下间距 */
  width: 100%; /* 分割线的宽度 */
}
</style>
