<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-form-item label="头像" prop="avatar">
                    <material-picker v-model="formData.avatar" />
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickname">
                    <el-input v-model="formData.nickname" clearable placeholder="请输入用户昵称" />
                </el-form-item>
                <el-form-item label="用户电话" prop="mobile">
                    <el-input v-model="formData.mobile" clearable placeholder="请输入用户电话" />
                </el-form-item>
                <el-form-item label="用户账号" prop="account">
                    <el-input v-model="formData.account" clearable placeholder="请输入用户账号" />
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-if="mode == 'add'">
                    <el-input v-model="formData.password" clearable placeholder="请输入用户密码" />
                </el-form-item>
                <el-form-item label="选择门店" prop="store_ids">
                    <el-select v-model="formData.store_ids" multiple filterable clearable placeholder="请选择门店"
                        @remove-tag="handleRemoveStore">
                        <el-option v-for="item in storeList" :key="item.id"
                            :label="item.name || item.store_name || item.nickname || `门店${item.id}`"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否禁用" prop="disable">
                    <el-select v-model="formData.disable" clearable placeholder="请选择">
                        <el-option label="启用" value="1"></el-option>
                        <el-option label="禁用" value="0"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="storeUserEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiStoreUserAdd, apiStoreUserEdit, apiStoreUserDetail } from '@/api/store_user'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { apiUserLists } from '@/api/store_user'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

// 门店列表
const storeList = ref<any[]>([])

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑门店管理员' : '新增门店管理员'
})

// 表单数据
const formData = reactive({
    id: '',
    sn: '',
    avatar: '',
    nickname: '',
    account: '',
    password: '',
    mobile: '',
    login_ip: '',
    login_time: '',
    disable: '',
    bind_user_id: '',
    store_ids: [] as any[],
    del_store_ids: ''
})

const formRules = reactive<any>({
    avatar: [
        {
            required: true,
            message: '请上传头像',
            trigger: 'blur'
        }
    ],
    nickname: [
        {
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
        }
    ],
    account: [
        {
            required: true,
            message: '请输入账号',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
        }
    ],
    mobile: [
        {
            required: true,
            message: '请输入电话',
            trigger: 'blur'
        }
    ],
    store_ids: [
        {
            required: true,
            message: '请选择门店',
            trigger: 'change'
        }
    ],
    disable: [
        {
            required: true,
            message: '请选择是否禁用',
            trigger: 'change'
        }
    ]
})

// 获取要绑定的门店列表
onMounted(async () => {
    try {
        const res = await apiUserLists()
        storeList.value = res || []
    } catch (e) {
        storeList.value = []
    }
})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    formData.disable = String(formData.disable)
    formData.store_ids = data.store_ids ? data.store_ids.split(',') : []
    if (Array.isArray(formData.store_ids)) {
        //@ts-ignore
        formData.store_ids = formData.store_ids.map((id: string) => Number(id))
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiStoreUserDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data: Record<string, any> = { ...formData }
    if (Array.isArray(data.store_ids)) {
        data.store_ids = data.store_ids.join(',')
    }

    mode.value == 'edit'
        ? await apiStoreUserEdit(data)
        : await apiStoreUserAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

// 处理门店删除
const handleRemoveStore = (removedId: number) => {
    if (!formData.del_store_ids) {
        formData.del_store_ids = String(removedId)
    } else {
        const existingIds = formData.del_store_ids.split(',')
        if (!existingIds.includes(String(removedId))) {
            formData.del_store_ids = formData.del_store_ids + ',' + removedId
        }
    }
}




defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
