<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" :limit="1" />
                </el-form-item>
                <el-form-item label="本人照片" prop="image">
                    <material-picker v-model="formData.image" :limit="9" />
                </el-form-item>
                <el-form-item label="茶艺师资格证书" prop="license_img">
                    <material-picker v-model="formData.license_img" :limit="1" />
                </el-form-item>
                <el-form-item label="健康证" prop="health_certificate">
                    <material-picker v-model="formData.health_certificate" :limit="1" />
                </el-form-item>
                <el-form-item label="身份证正面" prop="front_card">
                    <material-picker v-model="formData.front_card" :limit="1" />
                </el-form-item>
                <el-form-item label="身份证反面" prop="back_card">
                    <material-picker v-model="formData.back_card" :limit="1" />
                </el-form-item>
                <el-form-item label="专属圈子" prop="label_id">
                    <el-select v-model="formData.label_id" multiple placeholder="请选择" style="width: 240px">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="经纪人" prop="broker_user_id">
                    <el-select v-model="formData.broker_user_id" placeholder="请选择" style="width: 240px"
                        :disabled="Number(formData.broker_user_id) > 0 ? true : false">
                        <el-option v-for="item in brokerOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </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="name">
                    <el-input v-model="formData.name" clearable placeholder="请输入昵称" />
                </el-form-item>
                <el-form-item label="出生日期" prop="both">
                    <el-date-picker v-model="formData.both" type="date" placeholder="请选择" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="体重" prop="weight">
                    <el-input v-model="formData.weight" clearable placeholder="请输入体重" />
                </el-form-item>
                <el-form-item label="身高" prop="height">
                    <el-input v-model="formData.height" clearable placeholder="请输入身高" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="formData.sex" clearable placeholder="请选择">
                        <el-option label="女" :value="2"></el-option>
                        <el-option label="男" :value="1"></el-option>
                    </el-select>
                </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="mobile">
                    <el-input v-model="formData.mobile" clearable placeholder="请输入用户电话" />
                </el-form-item>
                <el-form-item label="茶艺师等级" prop="level">
                    <el-select class="flex-1" v-model="formData.level" clearable placeholder="请选择茶艺师等级">
                        <el-option v-for="(item, index) in dictData.level" :key="index" :label="item.name"
                            :value="parseInt(item.value)" />
                    </el-select>
                </el-form-item>
                <el-form-item label="星级" prop="star">
                    <el-input v-model="formData.star" clearable placeholder="请输入星级" />
                </el-form-item>
                <el-form-item label="服务单价" prop="price">
                    <el-input v-model="formData.price" clearable placeholder="请输入茶艺服务单价" />
                </el-form-item>
                <el-form-item label="车马费" prop="mileage_price">
                    <el-input v-model="formData.mileage_price" clearable placeholder="请输入车马费/每公里" />
                </el-form-item>
                <el-form-item label="是否免费出行" prop="is_mileage">
                    <el-select class="flex-1" v-model="formData.is_mileage" clearable placeholder="请选择">
                        <el-option label="免费" :value="1"></el-option>
                        <el-option label="收费" :value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="服务次数" prop="sold">
                    <el-input v-model="formData.sold" clearable placeholder="请输入服务次数" />
                </el-form-item>
                <el-form-item label="服务方式" prop="server_type">
                    <el-select class="flex-1" v-model="formData.server_type" clearable placeholder="请选择服务方式">
                        <el-option v-for="(item, index) in dictData.server_type" :key="index" :label="item.name"
                            :value="parseInt(item.value)" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属城市" prop="city_id">
                    <el-select v-model="formData.city_id" clearable placeholder="请选择">
                        <el-option :label="item.name" :value="item.id" v-for="item in cityList"
                            :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="地址" prop="longitude">
                    <el-input v-model="formData.address" clearable placeholder="请输入地址"
                        :disabled="mode == 'edit' ? true : false" />
                </el-form-item>
                <el-form-item label="经度" prop="longitude">
                    <el-input v-model="formData.longitude" clearable placeholder="请输入经度"
                        :disabled="mode == 'edit' ? true : false" />
                </el-form-item>
                <el-form-item label="纬度" prop="latitude">
                    <div class="flex items-center w-full">
                        <el-input v-model="formData.latitude" clearable placeholder="请输入纬度" class="flex-1 min-w-0"
                            :disabled="mode == 'edit' ? true : false" />
                        <a href="http://jingweidu.757dy.com/" target="open" class="ml-2 flex items-center">
                            <el-icon>
                                <Location />
                            </el-icon>
                        </a>
                    </div>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-select class="flex-1" v-model="formData.state" clearable placeholder="请选择">
                        <el-option label="可约" :value="0"></el-option>
                        <el-option label="不可约" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否禁用" prop="disable">
                    <el-select class="flex-1" v-model="formData.disable" clearable placeholder="请选择">
                        <el-option label="否" :value="0"></el-option>
                        <el-option label="是" :value="1"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="teamasterUserEdit">
