<template>
    <div>
        <el-card shadow="never" class="!border-none">
            <el-page-header content="查看订单" @back="$router.back()" />
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="分销员名称" prop="distributorName">
                    <el-input class="w-[280px]" v-model="queryParams.distributorName" clearable />
                </el-form-item>
                <el-form-item label="分销员ID" prop="distNum">
                    <el-input class="w-[280px]" v-model="queryParams.distNum" clearable />
                </el-form-item>
                <el-form-item label="组别" prop="groupName">
                    <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="categoryId">
                    <el-cascader
                        ref="cascaderRef"
                        class="ls-input"
                        v-model="queryParams.categoryId"
                        :options="categoryData"
                        :props="{
                            checkStrictly: true,
                            label: 'name',
                            value: 'id',
                            children: 'sons',
                            emitPath: false
                        }"
                        clearable
                        filterable
                    />
                </el-form-item>
                <el-form-item label="订单完成时间">
                    <daterange-picker
                        class="w-[385px]"
                        v-model:startTime="queryParams.finishStartTime"
                        v-model:endTime="queryParams.finishEndTime"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getLists">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <el-button :disabled="isDisabled" type="primary" @click="handleExportExcel">
                导出订单
            </el-button>
            <div class="mt-3">
                <el-table ref="tableRef" class="mt-4" size="large" :data="pager.lists">
                    <el-table-column label="订单编号" prop="sn" width="200" />
                    <el-table-column label="服务分类" prop="categoryName" />
                    <el-table-column
                        label="服务名称"
                        prop="goodsName"
                        showOverflowTooltip
                    ></el-table-column>
                    <el-table-column label="商品数量" prop="totalNum" />
                    <el-table-column label="订单金额" prop="totalAmount" />
                    <el-table-column label="实付金额" prop="orderAmount" />
                    <el-table-column
                        label="订单完成时间"
                        width="200"
                        prop="finishTime"
                    ></el-table-column>
                    <el-table-column
                        label="分销员ID"
                        width="200"
                        prop="distNum"
                        :formatter="row => parseEmpty(row, 'distNum')"
                    ></el-table-column>
                    <el-table-column
                        label="分销员名称"
                        prop="distributorName"
                        :formatter="row => parseEmpty(row, 'distributorName')"
                    />
                    <el-table-column
                        label="组别"
                        prop="groupName"
                        :formatter="row => parseEmpty(row, 'groupName')"
                    />
                    <el-table-column
                        label="服务抽佣比"
                        prop="goodsCommissionRate"
                        :formatter="row => parseEmpty(row, 'goodsCommissionRate', '%')"
                    />
                    <el-table-column
                        label="最终抽佣比"
                        prop="ultimatelyCommissionRate"
                        :formatter="row => parseEmpty(row, 'ultimatelyCommissionRate', '%')"
                    />
                    <el-table-column
                        label="抽佣金额"
                        prop="commission"
                        :formatter="row => parseEmpty(row, 'commission', '元')"
                    />
                </el-table>
                <!-- <el-table-v2 :columns="columns" :data="tableData" :width="1600" :height="500" fixed /> -->
            </div>
            <div class="total mt-3">
                <span>订单总额：{{ pager.totalOrderAmount }}元</span>
                <span>实付总额：{{ pager.actualPaymentTotal }}元</span>
                <span>抽佣总额：{{ pager.totalCommissionAmount }}元</span>
            </div>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
    </div>
</template>

<script setup lang="tsx">
import type { ElCascader } from 'element-plus'
import { usePaging } from '@/hooks/usePaging'
import { streamFileDownload } from '@/utils/file'
import feedback from '@/utils/feedback'
import { parseEmpty } from '@/utils/util'
import { apiCategoryCommonLists } from '@/api/service/category'
import {
    apiDistributorDetail,
    apiDistributorExcel,
    apiDistributorQrder
} from '@/api/distributor/lists'
import { apiDistributorGroupLists } from '@/api/distributor/group'
import type { DistributorGroup } from '@/api/distributor/group'

const route = useRoute()
const id = route.query.id

const cascaderRef = ref<InstanceType<typeof ElCascader>>()

const detailInfo = ref<Record<string, string>>({})
const categoryData = ref<any>([])
const queryParams = reactive<Record<string, any>>({})

const { pager, getLists, resetPage } = usePaging({
    fetchFun: apiDistributorQrder,
    params: queryParams
})

const totalPrice = computed(() => pager?.sum)
const isDisabled = computed(() => pager.lists.length === 0)

/**重置参数 */
const handleReset = () => {
    const filedMap: Record<string, string> = {
        distributorName: 'name',
        groupId: 'groupId',
        distNum: 'distNum'
    }
    Object.keys(queryParams).forEach(key => {
        if (key == 'distributorName' || key == 'distNum' || key == 'groupId') {
            queryParams[key] = detailInfo.value[filedMap[key]]
        } else {
            queryParams[key] = ''
        }
    })
    getLists()
}
/**导出订单 */
const handleExportExcel = async () => {
    await feedback.confirm('确定要导出全部订单？')
    const params = {
        distributorName: queryParams.distributorName,
        distNum: queryParams.distNum,
        groupId: queryParams.groupId,
        categoryId: queryParams.categoryId
    }
    const file = await apiDistributorExcel(params)
    streamFileDownload(file, '订单', 'application/vnd.ms-excel')
}
/**获取详情 */
async function getDetail() {
    const filedMap: Record<string, string> = {
        distributorName: 'name',
        groupId: 'groupId',
        distNum: 'distNum',
        categoryId: 'categoryName',
        finishStartTime: 'finishStartTime',
        finishEndTime: 'finishEndTime'
    }
    const res = await apiDistributorDetail({ id })
    detailInfo.value = res
    Object.keys(filedMap).forEach(key => {
        queryParams[key] = res[filedMap[key]] ?? ''
    })
}
/**获取分类通用列表 */
const getCategoryLists = async () => {
    categoryData.value = await apiCategoryCommonLists()
}
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()
}

onMounted(async () => {
    getCategoryLists()
    await getDetail()
    getLists()
    getGroupList()
})
</script>
<style lang="scss" scoped>
.total {
    > span {
        margin-right: 60px;
    }
}
</style>
