<route lang="json">
{
  "layout": "tabbar",
  "style": {
    "navigationBarTitleText": "消息",
    "navigationBarBackgroundColor": "#fff"
  }
}
</route>

<script setup lang="ts">
import PageHelper from '@/components/page-helper.vue'
import {
  getMessages,
  orderPointsCancel,
  orderPointsSubmit,
  updateMessage,
} from '../../core/libs/requests'
import { MessageType } from '../../core/libs/enums'
import { ComponentExposed } from 'vue-component-type-helpers'
import { Coupon, Message } from '../../core/libs/models'
import { requestToast } from '../../core/utils/common'
import { useUserStore } from '../../store'
import { storeToRefs } from 'pinia'
import MessageCard from './components/message-card.vue'
import { useMessage } from 'wot-design-uni'
import CouponsSelector from '../common/components/coupons-selector.vue'
import { handleClickInstruction } from '../../core/libs/actions'
import PageHelperEvo from '@/components/page-helper-evo.vue'

const pageHelperRef = ref<ComponentExposed<typeof PageHelper>>()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const show = ref(false)
const tab = ref(0)
const tabs = ref([
  { label: '积分消息', value: MessageType.Integral },
  { label: '系统消息', value: MessageType.System },
  { label: '互动消息', value: MessageType.Interact },
])
const selectedCoupons = ref<Coupon[]>([])
const coupons = ref<Coupon[]>([])
const cancelReason = ref('')
const currentMessage = ref<Message>()
const { alert, confirm } = useMessage()
const { confirm: rejectConfirm } = useMessage('wd-message-box-slot')

const query = computed(() => ({ messageType: tabs.value[tab.value]?.value }))

const handleCancel = async (message: Message) => {
  await rejectConfirm({
    title: '驳回',
    beforeConfirm: async ({ resolve }) => {
      if (!cancelReason.value) {
        resolve(false)
        await uni.showToast({ title: '请输入驳回原因', icon: 'none' })
        return
      }
      await requestToast(
        () =>
          orderPointsCancel({
            id: message.businessId.toString(),
            cancelReason: cancelReason.value,
          }),
        { success: true, successTitle: '积分确认已驳回' },
      )
      resolve(true)
    },
  })
  // await deleteMessage(message.id.toString())
  await updateMessage({ id: message.id, isRead: '1' })
  await pageHelperRef.value?.refresh()
}
const handleSubmit = async (message: Message, coupons: Coupon[]) => {
  console.log(
    Number(message.pointsDetail?.points) + Number(selectedCoupons.value.at(0)?.brandPoints ?? 0),
  )
  if (coupons.length && !selectedCoupons.value.length) {
    const result = await confirm({
      title: `您有${coupons.length}张销售积分券可使用，若不使用请点击确定`,
    }).catch((reason) => reason)
    console.log(result.action)
    if (result.action === 'cancel') {
      return false
    }
  }
  console.log(11111)

  // return;
  // if (!selectedCoupons.value.length) {
  //
  // }
  await requestToast(
    async () =>
      orderPointsSubmit({
        id: message.businessId,
        userId: message.designerId,
        couponUserId: selectedCoupons.value[0]?.id,
      }),
    {
      success: true,
      successTitle: `订单积分确认成功，获得${Number(message.pointsDetail?.points) + Number(selectedCoupons.value.at(0)?.brandPoints ?? 0)}积分`,
    },
  )
  // await deleteMessage(message.id.toString())
  await updateMessage({ id: message.id, isRead: '1' })
  await pageHelperRef.value?.refresh()
  selectedCoupons.value = []
}
const handleQ = async (msg, res) => {
  currentMessage.value = msg
  coupons.value = res
  show.value = true
}
onShow(async () => {
  await nextTick(() => {
    pageHelperRef.value?.reload()
  })
})
</script>

<template>
  <view class="flex-grow flex flex-col bg">
    <PageHelperEvo
      ref="pageHelperRef"
      class="flex-grow flex"
      :request="getMessages"
      :query="query"
      :automatic="false"
    >
      <template #top>
        <wd-tabs v-model="tab">
          <block v-for="({ label }, i) in tabs" :key="i">
            <wd-tab :title="`${label}`"></wd-tab>
          </block>
        </wd-tabs>
      </template>
      <template #default="{ source }">
        <div class="flex-grow p-3.5 gap-3.5 flex flex-col">
          <template v-for="(it, i) in source.list" :key="i">
            <MessageCard
              :options="{
                ...it,
                selectedCoupons,
              }"
              @submit="handleSubmit"
              @cancel="handleCancel"
              @select-coupon="handleQ"
            ></MessageCard>
          </template>
        </div>
      </template>
    </PageHelperEvo>
    <wd-message-box selector="wd-message-box-slot">
      <!-- <wd-rate custom-class="custom-rate-class" v-model="rate" /> -->
      <wd-config-provider :themeVars="{ textareaBg: 'transparent', textareaCellHeight: '100rpx' }">
        <wd-textarea
          custom-class="bg-[#f6f6f6]! rounded-lg border border-solid border-[#9f9f9f]/20"
          v-model="cancelReason"
          line="2"
          height="100rpx"
          placeholder="请输入驳回原因"
        />
      </wd-config-provider>
    </wd-message-box>
    <CouponsSelector
      v-model="selectedCoupons"
      type="points"
      :show="show"
      :business-id="currentMessage?.businessId"
      @close="show = false"
      @click-instruction="(e) => handleClickInstruction(alert, e)"
    ></CouponsSelector>
  </view>
</template>

<style scoped lang="scss"></style>
