<template>
    <div class="default-main ba-table-box">
        <MallPageIntro page-key="order" />
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('mall.order.quick Search Fields') })"
        ></TableHeader>

        <Table ref="tableRef"></Table>

        <PopupForm />
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { baTableApi } from '/@/api/common'
import createAxios from '/@/utils/axios'
import MallPageIntro from '/@/components/mall/MallPageIntro.vue'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import PopupForm from './popupForm.vue'
import { defaultOptButtons } from '/@/components/table'

defineOptions({
    name: 'mall/order',
})

const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')

const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete']).map((btn) =>
    btn.name === 'edit'
        ? {
              ...btn,
              title: t('mall.order.approve'),
              type: 'primary',
              class: 'table-row-edit',
              icon: 'fa fa-check',
              display: (row: TableRow) => ['PHYSICAL', 'WITHDRAW'].includes(String(row.type)) && row.status === 'PENDING',
          }
        : btn
)

const baTable = new baTableClass(
    new baTableApi('/admin/mall.Order/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('mall.order.id'), prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
            {
                label: t('mall.order.user_id'),
                prop: 'user_id',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                sortable: false,
                operator: 'LIKE',
                formatter: (row: TableRow, _column: TableColumn, cellValue: string) => {
                    const r = row as Record<string, unknown>
                    const rel = r.mallUserAsset ?? r.mall_user_asset
                    if (rel && typeof rel === 'object' && 'username' in rel) {
                        const u = (rel as { username?: unknown }).username
                        if (typeof u === 'string' && u.trim() !== '') {
                            return u
                        }
                    }
                    return (cellValue ?? row.user_id ?? '').toString()
                },
            },
            {
                label: t('mall.order.type'),
                prop: 'type',
                align: 'center',
                effect: 'light',
                custom: { BONUS: 'success', PHYSICAL: 'primary', WITHDRAW: 'info' },
                minWidth: 140,
                operator: 'eq',
                sortable: false,
                render: 'tag',
                replaceValue: {
                    BONUS: t('mall.order.type BONUS'),
                    PHYSICAL: t('mall.order.type PHYSICAL'),
                    WITHDRAW: t('mall.order.type WITHDRAW'),
                },
            },
            {
                label: t('mall.order.status'),
                prop: 'status',
                align: 'center',
                effect: 'dark',
                custom: { PENDING: 'success', COMPLETED: 'primary', SHIPPED: 'info', REJECTED: 'loading' },
                minWidth: 100,
                operator: 'eq',
                sortable: false,
                render: 'tag',
                replaceValue: {
                    PENDING: t('mall.order.status PENDING'),
                    COMPLETED: t('mall.order.status COMPLETED'),
                    SHIPPED: t('mall.order.status SHIPPED'),
                    REJECTED: t('mall.order.status REJECTED'),
                },
            },
            {
                label: t('mall.order.mall_item_id'),
                prop: 'mall_item_id',
                align: 'center',
                show: false,
                operator: 'RANGE',
                sortable: false,
            },
            {
                label: t('mall.order.mallitem__title'),
                prop: 'mallItem.title',
                align: 'center',
                minWidth: 90,
                operatorPlaceholder: t('Fuzzy query'),
                sortable: false,
                operator: 'LIKE',
            },
            { label: t('mall.order.points_cost'), prop: 'points_cost', align: 'center', minWidth: 90, operator: 'RANGE', sortable: false },
            { label: t('mall.order.amount'), prop: 'amount', align: 'center', minWidth: 90, operator: 'RANGE', sortable: false },
            { label: t('mall.order.multiplier'), prop: 'multiplier', align: 'center', minWidth: 90, operator: 'eq', sortable: false },
            {
                label: t('mall.order.external_transaction_id'),
                prop: 'external_transaction_id',
                align: 'center',
                minWidth: 80,
                showOverflowTooltip: true,
                operatorPlaceholder: t('Fuzzy query'),
                sortable: false,
                operator: 'LIKE',
            },
            {
                label: t('mall.order.grant_status'),
                prop: 'grant_status',
                align: 'center',
                minWidth: 100,
                custom: {
                    NOT_SENT: 'info',
                    SENT_PENDING: 'primary',
                    ACCEPTED: 'primary',
                    FAILED_RETRYABLE: 'error',
                    FAILED_FINAL: 'error',
                    '---': 'info',
                },
                operator: 'eq',
                sortable: false,
                render: 'tag',
                replaceValue: {
                    NOT_SENT: t('mall.order.grant_status NOT_SENT'),
                    SENT_PENDING: t('mall.order.grant_status SENT_PENDING'),
                    ACCEPTED: t('mall.order.grant_status ACCEPTED'),
                    FAILED_RETRYABLE: t('mall.order.grant_status FAILED_RETRYABLE'),
                    FAILED_FINAL: t('mall.order.grant_status FAILED_FINAL'),
                    '---': t('mall.order.grant_status ---'),
                },
            },
            {
                label: t('mall.order.fail_reason'),
                prop: 'fail_reason',
                align: 'center',
                minWidth: 140,
                render: 'failReason',
                operatorPlaceholder: t('Fuzzy query'),
                sortable: false,
                operator: 'LIKE',
            },
            {
                label: t('mall.order.reject_reason'),
                prop: 'reject_reason',
                align: 'center',
                minWidth: 140,
                render: 'failReason',
                sortable: false,
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: t('mall.order.shipping_company'),
                prop: 'shipping_company',
                align: 'center',
                showOverflowTooltip: true,
                sortable: false,
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: t('mall.order.shipping_no'),
                prop: 'shipping_no',
                align: 'center',
                showOverflowTooltip: true,
                sortable: false,
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: t('mall.order.receiver_name'),
                prop: 'receiver_name',
                align: 'center',
                showOverflowTooltip: true,
                sortable: false,
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: t('mall.order.receiver_phone'),
                prop: 'receiver_phone',
                align: 'center',
                showOverflowTooltip: true,
                sortable: false,
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: t('mall.order.receiver_address'),
                prop: 'receiver_address',
                align: 'center',
                showOverflowTooltip: true,
                sortable: false,
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            { label: t('mall.order.mall_address_id'), prop: 'mall_address_id', align: 'center', width: 100, operator: 'eq', sortable: false },
            {
                label: t('mall.order.start_time'),
                prop: 'start_time',
                align: 'center',
                operator: 'RANGE',
                comSearchRender: 'datetime',
                sortable: 'custom',
                width: 160,
            },
            {
                label: t('mall.order.end_time'),
                prop: 'end_time',
                align: 'center',
                operator: 'RANGE',
                comSearchRender: 'datetime',
                sortable: 'custom',
                width: 160,
            },
            {
                label: t('mall.order.create_time'),
                prop: 'create_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                comSearchRender: 'datetime',
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            {
                label: t('mall.order.update_time'),
                prop: 'update_time',
                align: 'center',
                show: false,
                render: 'datetime',
                operator: 'RANGE',
                comSearchRender: 'datetime',
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            {
                label: t('Operate'),
                align: 'center',
                width: 120,
                fixed: 'right',
                render: 'buttons',
                buttons: [
                    ...optButtons,
                    {
                        render: 'confirmButton',
                        name: 'retry',
                        title: t('mall.order.manual_retry'),
                        text: '',
                        type: 'primary',
                        class: 'table-row-edit',
                        icon: 'fa fa-refresh',
                        display: (row: TableRow) =>
                            row.type === 'BONUS' &&
                            row.status === 'PENDING' &&
                            ['NOT_SENT', 'SENT_PENDING', 'FAILED_RETRYABLE', 'FAILED_FINAL'].includes(String(row.grant_status)),
                        popconfirm: {
                            title: t('mall.order.retry_confirm'),
                            confirmButtonText: t('Confirm'),
                            cancelButtonText: t('Cancel'),
                            confirmButtonType: 'primary',
                        },
                        click: async (row: TableRow) => {
                            await createAxios(
                                {
                                    url: '/admin/mall.Order/retry',
                                    method: 'post',
                                    data: {
                                        id: row.id,
                                    },
                                },
                                {
                                    showSuccessMessage: true,
                                }
                            )
                            await baTable.getData()
                        },
                    },
                ],
            },
        ],
        dblClickNotEditColumn: [undefined],
    },
    {
        defaultItems: {},
    }
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getData()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>
