<template>
    <div class="distributor-lists">
        <el-card class="!border-none" shadow="never">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="分销员名称" prop="name">
                    <el-input class="w-[280px]" v-model="queryParams.name" clearable />
                </el-form-item>
                <el-form-item label="组别" prop="groupId">
                    <el-select class="w-[280px]" v-model="queryParams.groupId">
                        <el-option label="全部" value="" />
                        <el-option v-for="option in groupData" :key="option.id" :label="option.groupName"
                            :value="option.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分销状态" prop="isStop">
                    <el-select class="w-[280px]" v-model="queryParams.status">
                        <el-option label="全部" value="" />
                        <el-option v-for="option in optionMap.accountStatus" :key="option.value" :label="option.label"
                            :value="option.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getLists">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <el-button type="primary" @click="$router.push('add')">
                <template #icon>
                    <icon name="el-icon-Plus" />
                </template>
                新增
            </el-button>
            <el-button type="danger" @click="handleDelete()" :disabled="isDisabled">批量删除</el-button>
            <el-dropdown class="ml-3" @command="handleCommand">
                <el-button type="default">
                    导出
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="exportSelect">导出所选</el-dropdown-item>
                        <el-dropdown-item command="exportAll">导出全部</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>

            <div class="mt-3">
                <el-table ref="tableRef" class="mt-4" size="large" v-loading="loading" :data="pager.lists" row-key="id"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" :reserve-selection="true" />
                    <el-table-column label="分销员名称" prop="name" />
                    <el-table-column label="ID号" prop="distNum"></el-table-column>
                    <el-table-column label="联系方式" prop="contact" :formatter="row => parseEmpty(row, 'contact')"
                        width="120" />
                    <el-table-column label="分销码有效期" width="200" prop="effectTime"
                        :formatter="parseEffectTime"></el-table-column>
                    <el-table-column label="分销用户量" prop="bindUserNum" />
                    <el-table-column label="组别" prop="groupName" />
                    <el-table-column label="分销状态" prop="status" :formatter="parseStatus" />
                    <el-table-column prop="getType" label="金额详情" min-width="110">
                        <template #default="{ row }">
                            <MoneyDetailDialog btn-text="金额详情" :rowData="row" />
                        </template>
                    </el-table-column>
                    <el-table-column label="分销抽佣比" prop="commissionRate"
                        :formatter="row => addUnit(row.commissionRate, '%')" />
                    <el-table-column label="操作" width="200" fixed="right">
                        <template #default="{ row }">
                            <router-link class="mr-2" :to="{
                                path: 'edit',
                                query: {
                                    id: row.id
                                }
                            }">
                                <el-link type="primary" :underline="false">编辑</el-link>
                            </router-link>

                            <el-button v-perms="['system:distributor:del']" type="danger" link
                                @click="handleDelete(row)">删除</el-button>

                            <el-dropdown class="more">
                                <span class="el-dropdown-link">
                                    更多
                                    <el-icon class="el-icon--right">
                                        <arrow-down />
                                    </el-icon>
                                </span>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item
                                            @click="handleViewOperation(row, 'user')">查看绑定用户</el-dropdown-item>
                                        <el-dropdown-item
                                            @click="handleViewOperation(row, 'order')">查看分销订单</el-dropdown-item>
                                        <el-dropdown-item @click="handleViewQrcode(row)">查看二维码</el-dropdown-item>
                                        <el-dropdown-item
                                            @click="handleViewOperation(row, 'coupon')">查看优惠券</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
    </div>
    <qrcode-dialog ref="qrcodeRef" />
</template>

<script lang="ts" setup name="distributorList">
import { reactive, ref } from 'vue'
import type { ElTable, FormInstance } from 'element-plus'
import QrcodeDialog from './components/QrcodeDialog.vue'
import Pagination from '@/components/pagination/index.vue'
import { usePaging } from '@/hooks/usePaging'
import { useRequest } from '@/hooks/useFetchData'
import { apiDistributorDel, apiDistributorLists, apiDistributorQrcode } from '@/api/distributor/lists'
import { statusMap } from '@/enums/modeEnum'
import { toast, parseEmpty, addUnit } from '@/utils/util'
import feedback from '@/utils/feedback'
import { optionMap } from '@/config/status'
import type { Distributor } from './interface'
import { apiDistributorGroupLists } from '@/api/distributor/group'
import type { DistributorGroup } from '@/api/distributor/group'
import MoneyDetailDialog from '@/components/money-detail/moneyDetailDialog.vue'
import { batchExport, type Column } from '@/utils/table2excel'

