<template>
    <el-card shadow="never" class="!border-none">
        <el-page-header content="新增师傅" @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"
                    v-model:userMobile="formData.mobile" :api="apiUserNotStaff" />
            </el-form-item>
            <el-form-item label="师傅全身照:" prop="avatarUploadList" class="star">
                <el-upload class="avatar-uploader" :class="{ hide: isHideAvatarUploadBtn }"
                    v-model:file-list="fileUploadList['avatar']" action="" list-type="picture-card" :auto-upload="false"
                    :limit="1"
                    @change="(file: UploadFile, fileList: UploadFiles) => startUpload(file, fileList, 'avatar', imageMaxSize)"
                    :before-remove="(file: UploadFile, fileList: UploadFiles) => beforeRemove(file, fileList, 'avatar')"
                    @preview="(file: UploadFile) => handlePreview(file, 'avatar')"
                    @exceed="(files: File[], uploadFiles: UploadUserFile[]) => handleExceed(files, uploadFiles, 'avatar')">
                    <el-icon class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="师傅姓名:" prop="name">
                <el-input class="w-56 ls-input" v-model="formData.name" placeholder="请输入师傅姓名" maxlength="64"
                    show-word-limit />
            </el-form-item>
            <el-form-item label="性别:" prop="sex">
                <el-radio-group v-model="formData.sex">
                    <el-radio v-for="option in optionMap.sexOptions" :label="option.value">{{ option.label }}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄:" prop="age">
                <el-input class="w-56 ls-input" v-model.number="formData.age" maxlength="3" placeholder="请输入年龄"
                    show-word-limit />
            </el-form-item>
            <el-form-item label="身份证号:" prop="idCard" class="star">
                <el-input class="w-56 ls-input" v-model="formData.idCard" placeholder="请输入身份证号" maxlength="18"
                    show-word-limit />
            </el-form-item>
            <el-form-item label="身份证正反面:" prop="fileUploadList" class="star">
                <el-upload class="avatar-uploader" :class="{ hide: isHideIdCardUploadBtn }"
                    v-model:file-list="fileUploadList['idCard']" action="" multiple list-type="picture-card"
                    :auto-upload="false" :limit="2"
                    @change="(file: UploadFile, fileList: UploadFiles) => startUpload(file, fileList, 'idCard', imageMaxSize)"
                    :before-remove="(file: UploadFile, fileList: UploadFiles) => beforeRemove(file, fileList, 'idCard')"
                    @preview="(file: UploadFile) => handlePreview(file, 'idCard')"
                    @exceed="(files: File[], uploadFiles: UploadUserFile[]) => handleExceed(files, uploadFiles, 'idCard')">
                    <el-icon class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </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>
            <!-- <el-form-item label="服务项目:" prop="goodsIds" class="star">
                <service-select v-model="formData.goodsIds" v-model:selectData="formData.goodsList">
                    <template #popup>
                        <el-button type="primary">选择服务</el-button>
                    </template>
                </service-select>
            </el-form-item> -->
            <el-form-item label="手机号码:" prop="mobile">
                <el-input class="w-56 ls-input" v-model="formData.mobile" placeholder="请输入手机号码" maxlength="11"
                    show-word-limit />
            </el-form-item>
            <el-form-item label="运营师傅:" prop="status">
                <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="所在地区:" 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="详细地址:" prop="address" class="star">
                <el-input class="ls-input" type="textarea" v-model="formData.address" placeholder="请输入详细地址" :rows="6"
                    maxlength="128" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="体检报告:" prop="">
                <div class="physical">
                    <el-upload class="pdf" ref="uploadPdf" action="#" :limit="1" :auto-upload="false"
                        @change="(file: UploadFile, fileList: UploadFiles) => startUpload(file, fileList, 'pdf', fileMaxSize)"
                        :before-remove="(file: UploadFile, fileList: UploadFiles) => beforeRemove(file, fileList, 'pdf')"
                        @exceed="(files: File[], uploadFiles: UploadUserFile[]) => handleExceed(files, uploadFiles, 'pdf')"
                        @preview="(file: UploadFile) => previewPdf(file)">
                        <template #trigger>
                            <el-button type="primary">上传pdf</el-button>
                        </template>
                    </el-upload>

                    <el-upload class="avatar-uploader" :class="{ hide: isHideReportUploadBtn }"
                        v-model:file-list="fileUploadList['report']" action="" multiple list-type="picture-card"
                        :auto-upload="false" :limit="9"
                        @change="(file: UploadFile, fileList: UploadFiles) => startUpload(file, fileList, 'report', imageMaxSize)"
                        :before-remove="(file: UploadFile, fileList: UploadFiles) => beforeRemove(file, fileList, 'report')"
                        @preview="(file: UploadFile) => handlePreview(file, 'report')"
                        @exceed="(files: File[], uploadFiles: UploadUserFile[]) => handleExceed(files, uploadFiles, 'report')">
                        <el-icon class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </div>
            </el-form-item>
        </el-card>
    </el-form>
    <footer-btns>
        <el-button type="primary" :disabled="isDisabled" @click="handleSubmit">保存</el-button>
    </footer-btns>

    <el-image-viewer v-if="imgViewerVisible" :urlList="previewSrcList" :initial-index="viewerIndex"
        @close="closeImageViewer" :hide-on-click-modal="true" />

    <PreviewPdfDialog ref="pdfDialog" />
