<template>
    <el-card shadow="never" class="!border-none">
        <el-page-header :content="id ? '编辑师傅' : '新增师傅'" @back="$router.back()" />
    </el-card>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
        <el-card shadow="never" style="margin-top: 15px" class="!border-none">
            <!-- 用户绑定 -->
            <el-form-item label="绑定用户:" prop="userId">
                <user-select btn-text="选择用户" type="primary" v-model="formData.userId" :userVo="formData.userVo" :id="id"
                    v-model:userMobile="formData.mobile" :api="apiUserNotStaff" />
            </el-form-item>
            <el-form-item label="师傅编号:" prop="sn">
                <el-input class="w-56 ls-input" :disabled="true" v-model="formData.sn" placeholder="请输入师傅编号" />
            </el-form-item>
            <el-form-item label="师傅名称:" prop="name">
                <el-input class="w-56 ls-input" v-model="formData.name" placeholder="请输入师傅的真实姓名" />
            </el-form-item>
            <el-form-item label="性别:" prop="sex">
                <el-radio v-model="formData.sex" name="1" :label="1">男</el-radio>
                <el-radio v-model="formData.sex" name="2" :label="2">女</el-radio>
            </el-form-item>
            <!-- 服务项目 -->
            <el-form-item label="服务项目" prop="goodsIds">
                <el-select v-model="formData.goodsIds" placeholder="请选择" class="ls-input" clearable multiple>
                    <el-option v-for="category in categoryLists" :key="category.id" :label="category.name"
                        :value="category.id"></el-option>
                </el-select>
            </el-form-item>
            <!-- <div class="serviceItem">
                <el-form-item label="服务项目:" prop="goodsIds">
                    <service-select v-model="formData.goodsIds" v-model:selectData="formData.goodsCategoryList">
                        <template #popup>
                            <el-button type="primary">选择服务</el-button>
                        </template>
                    </service-select>
                </el-form-item>
            </div> -->
            <!-- 服务区域 -->
            <!-- <div class="serviceItem">
                <el-form-item label="服务区域:" prop="serviceAreaIds">
                    <service-area v-model="formData.serviceAreaIds" v-model:selectData="formData.serviceArea">
                        <template #popup>
                            <el-button type="primary">选择区域</el-button>
                        </template>
                    </service-area>
                </el-form-item>
            </div> -->
            <!-- 手机号码 -->
            <el-form-item label="手机号码:" prop="mobile">
                <el-input class="w-56 ls-input" v-model="formData.mobile" placeholder="请输入手机号码" />
            </el-form-item>
            <!-- 所在地区 -->
            <el-form-item label="所在地区:" prop="districtId">
                <area-select class="w-56 ls-input" v-model:province="formData.provinceId" v-model:city="formData.cityId"
                    v-model:district="formData.districtId" />
            </el-form-item>
            <el-form-item label="详细地址:">
                <el-input class="ls-input" type="textarea" v-model="formData.address" placeholder="选填，请输入详细地址"
                    :rows="6"></el-input>
            </el-form-item>
            <el-form-item label="接单状态:" prop="isReceiveOrder">
                <el-switch v-model="formData.isReceiveOrder" :active-text="!formData.isReceiveOrder ? '启用' : '停用'"
                    :active-value="0" :inactive-value="1" />
            </el-form-item>
            <el-form-item label="运营师傅:">
                <el-switch v-model="formData.isOperational" :active-value="1" :inactive-value="0"
                    :active-text="formData.isOperational ? '是' : '否'" />
            </el-form-item>
            <el-form-item label="工作时间" prop="workStartTime" v-if="formData.isOperational === 1">
                <el-time-picker v-model="formData.workStartTime" placeholder="开始时间" value-format="HH:mm" format="HH:mm"
                    class="h-[45px]" />
                <el-time-picker v-model="formData.workEndTime" placeholder="结束时间" value-format="HH:mm" format="HH:mm"
                    class="h-[45px]" />
            </el-form-item>
            <!-- <el-form-item label="首页推荐:">
                <el-radio v-model="formData.isRecommend" name="1" :label="1">推荐</el-radio>
                <el-radio v-model="formData.isRecommend" name="0" :label="0">不推荐</el-radio>
            </el-form-item> -->
        </el-card>
    </el-form>
    <footer-btns>
        <el-button type="primary" @click="onSubmit(formRef)">保存</el-button>
    </footer-btns>
</template>

<script lang="ts" setup>
import { apiMasterWorkerAdd, apiMasterWorkerEdit, apiMasterWorkerDetail, apiMasterWorkerAreaAdd, apiMasterWorkerArea } from '@/api/master_worker'
import { ref, reactive } from 'vue'
import FooterBtns from '@/components/footer-btns/index.vue'
import UserSelect from '@/components/user-select/index.vue'
import AreaSelect from '@/components/area-select/index.vue'
import ServiceSelect from '@/components/service-select/index.vue'
import ServiceArea from '@/components/service-area/index.vue'
import type { ElForm } from 'element-plus'
import feedback from '@/utils/feedback'
import { apiUserNotStaff } from '@/api/master_worker'
import { validateWorkTime } from '@/utils/validate'
import { useCommon } from '@/hooks/useCommon'