const router = useRouter()

const tableRef = ref<InstanceType<typeof ElTable>>()
const formRef = ref<FormInstance>()
const loading = ref(false)
const selectedIds = ref<number[]>([])
const selectedItems = ref<Distributor[]>([])
const qrcodeRef = ref()
const queryParams = reactive({
    status: '',
    groupId: '',
    name: ''
})

const clearSelection = () => {
    tableRef.value?.clearSelection()
}

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: apiDistributorLists,
    params: queryParams,
    nextFetchFun: clearSelection
})

getLists()

const isDisabled = computed(() => !selectedIds.value.length)

/**多选操作 */
const handleSelectionChange = (val: Distributor[]) => {
    selectedIds.value = val.map(item => item.id) as number[]
    selectedItems.value = val
}
/**删除 */
const handleDelete = (row?: Distributor) => {
    row && tableRef.value?.toggleRowSelection(row, true)
    feedback
        .confirm('确定要删除？')
        .then(() => {
            const { runFn } = useRequest({
                apiFn: apiDistributorDel,
                onSuccess: res => {
                    feedback.msgSuccess('删除成功')
                    getLists()
                    tableRef.value?.clearSelection()
                }
            })
            runFn({ ids: !row ? selectedIds.value : [row?.id] })
        })
        .catch(() => {
            toast('取消删除', 'warning')
        })
}

/**查看用户和查看订单和查看优惠券 */
const handleViewOperation = (row: Distributor, type: string) => {
    const path = type === 'user' ? '/distributor/register' : type === 'coupon' ? '/distributor/coupon' : '/distributor/order'
    router.push({
        path,
        query: {
            id: row.id
        }
    })
}
/**查看二维码 */
const handleViewQrcode = (row: Distributor) => {
    const params = {
        title: '查看二维码',
        rawData: { ...row },
        api: apiDistributorQrcode
    }
    qrcodeRef.value.acceptParams(params)
}

/**对table字段的分销码和分校状态格式化 */
function parseEffectTime(row: Distributor) {
    return `${row.validStartTime}至${row.validEndTime}`
}
function parseStatus(row: Distributor) {
    return statusMap[row.status]
}

const groupData = ref<DistributorGroup[]>([])
// 获取分类通用列表
const getGroupList = (): void => {
    let pageNo = 1
    async function request() {
        const res = await apiDistributorGroupLists({ pageNo, pageSize: 60 })
        groupData.value.push(...res.lists)
        if (groupData.value.length < res.count) {
            pageNo++
            request()
        }
    }
    request()
}

const handleCommand = async (command: string | number | object) => {
    const column: Column[] = [
        {
            title: '分销员名称',
            key: 'name'
        },
        {
            title: 'ID号',
            key: 'distNum'
        },
        {
            title: '联系方式',
            key: 'contact',
            width: 150
        },
        {
            title: '分销码有效期',
            key: 'effectTime',
            width: 200
        },
        {
            title: '分销用户量',
            key: 'bindUserNum',
            width: 150
        },
        {
            title: '组别',
            key: 'groupName'
        },
        {
            title: '分销状态',
            key: 'status'
        },
        {
            title: '已提现金额',
            key: 'alreadyWithdraw'
        },
        {
            title: '可提现金额',
            key: 'canWithdrawCommission'
        },
        {
            title: '待结算金额',
            key: 'toBeSettledMoney'
        },
        {
            title: '分销抽佣比',
            key: 'commissionRate'
        }
    ]
    let tableDatas = selectedItems.value || []
    if (command == 'exportAll') {
        const res = await apiDistributorLists({
            ...queryParams,
            pageNo: 1,
            pageSize: 9999
        })
        tableDatas = res.lists || []
    }
    if (tableDatas.length == 0) return toast('导出数据为空', 'error')
    tableDatas.map(item => {
        item.status = statusMap[item.status as number]
        item.effectTime = `${item.validStartTime}至${item.validEndTime}`
        item.commissionRate = item.commissionRate + '%'
        item.alreadyWithdraw = item.alreadyWithdraw + '元'
        item.canWithdrawCommission = item.canWithdrawCommission + '元'
        item.toBeSettledMoney = item.toBeSettledMoney + '元'
    })
    batchExport(column, tableDatas, '分销商列表')
}

getGroupList()
</script>

<style lang="scss" scoped>
.el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.more {
    margin-left: 20px;
    vertical-align: middle;
}
</style>
