<template>
  <view class="min-page bg-f7 default-box-padding u-font-28 color-333">
    <view class="bg-fff default-box-radius">
      <view class="default-box-padding u-flex u-row-between">
        <text class="font-bold">兑换码名称</text>
        <view  >
            <up-input  v-model="form.name" placeholder="请输入兑换码名称"></up-input>
        </view>
      </view>
      <up-line></up-line>
      <view class="default-box-padding u-flex u-row-between">
        <text class="font-bold">活动日期</text>
        <text class="color-666 u-font-24"
          >{{ form.startTime }} 至 {{ form.endTime }}</text
        >
      </view>
      <up-line></up-line>
      <view class="default-box-padding u-flex u-row-between">
        <text class="font-bold">总数</text>
        <text class="color-666 u-font-24">{{ form.total }}</text>
      </view>
      <up-line></up-line>
      <view class="default-box-padding u-flex u-row-between">
        <text class="font-bold">库存</text>
        <view style="width: 158rpx">
          <up-input
            v-model="form.stock"
            type="number"
            placeholder="库存"
            placeholder-class="color-999 u-font-28"
          ></up-input>
        </view>
      </view>
      <up-line></up-line>
      <view class="default-box-padding u-flex u-row-between">
        <text class="font-bold no-wrap">优惠券</text>
        <view class="u-p-l-30">
          <text class="">{{ returnCoupon }}</text>
          <text class="color-main u-font-32 u-m-l-20" @click="showModal"
            >修改</text
          >
        </view>
      </view>
      <up-line></up-line>
      <view class="u-p-b-24"></view>
    </view>
    <view class="u-p-t-48 u-p-b-48 u-p-l-60 u-p-r-60">
      <my-button type="primary" shape="circle" @click="save" v-if="isMainShop()">保存</my-button>
    </view>

    <view class="bg-fff default-box-radius">
      <view class="default-box-x-padding u-p-t-32 u-flex u-row-between">
        <couponStatus v-model="query.status"></couponStatus>

        <view class="u-flex">
          <view class="border u-flex default-box-radius search-box">
            <up-icon name="search"></up-icon>
            <input
              style="width: 140rpx"
              placeholder="输入兑换码"
              class="u-font-28 u-m-l-20"
              placeholder-class="color-999 u-font-28"
              @input="codeChange"
              v-model="query.code"
            />
          </view>
          <view class="daochu u-m-l-24" @click="exportCode">导出</view>
        </view>
      </view>

      <view class="list u-m-t-48">
        <view
          class="item default-box-padding"
          v-for="(item, index) in list"
          :key="index"
        >
          <view class="u-flex u-row-between">
            <text class="status" :class="['status-' + item.status]">{{
              item.status == 0 ? "未兑换" : "已兑换"
            }}</text>
            <view>
              <text class="color-666">{{ item.code }}</text>
              <text class="color-main u-m-l-20" @click="copyCode(item.code)"
                >复制</text
              >
            </view>
          </view>
          <view class="u-m-t-16 u-flex u-row-between color-666">
            <text>{{ item.redemptionTime }}</text>
            <view>
              <text>{{ item.nickName }}</text>
              <text>{{ item.phone }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <up-loadmore :status="isEnd ? 'nomore' : 'loading'"></up-loadmore>

    <Modal
      :title="ModalData.title"
      v-model="ModalData.show"
      @confirm="modelConfirm"
    >
      <view class="default-box-padding">
        <CouponList v-model="form.couponInfoList"></CouponList>
        <view class="u-m-t-16 u-flex">
          <view class="u-flex" @click="addCoupon">
            <up-icon
              name="plus-circle-fill"
              color="#318AFE"
              size="18"
            ></up-icon>
            <text class="font-bold u-m-l-20">添加</text>
          </view>
        </view>
      </view>
    </Modal>
  </view>
</template>

<script setup>
import {
  onLoad,
  onReady,
  onShow,
  onPageScroll,
  onReachBottom,
  onBackPress,
} from "@dcloudio/uni-app";
import couponStatus from "./components/status.vue";
import CouponList from "@/pageMarket/components/coupon-list.vue";
import DateTimePicker from "@/pageMarket/components/date-time-picker.vue";
import {isMainShop} from "@/store/account.js";
import Modal from "@/pageMarket/components/modal.vue";
import * as couponRedemptionApi from "@/http/api/market/couponRedemption.js";
import { saveFileFromTemp } from "@/utils/downloadFile.js";
import {
  reactive,
  toRefs,
  computed,
  watch,
  onMounted,
  onUnmounted,
  ref,
} from "vue";
function addCoupon() {
  form.couponInfoList.push({
    id: "",
    num: "",
    title: "",
  });
}
function modelConfirm() {
  //判断优惠券列表是否选择了优惠券，数量是否填写
  if (form.couponInfoList.some((item) => !item.id || !item.num)) {
    uni.showToast({
      title: "请选择优惠券并填写数量",
      icon: "none",
    });
    return;
  }
  ModalData.show = false;
}
const ModalData = reactive({
  show: false,
  title: "修改优惠券",
});
function save() {
  if (form.stock === "" || form.stock === null) {
    uni.showToast({
      title: "请填写库存",
      icon: "none",
    });
    return;
  }
  couponRedemptionApi.edit(form).then((res) => {
    uni.showToast({
      title: "修改成功",
      icon: "none",
    });
    ModalData.show = false;
    refresh();
  });
}
function showModal() {
  ModalData.show = true;
}
const form = reactive({
  couponInfoList: [],
});
onLoad((opt) => {
  const item = uni.getStorageSync("couponRedemptionItem");
  Object.assign(form, item);
  console.log(form);
  getList();
});
const query = reactive({
  status: "",
  code: "",
  page: 1,
  size: 10,
});

function copyCode(code) {
  uni.setClipboardData({
    data: code,
    success: () => {
      uni.showToast({
        title: "复制成功",
        icon: "none",
      });
    },
  });
}
const returnCoupon = computed(() => {
  return form.couponInfoList
    .reduce((prev, cur) => prev + cur.title + "*" + cur.num + "、", "")
    .slice(0, -1);
});
const list = ref([]);
const isEnd = ref(false);
function getList() {
  couponRedemptionApi
    .codeList({ ...query, redemptionId: form.id })
    .then((res) => {
      if (query.page == 1) {
        list.value = res.records;
      } else {
        list.value = [...list.value, ...res.records];
      }
      if (query.page >= res.totalPage * 1) {
        isEnd.value = true;
      }
    });
}
function refresh() {
  isEnd.value = false;
  query.page = 1;
  getList();
}
watch(() => query.status, refresh);

//节流
const throttle = (fn, delay = 500) => {
  let timer = null;
  return function () {
    if (timer) {
      return;
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, delay);
  };
};

const codeChange = throttle(() => {
  console.log(query.code);
  refresh();
});

function exportCode() {
  couponRedemptionApi
    .codeExport({
      status: query.status,
      redemptionId: form.id,
      code: query.code,
    })
    .then((res) => {
      console.log(res);
      if (res.statusCode == 200) {
        saveFileFromTemp({
            tempFilePath: res.tempFilePath,
            fileName: '优惠券兑换码.xlsx',
            isNowOpen:true
        });
        // uni.getFileSystemManager().saveFile({
        //   tempFilePath: res.tempFilePath,
        //   success: function (res) {
        //     console.log(res);
        //   },
        //   fail: function (err) {
        //     console.log(err);
        //   }
        // });
      }
    });
}

onReachBottom(() => {
  console.log("触底");
  if (isEnd.value) {
    return;
  }
  query.page++;
  getList();
});
</script>

<style scoped lang="scss">
.border {
  border: 1rpx solid #dddfe6;
}
.search-box {
  padding: 18rpx 32rpx;
}
.daochu {
  border: 1rpx solid $my-main-color;
  padding: 12rpx 34rpx;
  border-radius: 8rpx;
  white-space: nowrap;
  color: $my-main-color;
  min-height: 72rpx;
}
.status {
  font-weight: 700;
  &.status-0 {
    color: #5bbc6d;
  }
  &.status-1 {
    color: #ff895c;
  }
}
.item {
  border-bottom: 1rpx solid #f5f5f5;
  &:last-child {
    border-bottom: none;
  }
}
:deep(.uni-input-input){
    text-align: right;
}
:deep(.input-placeholder){
    text-align: right;
    color: #999;
    font-size: 28rpx;
}
</style>