</template>

<script setup lang="ts">
import { ElImageViewer, type FormRules, type UploadUserFile, type FormInstance, type UploadFile, type UploadFiles } from 'element-plus'
import { omit } from 'lodash-es'
import AreaSelect from '@/components/area-select/index.vue'
import ServiceSelect from '@/components/service-select/index.vue'
import { useCommon, useUploadMoreAction } from '@/hooks/useCommon'
import { optionMap } from '@/config/status'
import { apiMasterWorkerAdd, apiUploadFile } from '@/api/master_worker'
import { apiUserNotStaff } from '@/api/master_worker'
import feedback from '@/utils/feedback'
import {
    validateAvatarUploadList,
    validateContact,
    validateFileUploadList,
    validateGoodsIds,
    validateIdCard,
    validateLocation,
    validateAge,
    validateWorkTime
} from '@/utils/validate'
import PreviewPdfDialog from './components/previewPdfDialog.vue'

const router = useRouter()
const { fetchCategoryList, categoryLists } = useCommon()

const formData = ref({
    userId: '', //用户id
    userVo: {},
    goodsIds: [],
    age: '',
    address: '',
    name: '',
    sex: 1,
    idCard: '',
    mobile: '',
    cityId: 440100,
    districtId: 440118,
    provinceId: 440000,
    location: '',
    files: {
        idCard: [],
        report: [],
        pdf: [],
        avatar: []
    },
    goodsList: [],
    fileUploadList: {},
    avatarUploadList: '',
    workStartTime: '',
    workEndTime: '',
    isOperational: 0
})
const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
    userId: [{ required: true, message: '请选择用户', trigger: [] }],
    name: { required: true, message: '请输入师傅姓名', trigger: 'blur' },
    sex: { required: true, message: '请选择性别', trigger: 'change' },
    age: [
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { validator: validateAge, trigger: 'blur' }
    ],
    idCard: { validator: validateIdCard, trigger: 'blur' },
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validateContact, trigger: 'blur' }
    ],
    goodsIds: [{ required: true, validator: validateGoodsIds, trigger: 'blur' }],
    districtId: [
        { required: true, message: '请选择所在地区', trigger: [] },
        { validator: (...args) => validateLocation(args, unref(formData)), trigger: ['blur', 'change'] }
    ],
    address: { required: true, message: '请输入详细地址' },
    fileUploadList: {
        validator: (...args) => validateFileUploadList(args, unref(fileUploadList)),
        trigger: ['blur', 'change']
    },
    avatarUploadList: { validator: (...args) => validateAvatarUploadList(args, unref(fileUploadList)), trigger: ['blur', 'change'] },
    workStartTime: [
        { required: true, message: '请选择工作时间', trigger: 'blur' },
        { validator: (...args) => validateWorkTime(args, unref(formData)), trigger: 'blur' }
    ]
})