import Popup from '@/components/popup/index.vue'
import { apiTeamasterUserAdd, apiTeamasterUserEdit, apiTeamasterUserDetail, apiLabel, apiBrokerList } from '@/api/teamaster_user'
import { timeFormat, removeImageUrlPrefix, normalizeImageUrl } from '@/utils/util'
import type { PropType } from 'vue'
import { apiTeaStoreCityLists } from '@/api/tea_store'
import type { FormInstance } from 'element-plus'
import { isArray } from 'lodash'


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 options = ref<{ label: string; value: string }[]>([])
const getLabel = async () => {
    try {
        const res = await apiLabel({})
        options.value = res.map((item: any) => ({ label: item.label_name, value: item.id }))
    } catch (e) {
        options.value = []
    }
}
getLabel()

// 获取经纪人列表
const brokerOptions = ref<{ label: string; value: string }[]>([])
const getBrokerList = async () => {
    try {
        const res = await apiBrokerList()
        brokerOptions.value = res.map((item: any) => ({ label: item.name, value: item.id }))
    } catch (e) {
        brokerOptions.value = []
    }
}
getBrokerList()

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑茶艺师' : '新增茶艺师'
})

// 表单数据
const formData = reactive({
    id: '',
    avatar: '',
    image: '',
    nickname: '',
    name: '',
    both: '',
    weight: '',
    height: '',
    sex: '',
    hobby_introduce: '',
    account: '',
    mobile: '',
    level: '',
    star: '',
    price: '',
    mileage_price: '',
    is_mileage: '',
    sold: '',
    server_type: '',
    address_id: 0,
    city_id: '',
    address: '',
    longitude: '',
    latitude: '',
    disable: '',
    state: '',
    user_money: '',
    license_img: '',
    information: '',
    health_certificate: '',
    label_id: '',
    broker_user_id: '',
    front_card: '',
    back_card: '',
})

// 城市列表
const cityList = ref<any[]>([])

onMounted(async () => {
    try {
        const res = await apiTeaStoreCityLists()
        cityList.value = res || []
    } catch (e) {
        cityList.value = []
    }
})


// 表单验证
const formRules = reactive<any>({})


// 获取详情
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]
        }
    }

    //@ts-ignore
    // formData.avatar = normalizeImageUrl(formData.avatar)
    formData.label_id = formData.label_id ? formData.label_id.split(',') : []
    if (isArray(formData.label_id)) {
        //@ts-ignore
        formData.label_id = formData.label_id.map((item: string) => Number(item))
    }
    console.log("🚀 ~ setFormData ~ formData.label_id:", formData.label_id)
    //@ts-ignore
    formData.information = formData.information ? formData.information.split(',') : ''
}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    let data = { ...formData, }
    data.avatar = removeImageUrlPrefix(data.avatar)
    data.image = removeImageUrlPrefix(data.image)
    data.image = Array.isArray(data.image) ? data.image.join(',') : ''
    data.license_img = removeImageUrlPrefix(data.license_img)
    data.information = removeImageUrlPrefix(data.information)
    data.information = Array.isArray(data.information) ? data.information.join(',') : ''
    data.health_certificate = removeImageUrlPrefix(data.health_certificate)
    data.front_card = removeImageUrlPrefix(data.front_card)
    data.back_card = removeImageUrlPrefix(data.back_card)
    data.label_id = Array.isArray(data.label_id) ? data.label_id.join(',') : ''
    // console.log("🚀 ~ handleSubmit ~ data:", data)
    // return

    if (mode.value == 'edit') {
        delete data.address
        delete data.longitude
        delete data.latitude
    }

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

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

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


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