<template>
  <view class="min-page bg-f7 u-font-28">
    <up-sticky>
      <view class="bg-fff default-box-padding">
        <view class="u-flex">
          <image
            style="width: 60rpx; height: 60rpx"
            src="/pageMarket/static/images/coupon_code.png"
          ></image>
          <view class="u-flex-1 u-flex u-p-l-24">
            <view class="u-font-28 u-flex-1 u-p-r-24">
              <view class="color-333 font-bold">券兑换码 </view>
              <view class="color-666 u-m-t-4 u-font-24"
                >可添加多券组合兑换
              </view>
            </view>
            <up-switch
              v-model="accountInfoStore.shopInfo.isProductSuggest"
              size="18"
              :active-value="1"
              :inactive-value="0"
            ></up-switch>
          </view>
        </view>
      </view>
    </up-sticky>
    <view class="u-p-t-60 default-box-x-padding">
      <view class="u-flex u-row-between">
        <view class="shop" @click="showShopModal">适用门店</view>
        <view
          class="u-flex status-sel u-row-between bg-fff u-line-1"
          @click="showStatusModal"
        >
          <text class="color-999" v-if="returnStatusText == '全部'">全部</text>
          <text class="color-333" v-else>{{ returnStatusText }}</text>
          <up-icon name="arrow-down" size="14"></up-icon>
        </view>
      </view>
    </view>
    <view class="default-box-padding">
      <view
        v-for="(item, index) in list"
        class="u-m-b-56 default-box-radius bg-fff default-box-padding"
      >
        <view class="u-flex u-row-between">
          <text class="u-font-32 font-bold color-333">{{ item.name }}</text>
          <view class="status" :class="['status' + item.status]">{{
            item.status == 0 ? "有效" : "无效"
          }}</view>
        </view>
        <view class="u-m-t-22 color-666 u-font-24 u-flex">
          <view>
            <view> 有效期：{{ item.startTime }} 至 {{ item.endTime }}</view>
            <view class="u-m-t-16"
              >优惠券（张）：
              <text class="color-333 u-font-28 font-bold">{{
                item.couponNum
              }}</text></view
            >
            <view class="u-m-t-16">{{ returnCoupon(item) }}</view>
          </view>

          <view class="btn edit" @click="handleEdit(item)">查看</view>
        </view>
        <!-- <view class="u-flex u-row-right gap-20 u-m-t-24">
          <view class="btn del" @click="handleDelete(item)">删除</view>
          <view class="btn edit" @click="handleEdit(item)">查看</view>
        </view> -->
      </view>
    </view>
    <view style="height: 100rpx"></view>
    <view class="fixed-bottom">
      <my-button @click="go.to('PAGES_MARKET_COUPON_EXCHANGE_CODE_ADD')"
        >添加兑换码</my-button
      >
    </view>

    <Modal
      v-model="modalData.show"
      :title="modalData.title"
      @confirm="handleConfirm"
    >
      <template v-if="modalData.key == 'selShop'">
        <view class="default-box-padding">
          <my-shop-select
            @shop-select="shopSelect"
            v-model:selShops="form.shopIdList"
            v-model:useType="form.useType"
          ></my-shop-select>
        </view>
      </template>
    </Modal>

    <u-action-sheet
      :actions="actions"
      cancelText="取消"
      :closeOnClickAction="true"
      round="6"
      @close="showAction = false"
      @select="selectStatus"
      :show="showAction"
    ></u-action-sheet>
  </view>
</template>

<script setup>
import {
  onLoad,
  onReady,
  onShow,
  onPageScroll,
  onReachBottom,
  onBackPress,
} from "@dcloudio/uni-app";
import Modal from "@/pageMarket/components/modal.vue";
import * as couponRedemptionApi from "@/http/api/market/couponRedemption.js";
import { useAccountInfoStore } from "@/store/account.js";
import go from "@/commons/utils/go.js";
const accountInfoStore = useAccountInfoStore();
import { ref, reactive, onMounted, computed, watch } from "vue";
const loadFinish = ref(false);
const form = reactive({
  isEnable: 0,
  useType: "all",
});

const actions = [
  {
    name: "全部",
    value: "",
  },
  {
    name: "有效",
    value: "0",
  },
  {
    name: "无效",
    value: "1",
  },
];
const returnStatusText = computed(() => {
  return actions.find((item) => item.value == query.status)?.name || "全部";
});