const isHideAvatarUploadBtn = computed(() => fileUploadList.value['avatar'].length >= 1)
const isHideIdCardUploadBtn = computed(() => fileUploadList.value['idCard'].length >= 2)
const isHideReportUploadBtn = computed(() => fileUploadList.value['report'].length >= 9)
const isDisabled = computed(() => unref(formData).userId === '')
const imageMaxSize = 1024 * 1024 * 2 //图片限制大小
const fileMaxSize = 1024 * 1024 * 5 //文件限制大小

onMounted(() => {
    fetchCategoryList()
})
/**保存 */
const handleSubmit = () => {
    formRef.value?.validate(async valid => {
        if (!valid) return
        try {
            await handleUpload()
            const newFormData = omit(unref(formData), ['goodsList', 'fileUploadList', 'avatarUploadList'])
            if (newFormData.isOperational === 0) {
                newFormData.workEndTime = ''
                newFormData.workStartTime = ''
            }
            const data = {
                ...newFormData,
                goodsCategoryIds: unref(formData).goodsIds.join(','),
                files: {
                    portrait: [unref(formData).files.idCard[0]],
                    backend: [unref(formData).files.idCard[1]],
                    avatar: unref(formData).files.avatar,
                    pdf: unref(formData).files.pdf,
                    report: unref(formData).files.report
                }
            }

            apiMasterWorkerAdd(data)
            feedback.msgSuccess('提交成功')
            router.back()
        } catch (error) { }
    })
}
/**上传所有文件 */
const handleUpload = () => {
    return new Promise(async (resolve, reject) => {
        if (!unref(fileUploadList) || !Object.keys(unref(fileUploadList)).length) {
            resolve([])
            return
        }

        const fileTypes = Object.keys(unref(fileUploadList))
        try {
            for (const type of fileTypes) {
                await loopUploadFile(unref(fileUploadList)[type], type)
            }
            resolve(formData.value.files)
        } catch (error) {
            reject(error)
        }
    })
}
/**循环上传图片 */
async function loopUploadFile(files: UploadFile[], type: string) {
    if (files.length > 0) {
        for (let i = 0; i < files.length; i++) {
            try {
                const { path } = await uploadFile(files[i])
                formData.value.files[type][i] = path
            } catch (error) { }
        }
    } else {
        formData.value.files[type] = []
    }
}
/**上传图片接口 */
function uploadFile(file: UploadFile) {
    return new Promise(async (resolve, reject) => {
        try {
            let formData = new FormData()
            formData.append('file', file.raw!)
            const data = await apiUploadFile(formData)
            resolve(data)
        } catch (error) {
            reject(error)
        }
    })
}
const {
    uploadPdf,
    fileUploadList,
    imgViewerVisible,
    viewerIndex,
    previewSrcList,
    startUpload,
    beforeRemove,
    handlePreview,
    closeImageViewer,
    handleExceed,
    pdfDialog,
    previewPdf
} = useUploadMoreAction()
</script>

<style lang="scss" scoped>
.avatar-uploader {
    :deep(.el-upload) {
        border: 1px dashed #dcdfe6;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: 0.2s;

        &:hover {
            border-color: #409eff;
        }

        .el-icon {
            &.avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 178px;
                height: 178px;
                text-align: center;
            }
        }
    }

    &.hide {
        :deep(.el-upload) {
            display: none;
        }
    }
}

.pdf {
    :deep(.el-upload-list--text) {
        width: 400px;
    }
}

.physical {
    display: flex;
    flex-direction: column;
}

.star {
    :deep(.el-form-item__label) {
        &::before {
            content: '*';
            color: #f56c6c;
            margin-right: 4px;
        }
    }
}

.ls-input,
.select {
    width: 340px;
}
</style>