/** Interface Start **/
interface formDataObj {
    userId?: number | string //用户id
    user?: object //用户id
    name?: string //师傅姓名
    sn?: string //师傅姓名
    sex?: number | string //性别
    mobile?: number | string //手机号码
    goods?: any //服务项目
    goodsIds: Array<any> //服务项目
    goodsList: any
    goodsCategoryList: any[]
    provinceId: number | string //省
    cityId: number | string //市
    districtId: number | string //区
    address: string //详细地址
    longitude: string //经度
    latitude: string //纬度
    status: number //状态
    isRecommend?: number //是否推荐
    serviceArea?: any[]
    serviceAreaIds: any
    userVo?: object
    isReceiveOrder: any
    workStartTime: string
    workEndTime: string
    isOperational: number
}
type FormInstance = InstanceType<typeof ElForm>
const formRef = ref<FormInstance>()
/** Interface End **/

/** Data Start **/
const { fetchCategoryList, categoryLists } = useCommon()

const route = useRoute()
const router = useRouter()
const id: any = route.query.id
const formData = ref<formDataObj>({
    userId: '', //用户id
    name: '', //师傅姓名
    sn: '', // 师傅编号
    sex: 1, //性别
    mobile: '', //手机号码
    goodsIds: [], //服务项目
    goodsList: [],
    goodsCategoryList: [],
    goods: [],
    provinceId: 440000, //省
    cityId: 440100, //市
    districtId: 440118, //区
    address: '', //详细地址
    longitude: '111', //经度 暂时不用
    latitude: '111', //纬度  暂时不用
    status: 0, //状态
    isRecommend: 0, //是否推荐
    serviceArea: [],
    serviceAreaIds: [],
    isReceiveOrder: '',
    workStartTime: '',
    workEndTime: '',
    isOperational: 0
})
// 表单校验规则
const rules = reactive<object>({
    userId: [{ required: true, message: '请选择用户', trigger: [] }],
    name: [{ required: true, message: '请输入师傅名称', trigger: 'blur' }],
    sn: [{ required: true, message: '请输入师傅编号', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择性别', trigger: ['blur', 'change'] }],
    goodsIds: [{ required: true, message: '请选择服务项目', trigger: [] }],
    mobile: [
        { required: true, message: '请输入手机号', trigger: ['blur'] },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号码输入有误', trigger: ['blur'] }
    ],
    districtId: [{ required: true, message: '请选择地区', trigger: ['blur', 'change'] }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    workStartTime: [
        { required: true, message: '请选择工作时间', trigger: 'blur' },
        { validator: (...args) => validateWorkTime(args, unref(formData)), trigger: 'blur' }
    ]
})

// 获取详情
const getMasterWorkerDetail = async (id: number): Promise<void> => {
    ; (formData.value as {}) = await apiMasterWorkerDetail({ id })
    if (!formData.value.goodsCategoryList.length) return
    formData.value.goodsIds = formData.value.goodsCategoryList.map(category => category.id)
}
const getMasterWorkerAreaDetail = async () => {
    formData.value.serviceArea = await apiMasterWorkerArea({ staffId: formData.value.userId })
}

// 添加师傅（编辑师傅）和单独区域
const handleAddOrEdit = async (id: number) => {
    const goodsCategoryIds = formData.value.goodsIds.join(',')
    // const serviceAreaIds = formData.value.serviceAreaIds.join(',')
    const serviceAreaIds = formData.value.serviceAreaIds.map((serviceAreaId: number) => ({
        staffId: formData.value.userId,
        serviceAreaId
    }))
    const api = !id ? apiMasterWorkerAdd : apiMasterWorkerEdit
    await api({ ...formData.value, goodsCategoryIds })
    router.back()
    feedback.msgSuccess('操作成功')
}

// 提交数据
const onSubmit = (formEl: FormInstance | undefined): void => {
    formData.value.serviceAreaIds = formData.value.serviceArea?.map(item => item.id)
    if (!formEl) return
    formEl.validate((valid): boolean | undefined => {
        if (!valid) return false
        if (unref(formData).isOperational === 0) {
            unref(formData).workEndTime = ''
            unref(formData).workStartTime = ''
        }
        handleAddOrEdit(id)
    })
}
// const handleStatusChange = () => {
//     formData.value.isReceiveOrder = unref(formData).isReceiveOrder == 0 ? 1 : 0
//     return true
// }
// 请求详情 => 如果是编辑的话
onMounted(async () => {
    if (id) {
        fetchCategoryList()
        await getMasterWorkerDetail(id)
        getMasterWorkerAreaDetail()
    }
})
</script>

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

.serviceItem :deep() .el-form-item__content {
    display: block;
}

.serviceItem :deep() .dialog__trigger {
    width: 80px;
}
</style>
