<script lang="ts" setup>
import dayjs from "dayjs";
import {appCouponCopyCouponCodePost, appCouponMerchantCouponListPost} from "@/service";
import usePage from "@/hooks/usePage";
import {setClipboardData} from "@/utils/utils";
import {useUserStore} from "@/store";
import {useMessage} from "wot-design-uni";
import {deleteCouponApi} from "@/pages-user/service";

const message = useMessage();
const userStore = useUserStore();
const {t} = useI18n()

function appShopSettlementList(pageNum: number, pageSize: number) {
  return new Promise(resolve => {
    appCouponMerchantCouponListPost({
      params: {
        pageNum,
        pageSize,
      }
    }).then(res => {
      resolve(res)
    })
  })
}

const {paging, loading, firstLoaded, dataList, queryList} = usePage(appShopSettlementList)

onShow(() => {
  nextTick(() => {
    paging.value?.refresh()
  })
})

function navigateTo(url: string) {
  uni.navigateTo({url})
}

// 复制兑换码
function appCouponCopyCouponCode(item: any) {
  if (item.distributionType === 2) {
    appCouponCopyCouponCodePost({
      body: {
        id: item.id,
      }
    }).then((res: any) => {
      console.log('生成的', res)
      if (res.data && res.data.length > 0) {
        setClipboardData(res.data.join(','))
      }
    })
  }
}

// 删除优惠券
function appCouponDeleteCoupon(item: any) {
  message
      .confirm({
        title: t("common.prompt.system-prompt"),
        msg: `${t("common.prompt.system-prompt-delete")}`,
        confirmButtonText: t("common.yes"),
        cancelButtonText: t("common.no"),
        cancelButtonProps: {
          customClass:
              "!h-88rpx !w-258rpx !min-w-auto !text-30rpx  !lh-42rpx !font-bold !border-#666666   !rounded-20rpx",
        },
        confirmButtonProps: {
          customClass:
              "!h-88rpx !w-258rpx !min-w-auto !text-30rpx !lh-42rpx !font-bold  !bg-primary  !rounded-20rpx",
        },
      })
      .then(async () => {
        deleteCouponApi(item.id).then(() => {
          uni.showToast({
            title: t('toast.deleteSuccess'),
            icon: 'none'
          })
          paging.value?.refresh()
        })
      })
      .catch(() => {
      });
}

// 当前商家是否已经入驻了
const isMerchant = computed(() => {
  return userStore.currentMerchantToken.length > 0
})

const show = ref(false)
const pickerValue = ref(0)
const columns = [
  {
    label: t('common.redeemCode'),
    value: 0
  },
  {
    label: t('common.coupon'),
    value: 1
  }
]

function handleClose() {
  show.value = false
}

function handleSubmit() {
  show.value = false
  pickerValue.value ? navigateTo('/pages-user/pages/coupons/add-new-coupons') : navigateTo('/pages-user/pages/coupons/add-coupons')
}

function openCoupons() {
  show.value = true
}
</script>

<template>
  <view>
    <z-paging ref="paging" v-model="dataList" :auto="false" @query="queryList">
      <template #top>
        <navbar :title="t('pages-user.coupons.title')"></navbar>
      </template>

      <view class="p-30rpx">
        <template v-for="item in dataList">
          <wd-swipe-action>
            <view class="w-full h-178rpx relative mb-30rpx last:mb-0">
              <image
                  class="absolute top-0 left-0 w-full h-full"
                  src="@img/chef/198.png"
              ></image>
              <view class="absolute top-0 left-0 w-full h-full relative z-2 px-40rpx py-42rpx">
                <view class="flex-center-sb gap-20rpx">
                  <text class="text-36rpx lh-36rpx text-#333 font-500 line-clamp-1">
                    {{ item.name || item.nameZh }}
                  </text>
                  <view class="shrink-0 ml-30rpx">
                    <template v-if="item.usedQuantity !== item.totalQuantity">
                      <text class="text-28rpx lh-28rpx text-#CE7138 font-500">{{ t('common.distributing') }}</text>
                    </template>
                    <template v-else>
                      <text class="text-28rpx lh-28rpx text-#00A76D font-500">{{ t('common.ended') }}</text>
                    </template>
                  </view>
                </view>
                <view class="flex-center-sb text-28rpx lh-28rpx mt-30rpx">
                  <text v-if="item.distributionType === 1" class="text-#999">
                    {{ dayjs(Number(item.createTime)).format('YYYY.MM.DD') }}-
                    {{ dayjs(Number(item.createTime)).add(Number(item.validDays), 'day').format('YYYY.MM.DD') }}
                  </text>
                  <text v-if="item.distributionType === 2" class="text-#999">
                    {{ dayjs(Number(item.validStart)).format('YYYY.MM.DD') }}-
                    {{ dayjs(Number(item.validEnd)).format('YYYY.MM.DD') }}
                  </text>
                  <text class="text-#333 font-500">{{ item.usedQuantity }}/{{ item.totalQuantity }}</text>
                </view>
              </view>
            </view>
            <template #right>
              <view class="action flex items-center text-30rpx lh-30rpx text-#fff">
                <view class="w-180rpx h-178rpx center text-#333"
                      @click="appCouponCopyCouponCode(item)">
                  {{ t('pages-user.coupons.copyCode') }}
                </view>
                <view class="w-80rpx h-178rpx center"
                      @click="appCouponDeleteCoupon(item)">
                  <view class="i-carbon-trash-can text-36rpx text-#f00"></view>
                </view>
              </view>
            </template>
          </wd-swipe-action>
        </template>
      </view>
    </z-paging>

    <view v-if="isMerchant" class="w-118rpx h-118rpx rounded-50% fixed bottom-104rpx right-30rpx"
          @click="openCoupons">
      <image
          class="absolute top-0 left-0 w-118rpx h-118rpx"
          src="@img/chef/195.png"
      ></image>
      <view class="absolute top-0 left-0 w-118rpx h-118rpx center flex-col relative z-2">
        <wd-icon color="#fff" name="add" size="18px"></wd-icon>
        <text class="text-26rpx text-#fff mt-10rpx">{{ t('pages-user.recipe.index.add') }}</text>
      </view>
    </view>
  </view>

  <wd-popup
      v-model="show"
      position="bottom"
      @close="handleClose"
  >
    <view>
      <view class="flex-center-sb h-102rpx bg-#F7F7F7 px-30rpx">
        <view class="text-30rpx text-#999" @click="handleClose">{{ t('common.cancel') }}</view>
        <view class="text-34rpx text-#333">{{ t('common.select') }} {{ t('common.stores') }}</view>
        <view class="text-30rpx text-#FF6106" @click="handleSubmit">{{ t('common.confirm') }}</view>
      </view>
      <view class="bg-#fff px-54rpx py-56rpx">
        <wd-picker-view v-if="show" v-model="pickerValue" :columns="columns"/>
      </view>
    </view>
  </wd-popup>
</template>

<style>
page {
  background-color: #F6F6F6;
}
</style>

<style lang="scss" scoped>
:deep(.uni-picker-view-wrapper) {
  & > uni-picker-view-column:first-of-type .uni-picker-view-group {
    .uni-picker-view-indicator {
      border-radius: 20rpx !important;

      &:after {
        border: none;
      }

      &:before {
        border: none;
      }
    }
  }
}

:deep(.wd-picker-view-column__item) {
  line-height: 94rpx !important;
}

:deep(.uni-picker-view-indicator) {
  height: 94rpx !important;
}
</style>