<template>
  <view class="inventory-detail">
    <!-- 导航栏 -->
    <u-navbar
      :title="inventoryInfo.taskName"
      :autoBack="true"
      fixed
      safe-area-inset-top
      placeholder
    >
      <template #right>
        <view class="nav-right">
          <u-icon name="search" size="20" color="#333"></u-icon>
        </view>
      </template>
    </u-navbar>

    <u-sticky bgColor="#F5F6F7" :offsetTop="offsetTop">
      <!-- 基本信息 吸顶 -->
      <view class="search-box">
        <u-search
          placeholder="输入货物名称/库位/条码/内部编码"
          shape="square"
          :showAction="false"
          @search="onRefresh"
          @clear="onRefresh"
          v-model="queryFilterValues.number"
        ></u-search>
        <view class="scan-icon flex_box flex_row_center" @click="scanCode">
          <image src="@/static/image/scan-icon-2.png" mode=""></image>
        </view>
      </view>
      <view class="info-card">
        <view class="info-item page-title">
          {{ inventoryInfo.taskName }}
        </view>
        <view class="info-item-box">
          <view class="info-item">
            <text class="info-label">盘点单号：</text>
            <text class="info-value">{{ inventoryInfo.number }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">盘点人：</text>
            <text class="info-value">{{
              inventoryInfo.creatorName || "-"
            }}</text>
          </view>
        </view>

        <view class="progress-box">
          <view class="progress-label-box">
            <text class="progress-label"> 盘点进度 </text>
            <text class="progress-value"
              ><text class="finished-value">{{
                inventoryInfo.finishCount
              }}</text
              >/{{ inventoryInfo.materialCount }}</text
            >
          </view>
          <view class="progress-bar-wrap">
            <u-line-progress
              :percentage="getProgressPercentage"
              height="6"
              :show-text="false"
              activeColor="#4080FF"
            >
            </u-line-progress>
          </view>
        </view>
      </view>
      <!-- 筛选按钮 -->
      <view class="filter-wrap">
        <view class="filter-btn" @click="filterPopupVisible = true">
          <text>筛选</text>
          <image
            src="@/static/image/saixuan-icon.png"
            mode=""
            class="icon"
          ></image>
        </view>
      </view>
    </u-sticky>

    <!-- 商品列表 -->
    <view class="goods-list">
      <view class="goods-item" v-for="(item, index) in goodsList" :key="index">
        <view class="location-row">
          <view class="location-left">
            <text class="location-label">库位：</text>
            <text class="location-value">{{ item.position || "-" }}</text>
            <image
              v-if="item.status != 3"
              src="@/static/image/bianji-icon.png"
              mode=""
              class="icon"
              @click="handlePositionEdit(item)"
            ></image>
          </view>
          <text class="category-text">{{ item.categoryName }}</text>
        </view>

        <view class="goods-content">
          <image
            class="goods-image"
            :src="item.imgNameArr[0] || ''"
            mode="aspectFill"
          ></image>
          <view class="goods-info">
            <text class="goods-name u-line-2">{{ item.materialName }}</text>
            <view class="goods-field half-w">
              <text class="field-label">规格：</text>
              <text class="field-value">{{ item.standard }}</text>
            </view>
            <view class="goods-field half-w">
              <text class="field-label">盘点人：</text>
              <text class="field-value">{{ item.createName || "-" }}</text>
            </view>
            <view class="goods-field">
              <text class="field-label">盘点时间：</text>
              <text class="field-value">{{
                item.operTime ? $u.timeFormat(item.operTime, "yyyy-mm-dd") : "-"
              }}</text>
            </view>
            <view class="stock-row">
              <view class="stock-item">
                <text class="stock-label">系统库存</text>
                <text class="stock-value"
                  >{{ item.inventory }}{{ item.commodityUnit }}</text
                >
              </view>
              <view class="stock-item">
                <text class="stock-label">已盘库存</text>
                <text
                  class="stock-value"
                  :class="
                    Number(item.newInventory || 0) > 0
                      ? 'stock-value-warning'
                      : ''
                  "
                  >{{
                    Number(item.newInventory || 0) === 0
                      ? "未盘"
                      : `${Number(item.newInventory || 0)}${item.commodityUnit}`
                  }}</text
                >
              </view>
            </view>
          </view>
        </view>

        <view class="action-row">
          <u-button
            v-if="item.status === 1"
            type="primary"
            text="盘点"
            :customStyle="customBtnStyle"
            :disabled="!isEdit"
            @click="handleCheck(item)"
            class="action-btn"
          ></u-button>
          <u-button
            v-else
            type="primary"
            text="重新盘点"
            :disabled="!isEdit"
            :customStyle="customBtnStyle"
            @click="handleCheck(item)"
            class="action-btn"
          >
          </u-button>
          <u-tag
            :text="`盘亏${item.inventory - item.newInventory}`"
            bg-color="#FF4E02"
            color="#ffffff"
            class="action-btn"
            v-if="item.status === 3"
          >
          </u-tag>
          <u-tag
            :text="`盘盈${item.newInventory - item.inventory}`"
            bg-color="#F59701"
            color="#ffffff"
            class="action-btn"
            v-if="item.status === 2"
          >
          </u-tag>
          <u-tag
            text="无差异"
            bg-color="#00B97B"
            color="#ffffff"
            class="action-btn"
            v-if="item.status === 4"
          >
          </u-tag>
          <u-tag
            text="未盘"
            bg-color="#0256FF"
            color="#ffffff"
            class="action-btn"
            v-if="item.status === 1"
          >
          </u-tag>
        </view>
      </view>
      <!-- 加载更多 -->
      <u-loadmore :status="loadStatus" @loadmore="onLoadMore" />
    </view>
    <!-- 过滤条件弹框 -->
    <InventoryFilterPopup
      :show.sync="filterPopupVisible"
      :defaultValues="queryFilterValues"
      @confirm="handleFilterConfirm"
      :taskId="taskId"
    />
    <!-- 盘点数量 -->
    <actionNumPopup
      :show.sync="actionPop.showNumPop"
      :min-count="actionPop.minCount"
      @confirm="handleConfirmNum"
    />
    <!-- 修改库位 -->
    <categoryPopup
      :show.sync="actionPop.showCategoryPop"
      :original-location="actionPop.originalLocation"
      @confirm="haandleComfirmLocation"
    />
    <error-pop
      v-model="actionPop.errorShow"
      isCenter
      cancelBtnText="取消"
      confirmBtnText="确定"
      @close="actionPop.errorShow = false"
      @confirm="submit"
      :content="actionPop.errorText"
    ></error-pop>
  </view>
</template>

<script>
import InventoryFilterPopup from "./components/inventoryFilterPopup.vue";
import actionNumPopup from "./components/actionNumPopup.vue";
import categoryPopup from "./components/categoryPopup.vue";
import errorPop from "@/components/error-pop/error-pop.vue";
import { getGoodsInventoryStatusInfo } from "./utils/index.js";
import {
  taskStocktakingDetail,
  taskStocktakingItemList,
  stocktaking,
} from "@/common/request/apis/inventoryTask";
import { mapGetters } from "vuex";

export default {
  components: {
    InventoryFilterPopup,
    actionNumPopup,
    errorPop,
    categoryPopup,
  },
  data() {
    return {
      offsetTop: 0,
      pageType: "1", // 1:去盘点，可操作 2:盘点详情
      taskId: "", //任务id
      customBtnStyle: {
        width: "144rpx",
        height: "56rpx",
        borderRadius: "28rpx",
        fontSize: "32rpx",
        borderRadius: "8rpx",
      },
      pageTitle: "2025年中心仓第三季度食品盘点",
      pageNum: 1,
      pageSize: 10,
      inventoryInfo: {
        code: "2024202244",
        operator: "刘双秀",
        progress: 105,
        total: 604,
      },
      loadStatus: "loadmore", //加载前值为loadmore，加载中为loading，没有数据为nomore
      goodsList: [],
      filterPopupVisible: false,
      queryFilterValues: {
        statusList: [], //盘点状态
        userIdList: [], // 盘点负责人id
        categoryIdList: [], // 类目
        positionList: [], // 库位
        number: "",
      },
      actionPop: {
        // 盘点数量弹框状态
        showNumPop: false,
        minCount: 0,
        maxCount: 9,
        activeGoodsItem: null,
        // 警告提示弹框状态
        errorShow: false,
        errorText: "是否提交盘点？",
        // 修改库位弹框状态
        showCategoryPop: false,
        originalLocation: "",
      },
    };
  },
  computed: {
    getProgressPercentage() {
      return (
        (this.inventoryInfo.finishCount / this.inventoryInfo.materialCount) *
        100
      );
    },
    isEdit() {
      return this.pageType === "1";
    },
    ...mapGetters(["userInfo"]),
  },
  onLoad(opt) {
    let systemInfo = uni.getSystemInfoSync();
    let statusBarHeight = systemInfo.statusBarHeight;
    this.offsetTop = statusBarHeight + 40;
    console.log("222222", opt);
    this.pageType = opt.pageType;
    this.taskId = opt.id;
    this.loadData(opt.id);
  },
  onShow() {
    uni.$on("scanFinish", (data) => {
      this.queryFilterValues.number = data;
      this.onRefresh();
    });
  },
  onHide() {
    uni.$off("scanFinish");
  },
  onUnload() {
    uni.$off("scanFinish");
  },
  onPullDownRefresh() {
    // 下拉刷新
    this.onRefresh();
  },
  onReachBottom() {
    // 触底加载更多
    this.onLoadMore();
  },
  methods: {
    getGoodsInventoryStatusInfo,
    async onRefresh() {
      try {
        await this.loadData(this.taskId, true);
      } finally {
        uni.stopPullDownRefresh();
      }
    },
    async onLoadMore() {
      if (this.loadStatus !== "loadmore") return;
      this.loadStatus = "loading";
      try {
        await this.loadData(this.taskId);
      } catch (e) {
        this.loadStatus = "loadmore";
      }
    },
    // 商品列表
    async getTaskStocktakingItemList(taskId) {
      try {
        const pageNum = this.pageNum;
        const pageSize = this.pageSize;
        const params = {
          taskId,
          ...this.queryFilterValues,
        };
        const res = await taskStocktakingItemList(params);
        const { total, rows } = res.data;
        rows.forEach((item) => {
          if (item.imgName && item.imgName.length > 0) {
            item.imgNameArr = item.imgName.split(",");
          } else {
            item.imgNameArr = [];
          }
        });
        console.log("rows======", rows);
        this.goodsList = [...this.goodsList, ...rows];
        if (pageNum * pageSize < Number(total)) {
          this.pageNum++;
          this.loadStatus = "loadmore";
        } else {
          this.loadStatus = "nomore";
        }
      } catch (error) {}
    },
    // 任务详情
    async getTaskStocktakingDetail(taskId) {
      try {
        const res = await taskStocktakingDetail(taskId);
        this.inventoryInfo = res.data;
      } catch (error) {}
    },
    resetData() {
      this.pageNum = 1;
      this.goodsList = [];
    },
    async loadData(id, isRefresh = false) {
      if (isRefresh) {
        this.resetData();
      }
      try {
        this.getTaskStocktakingItemList(id);
        this.getTaskStocktakingDetail(id);
      } catch (error) {}
    },
    // 库位编辑
    handlePositionEdit(item) {
      this.actionPop.showCategoryPop = true;
      this.actionPop.activeGoodsItem = { ...item };
      this.actionPop.originalLocation = item.position;
    },
    async haandleComfirmLocation(val) {
      const activeGoodsItem = this.actionPop.activeGoodsItem;
      try {
        const params = {
          id: activeGoodsItem.id,
          materialItemId: activeGoodsItem.materialItemId,
          newPosition: val,
        };
        const res = await stocktaking(params);
        if (res.code === 200) {
          uni.$u.toast(res.msg);
          this.onRefresh();
          this.actionPop.showCategoryPop = false;
        } else {
          uni.$u.toast(res.data);
        }
      } catch (error) {}
    },
    handleCheck(item) {
      this.actionPop.showNumPop = true;
      this.actionPop.activeGoodsItem = { ...item };
      this.actionPop.maxCount = item.inventory;
    },
    async handleConfirmNum(val) {
      console.log(111223, val);
      const activeGoodsItem = this.actionPop.activeGoodsItem;
      console.log("activeGoodsItem========", activeGoodsItem);
      try {
        const params = {
          id: activeGoodsItem.id,
          materialItemId: activeGoodsItem.materialItemId,
          newInventory: val,
        };
        const res = await stocktaking(params);
        console.log("res----------", res);
        if (res.code === 200) {
          uni.$u.toast(res.msg);
          this.onRefresh();
        } else {
          uni.$u.toast(res.data);
        }
      } catch (error) {}
    },
    // 盘点提交
    submit() {},
    handleFilterConfirm(values) {
      console.log("handleFilterConfirm======", values);
      this.queryFilterValues = values;
      this.filterPopupVisible = false;
      this.onRefresh();
    },
    scanCode() {
      this.$scan.scanCode();
    },
  },
};
</script>

<style lang="scss">
.inventory-detail {
  min-height: 100vh;
  background-color: #f0f6fb;
  padding-bottom: 40rpx;

  .nav-right {
    padding: 0 24rpx;
  }

  .search-box {
    background-color: rgba(191, 200, 219, 0.2);
    margin: 0 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 8rpx;

    ::v-deep .u-search__content {
      background-color: transparent !important;

      .u-search__content__input {
        background-color: transparent !important;
      }
    }

    .scan-icon {
      width: 100rpx;
      height: 100%;

      image {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  .info-card {
    background-color: #fff;
    padding: 16rpx 32rpx;

    .info-item-box {
      display: flex;
      justify-content: space-between;
    }

    .info-item {
      display: flex;
      font-size: 28rpx;
      margin-bottom: 10rpx;

      &.page-title {
        color: #333;
      }
      .info-label {
        color: #999;
        margin-right: 8rpx;
      }

      .info-value {
        flex: 1;
        color: #999;
      }
    }

    .progress-box {
      .progress-label-box {
        display: flex;
        justify-content: space-between;
      }

      .progress-label {
        font-size: 28rpx;
        color: #999;
        display: block;
        margin-bottom: 16rpx;
      }

      .progress-bar-wrap {
        margin-bottom: 16rpx;
      }

      .progress-value {
        color: #999;
        font-size: 24rpx;
        display: block;
        text-align: right;
      }

      .finished-value {
        color: #4080ff;
      }
    }
  }

  .filter-wrap {
    display: flex;
    justify-content: flex-end;
    padding: 20rpx;

    .filter-btn {
      display: flex;
      align-items: center;
      border-radius: 8rpx;
      font-size: 24rpx;
      color: #333333;

      .icon {
        margin-left: 8rpx;
        width: 32rpx;
        height: 32rpx;
      }
    }
  }

  .goods-list {
    width: 710rpx;
    margin: 0 20rpx;
    border-radius: 16rpx;

    .goods-item {
      background-color: #fff;
      overflow: hidden;
      border-bottom: 1px solid #f5f6f7;

      .location-row {
        display: flex;
        align-items: center;
        padding: 24rpx 32rpx;
        gap: 40rpx;

        .location-left {
          display: flex;
          align-items: center;

          .location-label {
            font-size: 28rpx;
            color: #333;
          }

          .location-value {
            font-size: 28rpx;
            color: #4080ff;
            margin: 0 8rpx;
          }

          .icon {
            width: 32rpx;
            height: 32rpx;
          }
        }

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

      .goods-content {
        padding: 24rpx 32rpx;
        display: flex;

        .goods-image {
          width: 160rpx;
          flex-basis: 160rpx;
          height: 160rpx;
          border-radius: 8rpx;
          background-color: #f5f6f7;
        }

        .goods-info {
          display: flex;
          flex-wrap: wrap;
          flex: 1;
          margin-left: 24rpx;

          .half-w {
            width: 50%;
          }

          .goods-name {
            width: 100%;
            font-size: 28rpx;
            line-height: 1.4;
            color: #333;
            margin-bottom: 16rpx;
          }

          .goods-field {
            font-size: 24rpx;
            color: #666;
            margin-bottom: 16rpx;

            .field-label {
              color: #999;
            }

            .field-value {
              color: #666;
            }
          }
        }
      }

      .stock-row {
        display: grid;
        grid-template-columns: 50% 50%;
        width: 100%;
        padding: 24rpx;
        background-color: #f6f8fa;
        border-radius: 8rpx;

        .stock-item {
          display: flex;
          flex-direction: column;

          .stock-label {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 20rpx;
          }

          .stock-value {
            font-size: 24rpx;
            color: #333;

            &-warning {
              color: #ff4e02;
            }
          }
        }
      }

      .action-row {
        padding: 0 32rpx 32rpx;
        display: flex;
        justify-content: flex-end;
        gap: 24rpx;

        .action-btn {
          height: 56rpx;
          padding: 0;
          margin-left: 20rpx;
          border: 0;
        }
      }
    }
  }
}
</style>
