<template>
  <view class="check-page">
    <u-navbar height="40px" title="盘点" bgColor="#fff" autoBack placeholder>
      <view class="u-nav-slot depot-label" slot="right">
        <view class="name">{{ curDepotName }}</view>
      </view>
    </u-navbar>
    <view class="container_main">
      <u-sticky :offsetTop="offsetTop" bgColor="#fff">
        <view class="search-box">
          <u-search
            placeholder="请输入单据编号或名称"
            shape="square"
            v-model="query.number"
            :showAction="false"
            :clearabled="true"
            @search="handleSearch"
            @clear="handleSearch"
          ></u-search>
        </view>
        <view class="type-box">
          <u-tabs
            :list="tabList"
            :inactiveStyle="{ color: '#000', fontSize: '28rpx' }"
            :activeStyle="{ color: '#000', fontSize: '28rpx' }"
            lineColor="#0256FF"
            lineWidth="66rpx"
            @click="tabClick"
          >
          </u-tabs>
        </view>
      </u-sticky>
      <view class="content-box">
        <view class="content-box-val">
          <check-item
            v-for="item in list"
            :key="`${item.id}-${item.taskStatus}`"
            :info="item"
            @btnClick="handleBtnClick"
          ></check-item>
        </view>
        <u-empty
          mode="data"
          text="暂无内容"
          marginTop="60"
          icon="https://xiangli-erp.oss-cn-hangzhou.aliyuncs.com/APP/no-notifcations.png"
          v-if="list.length == 0"
        ></u-empty>
        <!-- 加载更多 -->
        <u-loadmore
          v-if="list.length > 0"
          :status="loadStatus"
          @loadmore="onLoadMore"
        />
      </view>
    </view>

    <error-pop
      v-model="actionPop.errorShow"
      isCenter
      cancelBtnText="取消"
      confirmBtnText="确定"
      @close="actionPop.errorShow = false"
      @confirm="submit"
      :content="actionPop.errorText"
    ></error-pop>
  </view>
</template>

<script>
import checkItem from "./components/check-item.vue";
import errorPop from "@/components/error-pop/error-pop.vue";

import {
  taskStocktakingList,
  startTask,
  taskComplete,
  taskStocktakingDetail,
} from "@/common/request/apis/inventoryTask";
import { taskStatusList } from "../inventory-task/utils/index.js";
import { mapGetters } from "vuex";

export default {
  components: {
    checkItem,
    errorPop,
  },
  data() {
    return {
      offsetTop: 0,
      tabList: taskStatusList,
      query: {
        number: "",
        status: "",
      },
      currentPage: 1,
      pageSize: 10,
      loadStatus: "loadmore", //加载前值为loadmore，加载中为loading，没有数据为nomore
      list: [],

      activeTaskId: null,
      actionPop: {
        // 警告提示弹框状态
        errorShow: false,
        submitActionFlag: false,
        errorText: "是否提交盘点？",
      },
      startTaskId: null,
      toStock: false, //是否跳转盘点
      // 中心仓
      cangName: "",
    };
  },
  computed: {
    ...mapGetters(["depotInfo"]),
    curDepotId() {
      return this.depotInfo ? this.depotInfo.id : "";
    },
    curDepotName() {
      return this.depotInfo ? this.depotInfo.depotName : "";
    },
  },
  onLoad() {
    let systemInfo = uni.getSystemInfoSync();
    let statusBarHeight = systemInfo.statusBarHeight;
    this.offsetTop = statusBarHeight + 40;
    this.loadData();
  },
  onShow() {
    if (this.startTaskId) {
      let index = this.list.findIndex((item) => item.id == this.startTaskId);
      this.list[index].taskStatus = 2;
      this.startTaskId = null;
    }
  },
  onPullDownRefresh() {
    // 下拉刷新
    this.onRefresh();
  },
  onReachBottom() {
    // 触底加载更多
    this.onLoadMore();
  },
  methods: {
    async onRefresh() {
      try {
        await this.loadData(true);
      } finally {
        uni.stopPullDownRefresh();
      }
    },
    async onLoadMore() {
      if (this.loadStatus !== "loadmore") return;
      this.loadStatus = "loading";
      try {
        await this.loadData();
      } catch (e) {
        this.loadStatus = "loadmore";
      }
    },
    async loadData(isRefresh = false) {
      if (isRefresh) {
        this.currentPage = 1;
        this.list = [];
      }

      try {
        this.loadStatus = "loading";
        const currentPage = this.currentPage;
        const pageSize = this.pageSize;
        const params = {
          currentPage,
          pageSize,
          ...this.query,
          depotId: this.curDepotId,
        };
        console.log("params=====", params);
        const res = await taskStocktakingList(params);
        const { rows, total } = res.data;
        this.list = [...this.list, ...rows];
        if (currentPage * pageSize < Number(total)) {
          this.currentPage++;
          this.loadStatus = "loadmore";
        } else {
          this.loadStatus = "nomore";
        }
      } catch (error) {}
    },
    tabClick({ index }) {
      this.query.status = this.tabList[index].value;
      this.loadData(true);
    },
    handleSearch(value) {
      this.loadData(true);
    },
    // 前往盘点任务详情
    handleBtnClick(data) {
      console.log(11111, data);
      // params.id--->任务id   params.btnName--->按钮label
      const { btnName } = data;
      switch (btnName) {
        case "详情":
          uni.navigateTo({
            url: `/pages/inventory-task/taskDetail?id=${data.id}`,
          });
          break;
        case "去盘点":
          startTask(data.id).then((res) => {
            if (res.code === 200) {
              uni.navigateTo({
                url: `/pages/inventory-task/detail?id=${data.id}&pageType=1`,
              });
              this.startTaskId = data.id;
            } else {
              uni.$u.toast(res.data);
            }
          });
          break;
        case "去提交":
          taskStocktakingDetail(data.id).then((res) => {
            let { finishCount, materialCount } = res.data;
            const a = Number(finishCount || 0);
            const b = Number(materialCount || 0);
            this.activeTaskId = data.id;
            this.actionPop.errorShow = true;
            if (a === b) {
              // 进度100%
              this.actionPop.errorText = "是否提交盘点？";
              this.actionPop.submitActionFlag = true;
            } else {
              this.actionPop.errorText = "尚有货物未完成盘点，请先去盘点";
              this.actionPop.submitActionFlag = false;
              this.toStock = true;
            }
          });

          break;
      }
    },
    resetErrorPopData() {
      this.actionPop.errorShow = false;
      this.actionPop.submitActionFlag = false;
      this.actionPop.errorShow = "";
    },
    submit() {
      if (this.actionPop.submitActionFlag) {
        taskComplete(this.activeTaskId).then((res) => {
          this.resetErrorPopData();
          if (res.code === 200) {
            uni.$u.toast(res.msg);
            this.actionPop.errorShow = false;
            this.onRefresh();
          } else {
            uni.$u.toast(res.data);
          }
        });
      } else {
        this.resetErrorPopData();
        if (this.toStock) {
          this.toStock = false;
          this.actionPop.errorShow = false;
          uni.navigateTo({
            url: `/pages/inventory-task/detail?id=${this.activeTaskId}&pageType=1`,
          });
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.check-page {
  min-height: 100vh;
  background-color: #f0f6fb;
  .container_main {
    .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;
        }
      }
    }

    .content-box {
      padding: 24rpx;
      &-val {
        border-radius: 16rpx 16rpx 0 0;
        overflow: hidden;
      }
    }
  }
}
</style>
