<template>
  <div class="store-page">
    <Breadcrumb />

    <a-card title="赠送审核列表">
      <AppQueryFilter>
      <a-row class="query-row app-query-form">
        <a-col :flex="1">
          <a-form :model="queryData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="status" label="审核状态">
                  <a-select v-model="queryData.status" :options="statusOptions" placeholder="请选择状态" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      </AppQueryFilter>

      <a-table :bordered="false"
        :data="data"
        stripe
        hoverable
        column-resizable
        class="table"
        :loading="loading"
        :columns="columns"
        :pagination="{
          showPageSize: true,
          showJumper: true,
          showTotal: true,
          pageSize: pagination.pagesize,
          current: pagination.current,
          total: pagination.total
        }"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #created_at="{ record }">
          {{ stramptoTime(record.created_at) }}
        </template>
        <template #reviewed_at="{ record }">
          {{ stramptoTime(record.reviewed_at) }}
        </template>
        <template #status="{ record }">
          <a-tag color="orangered" v-if="record.status === 'pending'">待审核</a-tag>
          <a-tag color="green" v-else-if="record.status === 'approved'">已通过</a-tag>
          <a-tag color="red" v-else-if="record.status === 'rejected'">已拒绝</a-tag>
        </template>
        <template #reject_reason="{ record }">
          {{ record.reject_reason || '-' }}
        </template>
        <template #optional="{ record }">
          <a-space v-if="record.status === 'pending' && hasPermission('action.goods.reviewSendCount')">
            <a-button type="primary" size="small" @click="approveRequest(record.id)">通过</a-button>
            <a-button status="danger" size="small" @click="openRejectModal(record.id)">拒绝</a-button>
          </a-space>
          <span v-else>-</span>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="rejectModalVisible"
      title="拒绝赠送申请"
      @before-ok="handleRejectBeforeOk"
      @cancel="handleRejectCancel"
    >
      <a-form :model="rejectForm">
        <a-form-item field="reason" label="拒绝原因">
          <a-textarea v-model="rejectForm.reason" :max-length="255" placeholder="选填，最多255字" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import {
  adminApproveSendCountRequest,
  adminRejectSendCountRequest,
  adminSendCountRequestList
} from '@/api/goods'
import { hasPermission } from '@/utils/permission'

const loading = ref(false)
const data = ref([])

const pagination = reactive({
  total: 0,
  current: 1,
  pagesize: 20
})

const statusOptions = [
  { label: '全部', value: '' },
  { label: '待审核', value: 'pending' },
  { label: '已通过', value: 'approved' },
  { label: '已拒绝', value: 'rejected' }
]

const queryData = reactive({
  status: ''
})

const columns = [
  { title: '申请ID', dataIndex: 'id' },
  { title: '赠送人', dataIndex: 'sender_username' },
  { title: '接收人', dataIndex: 'receiver_username' },
  { title: '赠送次数', dataIndex: 'count' },
  { title: '状态', slotName: 'status' },
  { title: '申请时间', slotName: 'created_at' },
  { title: '审核时间', slotName: 'reviewed_at' },
  { title: '拒绝原因', slotName: 'reject_reason' },
  { title: '操作', slotName: 'optional' }
]

const rejectModalVisible = ref(false)
const rejectForm = reactive({
  id: 0,
  reason: ''
})

const stramptoTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getList = async () => {
  try {
    loading.value = true
    const reqData = {
      pagesize: pagination.pagesize,
      current: pagination.current
    }
    if (queryData.status) reqData.status = queryData.status

    const res = await adminSendCountRequestList(reqData)
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取赠送审核列表失败！',
        content: res?.msg ?? '请稍后再试'
      })
    }

    data.value = res.data || []
    pagination.total = res.pagination?.total || 0
  } catch (error) {
    Notification.error({
      title: '获取赠送审核列表失败！',
      content: error.message || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

const approveRequest = async (id) => {
  try {
    const res = await adminApproveSendCountRequest({ id })
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '审核通过失败！',
        content: res?.msg ?? '请稍后再试'
      })
    }

    Notification.success({
      title: '操作成功',
      content: '该赠送申请已审核通过'
    })
    getList()
  } catch (error) {
    Notification.error({
      title: '审核通过失败！',
      content: error.message || '请稍后再试'
    })
  }
}

const openRejectModal = (id) => {
  rejectForm.id = id
  rejectForm.reason = ''
  rejectModalVisible.value = true
}

const handleRejectBeforeOk = async () => {
  try {
    const res = await adminRejectSendCountRequest({
      id: rejectForm.id,
      reject_reason: rejectForm.reason
    })

    if (!res || res.code !== 0) {
      Notification.error({
        title: '拒绝申请失败！',
        content: res?.msg ?? '请稍后再试'
      })
      return false
    }

    Notification.success({
      title: '操作成功',
      content: '该赠送申请已拒绝'
    })
    getList()
    return true
  } catch (error) {
    Notification.error({
      title: '拒绝申请失败！',
      content: error.message || '请稍后再试'
    })
    return false
  }
}

const handleRejectCancel = () => {
  rejectModalVisible.value = false
}

const search = () => {
  pagination.current = 1
  getList()
}

const reset = () => {
  pagination.current = 1
  queryData.status = ''
  getList()
}

const handlePageChange = (page) => {
  pagination.current = page
  getList()
}

const handlePageSizeChange = (size) => {
  pagination.pagesize = size
  pagination.current = 1
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.table {
  margin-top: 15px;
}
</style>
