<template>
    <popup class="mr-2 inline" :clickModalClose="false" :title="btnText" :center="true" :disabled="id !== ''"
        @close="handleClose(userFormRef)" @confirm="handleConfirm" width="1150px">
        <!-- Trigger Start -->
        <template #trigger>
            <!-- trigger -->
            <div v-if="!modelValue">
                <el-button type="primary">{{ btnText }}</el-button>
            </div>
            <div v-if="modelValue" class="flex items-center">
                <!-- userData.avatar || userVo.avatar -->
                <el-image style="width: 48px; height: 48px;border-radius: 50%;" :src="parseAvatarValue(userData)"
                    :fit="'cover'" />
                <div class="ml-2">{{ userData.nickname || userVo.nickname }}(用户编号{{ userData.sn || userVo.sn }})</div>
            </div>
        </template>
        <!-- Trigger End -->

        <!-- Form Start -->
        <el-form :model="userForm" ref="userFormRef" :inline="true" label-width="auto" @submit.native.prevent>
            <el-form-item label="用户信息">
                <el-input class="ls-input" v-model="userForm.keyword" placeholder="请输入用户编号/手机号码/用户昵称" clearable></el-input>
            </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>
        <!-- Form End -->

        <!-- Table Start -->
        <div>
            <el-table ref="tableDataRef" :data="pager.lists" border style="width: 100%">
                <el-table-column label="选择" width="60">
                    <template #default="scope">
                        <div class="flex justify-center">
                            <el-radio v-model="radio" :name="scope.row.id + ''" :label="scope.row.id">&nbsp;</el-radio>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column property="sn" :label="parseSnLabel" max-width="120" />
                <el-table-column :label="parseAvatarLabel" max-width="120">
                    <template #default="{ row }">
                        <el-image style="width: 48px; height: 48px" :src="parseAvatarValue(row)"
                            :fit="'contain'"></el-image>
                    </template>
                </el-table-column>
                <el-table-column property="mobile" label="手机号码" max-width="200"
                    :formatter="row => parseEmpty(row, 'mobile')" />
                <el-table-column property="nickname" :label="parseNameLabel" max-width="220">
                    <template #default="{ row }">
                        <span>{{ parseNameValue(row) }}</span>
                    </template>
                </el-table-column>
                <el-table-column property="createTime" label="注册时间" max-width="205"
                    :formatter="row => parseEmpty(row, 'createTime')" />
            </el-table>
        </div>
        <!-- Table End -->

        <div class="flex justify-end mt-2">
            <pagination v-model="pager" @change="getLists" />
        </div>
    </popup>
</template>

<script lang="ts" setup>
import { apiUserLists } from '@/api/user'
import Popup from '@/components/popup/index.vue'
import { ref, withDefaults } from 'vue'
import type { ElForm } from 'element-plus'
import Pagination from '@/components/pagination/index.vue'
import { usePaging } from '@/hooks/usePaging'
import { parseEmpty } from '@/utils/util'
import feedback from '@/utils/feedback'

interface userFormObj {
    keyword?: string
}

type FormInstance = InstanceType<typeof ElForm>
const userFormRef = ref<FormInstance>()

/** Props Start **/
const props = withDefaults(
    defineProps<{
        modelValue?: any
        userVo?: any
        id?: string | number
        btnText?: string
        userMobile?: any
        api?: (params: any) => Promise<any>
        binding: string
    }>(),
    {
        modelValue: '',
        userVo: {},
        id: '',
        btnText: '',
        userMobile: '',
        api: apiUserLists,
        binding: 'user'
    }
)
/** Props End **/

/** Emit Start **/
const emit = defineEmits(['update:modelValue', 'update:userMobile'])
/** Emit End **/

/** Data Start **/
const userForm = ref<userFormObj>({
    keyword: ''
})

const userData = ref<any>(props.userVo)
const radio = ref<number>(props.modelValue)
const fieldsMap: Record<string, any> = {
    'staff': {
        'name': '师傅姓名',
        'headPortrait': '师傅头像',
        'sn': '师傅编号'
    },
    'user': {
        'nickname': '用户昵称',
        'avatar': '用户头像',
        'sn': '用户编号'
    }
}
const fields = computed(() => Object.keys(fieldsMap[props.binding]))
const labels = computed(() => Object.values(fieldsMap[props.binding]))
const parseNameValue = computed(() => (row: any) => row[unref(fields)[0]])
const parseNameLabel = computed(() => unref(labels)[0])
const parseAvatarValue = computed(() => (row: any) => row[unref(fields)[1]])
const parseAvatarLabel = computed(() => unref(labels)[1])
const parseSnLabel = computed(() => unref(labels)[2])

const { pager, getLists, resetPage, resetParams } = usePaging({
    size: 10,
    fetchFun: props.api,
    params: userForm.value
})
/** Data End **/

/** Methods Start **/
// 弹窗关闭
const handleClose = (formEl: FormInstance | undefined): void => {
    if (!formEl) return
    formEl.resetFields()
}
// 确认选择
const handleConfirm = (): void => {
    console.log('radio', radio, pager.lists)
    if (!radio.value) {
        feedback.msgWarning(`请${props.btnText}！`)
        throw new Error(`没有${props.btnText}！`)
    }
    const row = pager.lists.filter(item => item.id == radio.value)
    userData.value = row[0]
    emit('update:modelValue', row[0]?.id)
    emit('update:userMobile', row[0]?.mobile)
}
/** Methods End **/

/** Life Cycle Start **/
getLists()
/** Life Cycle End **/
</script>

<style lang="scss" scoped>
.ls-input {
    width: 280px;
}

:deep(.el-table__inner-wrapper) {
    height: 565px;
    overflow-y: scroll;
    overflow-x: hidden;
}
</style>
