<template>
  <view class="app-container">
    <uv-sticky bgColor="#f7f7f7">
      <view class="table-box u-flex-center-sb">
        <view class="table-box-item" @click.stop="handleTab(1)">
          <image
            class="table-box-item-img"
            :src="$handleImageUrl('/personalCenter/icon_input.png')"
            mode=""
          >
          </image>
          <view class="title-text">输码核销</view>
        </view>
        <view class="table-box-item" @click.stop="handleTab(2)">
          <image
            class="table-box-item-img"
            :src="$handleImageUrl('/personalCenter/icon_scan.png')"
            mode=""
          >
          </image>
          <view class="title-text">扫码核销</view>
        </view>
      </view>
    </uv-sticky>
    <!-- 订单核销统计 -->
    <view class="statistics u-flex-center-sb" v-if="pageType == '1'">
      <view class="statistics-item">
        <view class="statistics-item-value">{{
          simpleCount.todayCount || 0
        }}</view>
        <view class="statistics-item-title">今日核销数</view>
      </view>
      <view class="statistics-item-line"> </view>
      <view class="statistics-item">
        <view class="statistics-item-value">{{
          simpleCount.weekCount || 0
        }}</view>
        <view class="statistics-item-title">本周核销数</view>
      </view>
      <view class="statistics-item-line"></view>
      <view class="statistics-item">
        <view class="statistics-item-value">{{
          simpleCount.totalCount || 0
        }}</view>
        <view class="statistics-item-title">已核销总数</view>
      </view>
    </view>
    <!-- 积分核销统计 -->
    <view class="statistics u-flex-center-sb" v-if="pageType == '2'">
      <view class="statistics-item">
        <view class="statistics-item-value">{{
          simpleCount.todayVerifyIntegral || 0
        }}</view>
        <view class="statistics-item-title">今日核销积分</view>
      </view>
      <view class="statistics-item-line"> </view>
      <view class="statistics-item">
        <view class="statistics-item-value">{{
          simpleCount.weekVerifyIntegral || 0
        }}</view>
        <view class="statistics-item-title">本周核销积分</view>
      </view>
      <view class="statistics-item-line"></view>
      <view class="statistics-item">
        <view class="statistics-item-value">{{
          simpleCount.totalVerifyIntegral || 0
        }}</view>
        <view class="statistics-item-title">累计核销积分</view>
      </view>
    </view>

    <view class="main-list">
      <view class="main-list-top">
        <view class="main-list-title u-flex-center">
          <image
            class="main-list-title-icon"
            :src="$handleImageUrl('/personalCenter/icon_writeOff.png')"
            mode=""
          >
          </image>
          <text class="main-list-title-text">核销记录</text>
        </view>
        <view class="main-list-query u-flex-center-sb">
          <view
            class="main-list-query-date"
            @click.stop="handleDateClick('startTime')"
          >
            <template v-if="!startTime">
              <text class="iconfont date">&#xe651;</text>
              <view class="placeholder">起始时间</view>
            </template>
            <template v-else>
              <view class="text">{{ startTime }}</view>
              <view @click.stop="deleteDate('startTime')">
                <uv-icon
                  name="close-circle-fill"
                  color="#000"
                  size="28rpx"
                ></uv-icon>
              </view>
            </template>
          </view>
          <view class="main-list-query-text">至</view>
          <view
            class="main-list-query-date"
            @click.stop="handleDateClick('endTime')"
          >
            <template v-if="!endTime">
              <text class="iconfont date">&#xe651;</text>
              <view class="placeholder">截止时间</view>
            </template>
            <template v-else>
              <view class="text">{{ endTime }}</view>
              <view @click.stop="deleteDate('endTime')">
                <uv-icon
                  name="close-circle-fill"
                  color="#000"
                  size="28rpx"
                ></uv-icon>
              </view>
            </template>
          </view>
          <view class="main-list-query-btn" @click.stop="handleQuery">
            <text class="iconfont">&#xe618;</text>
            <view class="text">查询</view>
          </view>
        </view>
      </view>

      <view
        class="main-list-item"
        v-for="(item, index) in dataList"
        :key="index"
      >
        <!-- 订单 -->
        <template v-if="pageType == '1'">
          <orderItem :item="item"></orderItem>
        </template>

        <!-- 积分 -->
        <template v-else-if="pageType == '2'">
          <scoreItem :item="item"></scoreItem>
        </template>
      </view>

      <noData
        v-if="dataList.length == 0"
        :config="{ top: 5, content: '暂无数据~' }"
      ></noData>
      <loadMore v-if="dataList.length > 0" :status="status"></loadMore>
    </view>

    <uv-datetime-picker
      ref="datetimePickerRef"
      v-model="pickerDate.startTime"
      mode="date"
      :minDate="0"
      :maxDate="pickerDate.maxDate"
      :formatter="formatter"
      @confirm="bindDateChange"
    ></uv-datetime-picker>

    <uv-datetime-picker
      ref="datetimePickerRef1"
      v-model="pickerDate.endTime"
      mode="date"
      :minDate="pickerDate.minDate"
      :maxDate="pickerDate.maxDate"
      :formatter="formatter"
      @confirm="bindDateChange"
    ></uv-datetime-picker>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
