<template>
    <ProDialog ref="proDialogRef" :showConfirmButton="false" @handle-cancel="handleCancel">
        <template #header>
            <div class="flex gap-[40px] flex-1 mb-[6px]">
                <div class="item relative" v-for="item in positionOptions" :key="item.id" @click="postId = item.id">
                    <span :class="{ active: postId == item.id }">{{ item.name + '业绩排名榜' }}</span>
                </div>
            </div>
        </template>
        <div class="flex mb-[16px]">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="">
                    <el-tree-select
                        v-model="queryParams.organizationId"
                        :props="defaultProps"
                        default-expand-all
                        :data="organizationList"
                        :render-after-expand="false"
                    />
                </el-form-item>
                <el-form-item label="">
                    <daterange-picker
                        type="datetimerange"
                        format="YYYY-MM-DD HH:mm:ss"
                        isDisabledDate
                        isDisabledHours
                        :shortcuts="shortcuts"
                        v-model:startTime="queryParams.createTimeStart"
                        v-model:endTime="queryParams.createTimeEnd"
                    />
                </el-form-item>
                <el-form-item label="">
                    <el-cascader v-model="selectedUserId" :props="CascaderProps" :options="userList" @change="handleCascaderChange" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <ProTable v-if="isRrefresh" ref="proTableRef" :columns="columns" :tableData="tableData" :loading="loading" :maxHeight="530"></ProTable>
        <div class="flex justify-end mt-[10px]">
            <pagination v-model="pager" @change="fetchData" layout="total, prev, pager, next, jumper" class="mb-[10px]" />
        </div>
    </ProDialog>
</template>

<script setup lang="ts">
import ProDialog, { type IParams } from '@/components/ProDialog/index.vue'
import { usePositionData, useWorkbench } from '@/hooks/useCommon'
import { rankMoreListApi } from '@/api/workbench'
import { getCurDate, shortcuts } from '@/utils/util'
import { templateTypeEum } from '@/enums'

const { positionOptions, postId, fetchPostionData } = usePositionData()

const pager = ref({
    page: 1,
    size: 10,
    count: 0
})
const proDialogRef = ref<InstanceType<typeof ProDialog>>()
const loading = ref(false)
const proTableRef = ref()
const tableData = ref<any[]>([])
const parseLabel = computed(() => (postId.value === templateTypeEum.TELE ? '意向客户数' : '成交客户数'))
const columns = ref<any[]>([])
const queryParams = ref()
const initialVal = ref()
const { defaultProps, CascaderProps, organizationList, userList, fetchOrganizationList, fetchAllUserList } = useWorkbench(id => {
    initialVal.value = id
})
const selectedUserId = ref([])
const isRrefresh = ref(true) // 解决columns不更新
const openDialog = async (params: IParams) => {
    queryParams.value = params.data
    await fetchPostionData()
    fetchOrganizationList()
    fetchAllUserList()
    columns.value = generateColumns()
    fetchData()
    proDialogRef.value?.openDialog(params)
}
const fetchData = async () => {
    loading.value = true
    isRrefresh.value = false
    try {
        const newParams = {
            ...queryParams.value,
            post: postId.value ?? queryParams.value.post
        }
        columns.value = generateColumns()
        const result = await rankMoreListApi(newParams)
        tableData.value = result.lists ?? []
        pager.value = {
            page: result.pageNo,
            size: result.pageSize,
            count: result.count
        }
    } catch (error) {}
    loading.value = false
    isRrefresh.value = true
}
const handleCancel = (callback: () => void) => {
    callback()
}
const generateColumns = () => {
    return [
        { prop: 'rank', label: '排名' },
        { prop: 'username', label: '账号名称' },
        { prop: 'clueCount', label: parseLabel.value }
    ]
}
watch(
    () => postId.value,
    async (newVal, oldVal) => {
        if (newVal !== oldVal) {
            fetchData()
        }
    }
)
const resetPage = () => {
    fetchData()
}
const resetParams = () => {
    queryParams.value = {
        organizationId: initialVal.value,
        createTimeStart: getCurDate('start').toString(),
        createTimeEnd: getCurDate('end').toString(),
        userId: ''
    }
    selectedUserId.value = []
    fetchData()
}
const handleCascaderChange = value => {
    const lastVal = value[value.length - 1]
    queryParams.value = {
        ...queryParams.value,
        userId: lastVal.toString()
    }
}

defineExpose({
    openDialog
})
</script>
<style scoped lang="scss">
.item {
    position: relative;
    cursor: pointer;
    > span {
        &.active {
            position: relative;
            color: var(--el-color-primary);
            &::after {
                content: '';
                position: absolute;
                bottom: -10px;
                left: 50%;
                transform: translateX(-50%);
                width: 46px;
                height: 3px;
                border-radius: 3px;
                background-color: var(--el-color-primary);
            }
        }
    }
    .active {
    }
}
</style>
