<script setup lang="ts">
import { Coupon, Message } from '../../../core/libs/models'
import Card from '@/components/card.vue'
import { integral, interact, message, system } from '../../../core/libs/svgs'
import { beforeNow } from '../../../utils/date-util'
import dayjs from 'dayjs'
import { MessageType, PointStatus } from '../../../core/libs/enums'
import { fuckYou, getPointsCoupons, updateReadByMessageType } from '../../../core/libs/requests'
import { getMessageType } from '../../../core/libs/message-types'
import { useRouter } from '../../../core/utils/router'
import ButtonEvo from '@/components/button-evo.vue'
import { messages } from '../../../core/libs/messages'
import { stringify } from 'qs'

const props = withDefaults(
  defineProps<{ options?: Message & { selectedCoupons?: Coupon[] } }>(),
  {},
)
const emits = defineEmits<{
  submit: [message: Message, coupons: Coupon[]]
  cancel: [message: Message]
  selectCoupon: [message: Message, coupons: any[]]
}>()
const router = useRouter()
const { data: coupons, run: setCoupons } = useRequest(
  () =>
    getPointsCoupons({
      userId: props.options.designerId,
      businessId: props.options.businessId,
      available: true,
    }),
  { initialData: [] },
)
const couponSelectText = computed(() => {
  const selectedCoupons = props.options.selectedCoupons || []
  const availableCoupons = props.options.availableCouponsNum || 0
  console.log('selectedCoupons computed', selectedCoupons)
  if (selectedCoupons.length > 0) {
    return `${selectedCoupons[0].brandPoints ?? 0}积分`
  }
  if (availableCoupons > 0) {
    return `${availableCoupons}张可用`
  }
  return '无可用'
})
const hasLine = computed(() => getMessageType(props.options.messageSubType)?.path)
const init = async () => {
  if (
    props.options.messageType === MessageType.Integral &&
    props.options.messageSubType === 31 &&
    props.options.isRead !== '1'
  ) {
    await setCoupons()
  }
}
const handleJump = () => {
  fuckYou({ id: props.options.id })
  if ((props.options.linkUrl ?? '') !== '') {
    return router.push(props.options.linkUrl)
  }
  const query: Record<string, string> = {}
  switch (props.options.messageSubType) {
    case 5:
      query.id = props.options.id as any
      query.title = props.options.title
      query.contentDetail = props.options.detailBody
      query.createTime = String(props.options.createTime)
      query.viewsCount = props.options.viewCount
      break
    case 14:
      query.type = props.options.couponType
    default:
      break
  }
  console.log(stringify(query))
  router.push(getMessageType(props.options.messageSubType)?.path + '?' + stringify(query))
}
watch(
  () => props.options,
  async (value, oldValue, onCleanup) => {
    // console.log('====>', value)
    await init()
  },
)
onMounted(async () => {
  await init()
})
</script>
<template>
  <Card>
    <div class="grid items-center grid-cols-[38px_auto_100px]">
      <div class="row-start-1 col-start-1">
        <div
          class="w-[30px] h-[30px] bg-neutral-100 rounded-full mr-2 flex items-center justify-center"
        >
          <wd-img
            width="18"
            height="18"
            :src="
              {
                [MessageType.Integral]: integral,
                [MessageType.System]: system,
                [MessageType.Interact]: interact,
              }[options.messageType]
            "
          ></wd-img>
        </div>
      </div>

      <div class="row-start-1 col-start-2 text-start relative">
        <div class="text-black/90 text-base font-normal font-['PingFang_SC'] leading-[30px]">
          <!--          {{-->
          <!--            String(options.messageSubType) === '5'-->
          <!--              ? getMessageType(options.messageSubType)?.desc-->
          <!--              : options.title-->
          <!--          }}-->
          {{ options.title }}
        </div>
      </div>

      <div class="row-start-1 col-start-3 text-end" style="white-space: nowrap">
        <div class="text-black/30 text-sm font-normal font-['PingFang_SC'] leading-[8.18px]">
          <template v-if="String(options.isRead) === '0'">
            <wd-img width="16" height="16" src="/static/svgs/red.svg"></wd-img>
          </template>
          {{ beforeNow(dayjs(options.createTime).toDate()) }}
          <!--          <div class="absolute top-[2px] right-[50px] z-10">-->
          <!--            <wd-img width="16" height="20" src="/static/svgs/red.svg"></wd-img>-->
          <!--          </div>-->
          <!--          <wd-img width="16" height="10" src="/static/svgs/red.svg"></wd-img>-->
        </div>
      </div>
      <div class="row-start-2 col-start-2 col-end-4">
        <div class="my-3 text-black/40 text-sm font-normal font-['PingFang_SC'] leading-[25px]">
          <!-- {{ options.detailBody }} -->
          <!--          <div-->
          <!--            v-if="-->
          <!--              [MessageType.Integral, MessageType.System].includes(options.messageType) &&-->
          <!--              String(options.messageSubType) !== '5'-->
          <!--            "-->
          <!--            v-html="options.detailBody"-->
          <!--          ></div>-->
          <div v-html="options.detailBody"></div>
          <div class="grid grid-cols-[auto_1fr] gap-x-1 gap-y-4.5">
            <template
              v-if="
                options.messageSubType === 31 &&
                options.pointsDetail?.pointsStauts === PointStatus.PendingConfirmation
              "
            >
              <div
                class="text-black/40 text-sm font-normal font-['PingFang_SC'] h-5.5 flex items-center"
              >
                销售积分券：
              </div>
              <div
                class="flex items-center h-full overflow-hidden"
                @click="emits('selectCoupon', options, coupons)"
              >
                <div
                  class="text-sm font-normal font-['PingFang_SC']"
                  :class="`${options.availableCouponsNum > 0 ? 'text-[#ef4343]' : 'text-black/60'}`"
                >
                  <!--                  {{ `${coupons.length > 0 ? `${coupons.length}张可用` : '无可用'}` }}-->
                  {{ couponSelectText }}
                </div>
                <div class="h-5.5 flex items-center overflow-hidden">
                  <wd-icon
                    name="chevron-right"
                    :custom-class="`${options.availableCouponsNum > 0 ? 'text-[#ef4343]' : 'text-black/60'}`"
                    size="16"
                  ></wd-icon>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
      <div
        v-if="options.coverUrl"
        class="row-start-3 col-start-2 col-end-4 aspect-[1.7/1] rounded-md overflow-hidden"
      >
        <wd-img
          width="100%"
          height="100%"
          mode="aspectFill"
          :src="options.coverUrl"
          @click="handleJump"
        />
      </div>
      <div v-if="hasLine" class="row-start-4 col-start-1 col-end-4 my-2">
        <div class="bg-[#dadada] w-full h-[1px]"></div>
      </div>
      <div class="row-start-5 col-start-2 col-end-4">
        <div class="text-black/40 text-xs font-normal font-['PingFang_SC']">
          <template
            v-if="
              [MessageType.Integral].includes(Number(options.messageType)) &&
              options.messageSubType === 31 &&
              options.pointsDetail?.pointsStauts === PointStatus.PendingConfirmation
            "
          >
            <span class="text-black/40">
              {{ messages.messages.pointNotice }}
            </span>
          </template>
          <template
            v-else-if="
              [MessageType.Integral].includes(Number(options.messageType)) &&
              options.messageSubType === 31
            "
          >
            <template v-if="options.pointsDetail?.pointsStauts === PointStatus.Rejected">
              <span class="text-[#EF4343]">
                <!-- 确认积分后，即刻到账，如有问题请驳回，联系材料商修改积分后再次确认 -->
                已驳回，驳回原因：{{ options.pointsDetail?.cancelReason }}
              </span>
            </template>
          </template>
          <template
            v-else-if="
              [MessageType.Integral].includes(Number(options.messageType)) &&
              [21, 22].includes(options.messageSubType)
            "
          >
            如有问题请您联系官方客服！
          </template>
          <template v-if="getMessageType(options.messageSubType)?.path">
            <div
              @click="handleJump"
              class="flex items-center text-[rgba(0,0,0,0.85)] text-xs font-normal font-['PingFang_SC'] leading-[25px]"
            >
              查看详情
              <wd-icon name="arrow-right" size="12" color="rgba(0,0,0,0.85)"></wd-icon>
            </div>
          </template>
        </div>
      </div>
      <div
        class="row-start-6 col-start-1 col-end-4 my-1"
        v-if="
          [MessageType.Integral].includes(Number(options.messageType)) &&
          options.messageSubType === 31 &&
          options.pointsDetail?.pointsStauts === PointStatus.PendingConfirmation
        "
      >
        <div class="flex gap-4 mt-4">
          <div class="flex-1">
            <!-- <wd-button block :round="false" plain @click="emits('cancel', options)">驳回</wd-button> -->
            <ButtonEvo block color="white" location="right" @click="emits('cancel', options)">
              <span class="text-black/80">驳回</span>
            </ButtonEvo>
          </div>
          <!-- <div class="flex-1">
            <wd-button block :round="false" @click="handleQ(it)">积分券</wd-button>
          </div> -->
          <div class="flex-1">
            <!-- <wd-button block :round="false" @click="emits('submit', options)">确认</wd-button> -->
            <ButtonEvo block @click="emits('submit', options, coupons)">确认</ButtonEvo>
          </div>
        </div>
      </div>
    </div>
  </Card>
</template>