function returnCoupon(item) {
  return item.couponInfoList
    .reduce((prev, cur) => prev + cur.title + "*" + cur.num + "、", "")
    .slice(0, -1);
}
const showAction = ref(false);
function selectStatus(item) {
  console.log(item);
  query.status = item.value;
}

function showStatusModal() {
  showAction.value = true;
}

function showShopModal() {
  modalData.show = true;
  modalData.title = "适用门店";
  modalData.key = "selShop";
}

const firstModalTime = ref(0);
const modalData = reactive({
  show: false,
  title: "",
  key: "",
});

function handleDelete(item) {
  uni.showModal({
    title: "确认删除吗？",
    success: (res) => {
      if (res.confirm) {
        couponRedemptionApi
          .delete({
            id: item.id,
          })
          .then((res) => {
            uni.showToast({
              title: "删除成功",
              icon: "none",
            });
            refreshList();
          });
      }
    },
  });
}
const isEnd = ref(false);
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  status: "",
});
const list = ref([]);
function refreshList() {
  query.pageNum = 1;
  isEnd.value = false;
  getList();
}

function handleEdit(item) {
  uni.setStorageSync("couponRedemptionItem", item);
  go.to("PAGES_MARKET_COUPON_EXCHANGE_CODE_DETAIL", {
    type: "edit",
  });
}

const handleConfirm = async () => {
  if (form.useType == "custom") {
    if (form.shopIdList.length == 0) {
      uni.showToast({
        title: "请选择适用门店",
        icon: "none",
      });
      return;
    }
  }

  couponRedemptionApi.enable({
    shopIdList: form.shopIdList,
    useType: form.useType,
    isEnable: form.isEnable,
  });
  uni.showToast({
    title: "修改成功",
    icon: "none",
  });
  modalData.show = false;
};

const getList = async () => {
  loadFinish.value = false;
  if (isEnd.value) {
    return;
  }
  const res = await couponRedemptionApi.couponRedemptionList(query);
  loadFinish.value = true;
  if (query.pageNum >= res.totalPage * 1) {
    isEnd.value = true;
  }
  if (query.pageNum == 1) {
    list.value = res.records || [];
  } else {
    list.value = list.value.concat(res.records || []);
  }
  console.log(list.value);
  query.pageNum++;
};

function getShopInfo() {
  accountInfoStore.getShopInfo().then((res) => {
    console.log(res);
  });
}
watch(
  () => accountInfoStore.shopInfo.isProductSuggest,
  (newVal, oldVal) => {
    if (!loadFinish.value) return;
    accountInfoStore.editShopInfo({
      isProductSuggest: newVal,
      id: accountInfoStore.shopInfo.id,
    });
    uni.showToast({
      title: "修改成功",
      icon: "none",
    });
  }
);
watch(
  () => query.status,
  (newval) => {
    console.log(newval);
    refreshList();
  }
);

async function getConfig() {
  couponRedemptionApi.status().then((res) => {
    Object.assign(form, res);
  });
}
onReachBottom(() => {
  console.log("触底");
  getList();
});
onMounted(() => {
  getShopInfo();
  getConfig();
});
onShow(() => {
  refreshList();
});
</script>

<style lang="scss" scoped>
.status {
  padding: 8rpx 18rpx;
  border: 2rpx solid transparent;
  border-radius: 8rpx;
  &.status0 {
    background-color: rgba(123, 209, 54, 0.12);
    border-color: rgba(123, 209, 54, 1);
    color: #7bd136;
  }
  &.status1 {
    border-color: rgba(153, 153, 153, 1);
    background-color: rgba(153, 153, 153, 0.12);
    color: #999;
  }
}
.btn {
  padding: 8rpx 42rpx;
  white-space: nowrap;
  border-radius: 100rpx;
  &.del {
    background-color: #f7f7fa;
    color: #999;
  }
  &.edit {
    background-color: $my-main-color;
    color: #fff;
  }
}
.fixed-bottom {
}
.time {
  margin-left: 30rpx;
  padding: 4rpx 20rpx;
  border: 1px solid $my-main-color;
  border-radius: 8rpx;
  color: $my-main-color;
}
.shop {
  background-color: rgba(49, 138, 254, 0.07);
  color: $my-main-color;
  border: 1px solid $my-main-color;
  padding: 20rpx;
  border-radius: 8rpx;
}
.status-sel {
  min-width: 266rpx;
  padding: 18rpx 32rpx;
  border: 1px solid #d9d9d9;
  border-radius: 8rpx;
}
</style>