import {
  onLoad,
  onReachBottom,
  onPullDownRefresh,
  onShow,
} from "@dcloudio/uni-app";
import {
  shopOrderBusinessSimpleCount_Api,
  shopOrderBusinessPage_Api,
  shopOrderValid_Api,
} from "@/api/order";

import {
  pageVerifyRecord_Api,
  verifyStatistics_Api,
  integralVerifierValid_Api,
} from "@/api/index";

import orderItem from "./components/orderItem.vue";
import scoreItem from "./components/scoreItem.vue";

const pageType = ref("1"); // 1：订单核销，2：积分核销
const simpleCount = ref({});
const dataList = ref([]);
const status = ref("more");
const parmas = reactive({
  pageNum: 1,
  pageSize: 10,
});
const datetimePickerRef = ref(null);
const datetimePickerRef1 = ref(null);
const pickerDate = reactive({ date: undefined });
const startTime = ref(""); // 起始时间
const endTime = ref(""); // 截止时间
const typeDate = ref("startTime");
const handleDateClick = (type) => {
  if (type == "startTime") {
    pickerDate.startTime = startTime.value || new Date().getTime();
    pickerDate.maxDate = endTime.value
      ? new Date(endTime.value).getTime()
      : new Date().getTime();
  } else {
    pickerDate.endTime = endTime.value || new Date().getTime();
    pickerDate.minDate = startTime.value
      ? new Date(startTime.value).getTime()
      : new Date().getTime();
    pickerDate.maxDate = new Date().getTime();
  }
  typeDate.value = type;
  nextTick(() => {
    if (type == "startTime") {
      datetimePickerRef.value.open();
    } else {
      datetimePickerRef1.value.open();
    }
  });
};

// 日期修改触发
const bindDateChange = (e) => {
  // console.log(e);
  let type = typeDate.value;
  let value = uni.$uv.date(new Date(e.value).getTime(), "yyyy-mm-dd");
  // console.log(value);
  // startTime.value = e.detail.value;
  if (type == "startTime") {
    startTime.value = value;
  }
  if (type == "endTime") {
    endTime.value = value;
  }
};

// 删除日期触发
const deleteDate = (type) => {
  if (type == "startTime") {
    startTime.value = "";
  }
  if (type == "endTime") {
    endTime.value = "";
  }
};

const formatter = (type, value) => {
  if (type === "year") {
    return `${value}年`;
  }
  if (type === "month") {
    return `${value}月`;
  }
  if (type === "day") {
    return `${value}日`;
  }
  return value;
};

const writeOffShow = uni.getStorageSync("writeOffShow") || "";
// 点击核销触发
const handleTab = (type) => {
  if (!writeOffShow) {
    uni.$uv.toast("请先营业");
    return;
  }
  if (type == 1) {
    uni.navigateTo({
      url: "/pages/shop/writeOff/inputCode?pageType=" + pageType.value,
    });
  } else {
    // 只允许通过相机扫码
    uni.scanCode({
      onlyFromCamera: true,
      success: function (res) {
        // console.log("条码类型：" + res.scanType);
        console.log("条码内容：" + res.result);
        handleSubmit(res.result);
      },
    });
  }
};

// 扫码核销触发
const handleSubmit = (code) => {
  // console.log("提交验证", code);
  if (!code) {
    return uni.showToast({ title: "未获取到核销码", icon: "none" });
  }
  uni.showLoading({ title: "核销码校验中", mask: true });
  let url =
    pageType.value == "1" ? shopOrderValid_Api : integralVerifierValid_Api;
  url({
    verificationCode: code,
  })
    .then((res) => {
      uni.hideLoading();
      if (res.code == 200) {
        uni.navigateTo({
          url: `/pages/shop/writeOff/result?code=${code}&pageType=${pageType.value}`,
        });
      }
    })
    .catch((err) => {
      // uni.hideLoading();
    });
};

const handleQuery = () => {
  parmas.startTime = startTime.value || undefined;
  parmas.endTime = endTime.value || undefined;
  handleReset();
};

// 获取简单统计信息
const getSimpleCount = (show) => {
  let url =
    pageType.value == "1"
      ? shopOrderBusinessSimpleCount_Api
      : verifyStatistics_Api;
  url().then((res) => {
    if (res && res.code == 200) {
      let info = simpleCount.value;
      if (
        show &&
        ((pageType.value != "1" &&
          info.weekVerifyIntegral != res.data.weekVerifyIntegral) ||
          (pageType.value == "1" && info.todayCount != res.data.todayCount))
      ) {
        handleReset();
      }
      simpleCount.value = res.data || {};
    }
  });
};

const getList = async () => {
  uni.showLoading({ title: "加载中..." });
  let url =
    pageType.value == "1" ? shopOrderBusinessPage_Api : pageVerifyRecord_Api;
  await url(parmas).then((res) => {
    uni.hideLoading();
    uni.stopPullDownRefresh();
    if (res && res.code == 200) {
      if (parmas.pageNum == 1) {
        dataList.value = [];
      }
      dataList.value = dataList.value.concat(res.rows);
      if (res.total <= dataList.value.length) {
        status.value = "noMore";
      } else {
        status.value = "more";
      }
    }
  });
};

// 重置列表请求
const handleReset = () => {
  status.value = "loading";
  parmas.pageNum = 1;
  dataList.value = [];
  getList();
};

onShow(() => {
  getSimpleCount(true);
});

onLoad((options) => {
  console.log(options);
  if (options.pageType) {
    pageType.value = options.pageType;
  }
});

onReachBottom(() => {
  if (status.value == "noMore") return;
  status.value = "loading";
  parmas.pageNum++;
  getList();
});

onPullDownRefresh(() => {
  getSimpleCount();
  handleReset();
});
</script>

<style lang="scss" scoped>
.app-container {
  min-height: 100vh;
  box-sizing: border-box;
  background-color: #f7f7f7;
  .table-box {
    justify-content: space-around;
    padding: 56rpx 0 30rpx 0;
    .table-box-item {
      .table-box-item-img {
        width: 144rpx;
        height: 101rpx;
      }
      .title-text {
        font-size: 36rpx;
        color: #1a1a1a;
        font-weight: 700;
        margin-top: -26rpx;
        position: relative;
        z-index: 1;
      }
    }
  }
  .statistics {
    padding: 44rpx 30rpx;
    margin-bottom: 50rpx;
    justify-content: space-around;
    background-color: #ffffff;
    border-radius: 24rpx;
    .statistics-item {
      text-align: center;
      .statistics-item-value {
        font-size: 38rpx;
        color: #eb5153;
        font-weight: 700;
      }
      .statistics-item-title {
        font-size: 28rpx;
        margin-top: 12rpx;
      }
    }
    .statistics-item-line {
      width: 1rpx;
      height: 56rpx;
      background-color: #e6e6e6;
    }
  }
  .main-list {
    .main-list-top {
      padding: 0 30rpx 30rpx 30rpx;
      .main-list-title {
        margin-bottom: 30rpx;
        .main-list-title-icon {
          width: 49rpx;
          height: 52rpx;
          margin-right: 10rpx;
        }
        .main-list-title-text {
          font-size: 34rpx;
          color: #1a1a1a;
          font-weight: 700;
        }
      }
      .main-list-query {
        box-sizing: border-box;
        .main-list-query-date {
          width: 240rpx;
          height: 70rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #ffffff;
          border: 1rpx solid #e6e6e6;
          border-radius: 10rpx;
          box-sizing: border-box;
          .date {
            font-size: 36rpx;
            color: #ffad00;
          }
          .placeholder {
            font-size: 24rpx;
            color: #d9d9d9;
            margin-left: 5rpx;
          }
          .text {
            font-size: 24rpx;
            color: #1a1a1a;
            margin-right: 10rpx;
          }
        }
        .main-list-query-text {
          font-size: 28rpx;
          font-weight: 400;
          color: #1a1a1a;
        }

        .main-list-query-btn {
          width: 141rpx;
          height: 70rpx;
          background: #eb5153;
          border-radius: 10rpx;
          box-sizing: border-box;
          color: #ffffff;
          font-size: 28rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          .text {
            margin-left: 5rpx;
          }
        }
      }
    }
  }
}
</style>
