<template>
    <div>
        <el-form
            :model="addAndEditForm"
            :rules="addAndEditRules"
            ref="addAndEditFormRef"
            label-width="0px"
            label-position="top"
            :disabled="formType === 2"
        >
            <div class="diploma-container">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="姓名" prop="userName">
                            <el-input
                                clearable
                                maxlength="10"
                                show-word-limit
                                placeholder="请输入姓名"
                                v-model="addAndEditForm.userName"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="身份证号" prop="idCard">
                            <el-input v-model="addAndEditForm.idCard" placeholder="请输入身份证号" clearable />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                    <el-form-item label="年龄" prop="age">
                        <el-input clearable placeholder="请输入年龄" v-model="addAndEditForm.age" />
                    </el-form-item>
                </el-col> -->
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="身份证照片" prop="idCardFront">
                            <div style="display: flex">
                                <el-form-item prop="idCardFront">
                                    <UploadImg
                                        :limit="1"
                                        :file-size="10"
                                        @deleteFile="deleteFile"
                                        :is-detail="formType === 2"
                                        :upload-file-url="uploadFileUrl"
                                        :file-type="['jpg', 'png', 'jpeg']"
                                        :file-list.sync="addAndEditForm.idCardFront"
                                        :is-uploaded="addAndEditForm.idCardFront.length >= 1"
                                    >
                                        <template #upload-img-box> 身份证正面 </template>
                                    </UploadImg>
                                </el-form-item>
                                <el-form-item prop="idCardBack">
                                    <UploadImg
                                        :limit="1"
                                        :file-size="10"
                                        @deleteFile="deleteFile"
                                        :is-detail="formType === 2"
                                        :upload-file-url="uploadFileUrl"
                                        :file-type="['jpg', 'png', 'jpeg']"
                                        :file-list.sync="addAndEditForm.idCardBack"
                                        :is-uploaded="addAndEditForm.idCardBack.length >= 1"
                                    >
                                        <template #upload-img-box> 身份证反面 </template>
                                    </UploadImg>
                                </el-form-item>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="学历" prop="education">
                            <el-input
                                clearable
                                maxlength="20"
                                show-word-limit
                                placeholder="请输入学历"
                                v-model="addAndEditForm.education"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="毕业日期及院校" prop="almaMater">
                            <template #label>
                                <span>毕业日期及院校</span>
                                <span style="color: #999; font-size: 12px"
                                    >(示例：xxxx年xx月毕业于xxxx大学xxxx专业)</span
                                >
                            </template>
                            <el-input
                                clearable
                                maxlength="50"
                                show-word-limit
                                placeholder="请输入毕业日期及院校"
                                v-model="addAndEditForm.almaMater"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="职称" prop="title">
                            <el-input
                                clearable
                                maxlength="20"
                                show-word-limit
                                placeholder="请输入职称"
                                v-model="addAndEditForm.title"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="职务" prop="position">
                            <el-input
                                clearable
                                maxlength="20"
                                show-word-limit
                                placeholder="请输入职务"
                                v-model="addAndEditForm.position"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="专业" prop="major">
                            <el-input
                                clearable
                                maxlength="20"
                                show-word-limit
                                placeholder="请输入专业"
                                v-model="addAndEditForm.major"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <!-- 资格证书 -->
            <div v-for="(item, index) in addAndEditForm.certificateList" :key="index" class="diploma-container">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item>
                            <template #label>
                                <span>资格证书</span>
                                <span style="margin-left: 4px; color: #999; font-size: 12px">({{ index + 1 }})</span>
                            </template>
                            <el-input
                                clearable
                                maxlength="30"
                                show-word-limit
                                placeholder="请输入资格证书"
                                v-model="item.diploma"
                                v-if="formType === 2"
                            >
                            </el-input>

                            <el-row v-else :gutter="24">
                                <el-col :span="20">
                                    <el-select
                                        clearable
                                        filterable
                                        allow-create
                                        style="width: 100%"
                                        v-model="item.diploma"
                                        placeholder="请选择资格证书"
                                        @change="onDiplomaChange($event, index)"
                                        @blur="onDiplomaBlur($event, index)"
                                    >
                                        <el-option
                                            v-for="j in item.diplomaList"
                                            :key="j.name"
                                            :label="j.name"
                                            :value="j.name"
                                        />

                                        <!-- <el-option label="注册建造师" value="注册建造师" />
                                        <el-option label="项目经理B证" value="项目经理B证" /> -->
                                    </el-select>
                                </el-col>

                                <el-col :span="4">
                                    <!-- 增加的按钮 -->
                                    <el-button
                                        @click="onAddDiploma()"
                                        v-if="index === 0 && formType !== 2"
                                        type="primary"
                                        icon="el-icon-plus"
                                    />

                                    <!-- 删除的按钮 -->
                                    <el-button
                                        @click="onDeleteDiploma(index)"
                                        v-if="index !== 0 && formType !== 2"
                                        type="danger"
                                        icon="el-icon-delete"
                                    />
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="证书编号">
                            <el-input
                                clearable
                                maxlength="30"
                                show-word-limit
                                placeholder="请输入证书编号"
                                v-model="item.diplomaNum"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="级别" prop="level">
                            <el-input
                                clearable
                                maxlength="20"
                                show-word-limit
                                placeholder="请输入级别"
                                v-model="item.level"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="养老保险" prop="isNormal">
                        <el-radio-group v-model="addAndEditForm.isNormal">
                            <el-radio label="0">正常</el-radio>
                            <el-radio label="1">异常</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row> -->

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item>
                            <template #label>
                                <span>上述资格证书照片</span>
                                <span style="color: #999; font-size: 12px"
                                    >(最多上传5张，仅支持jpg、png、jpeg格式)</span
                                >
                            </template>
                            <UploadImg
                                :limit="5"
                                :file-size="10"
                                :multiple="true"
                                @deleteFile="deleteFile"
                                :is-detail="formType === 2"
                                :upload-file-url="uploadFileUrl"
                                :file-type="['jpg', 'png', 'jpeg']"
                                :file-list.sync="item.diplomaImg"
                                :is-uploaded="item.diplomaImg.length >= 5"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <div class="diploma-container">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item prop="otherImg">
                            <template #label>
                                <span>其他资质照片</span>
                                <span style="color: #999; font-size: 12px"
                                    >(最多上传5张，仅支持jpg、png、jpeg格式)</span
                                >
                            </template>
                            <UploadImg
                                :limit="5"
                                :file-size="10"
                                :multiple="true"
                                @deleteFile="deleteFile"
                                :is-detail="formType === 2"
                                :upload-file-url="uploadFileUrl"
                                :file-type="['jpg', 'png', 'jpeg']"
                                :file-list.sync="addAndEditForm.otherImg"
                                :is-uploaded="addAndEditForm.otherImg.length >= 5"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
        </el-form>

        <el-row style="text-align: right; border-top: 1px solid #e5e5e5; padding-top: 10px">
            <el-button @click="onCancel">{{ formType !== 2 ? '取消' : '关闭' }}</el-button>
            <el-button type="primary" @click="onConfirm" v-if="formType !== 2">确定</el-button>
        </el-row>
    </div>
</template>

<script>
import UploadImg from '@/components/UploadImg'
import { getToken } from '@/utils/auth'
import { addKeyPersonAPI, editKeyPersonAPI } from '@/api/company-manage/key-person'
import { deleteImgAPI } from '@/api/common'
export default {
    components: {
        UploadImg,
    },
    props: {
        // 1新增 2详情 3编辑
        formType: {
            type: Number,
            default: 1,
        },
        // 编辑行
        editRow: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        return {
            uploadFileUrl: process.env.VUE_APP_BASE_API + '/system/file/uploadFiles',
            fileViewUrl: process.env.VUE_APP_BASE_API + '/files',
            deleteFileList: [],
            uploadOuterVisible: false,
            diplomaList: [{ name: '注册建造师' }, { name: '项目经理B证' }], // 资格证书列表
            addAndEditForm: {
                userName: '', // 姓名
                idCard: '', // 身份证号码
                age: '', // 年龄
                education: '', // 学历
                almaMater: '', // 毕业日期
                title: '', // 职称
                position: '', // 职务
                major: '', // 专业
                diploma: '', // 资格证书
                diplomaNum: '', // 证书编码
                level: '', // 级别
                isNormal: '0', // 养老保险
                idCardFront: [], // 身份证正面
                idCardBack: [], // 身份证反面
                diplomaImg: [], // 上述资格证书照片
                otherImg: [], // 其他资质照片
                id: '',
                certificateList: [
                    {
                        diploma: '',
                        diplomaNum: '',
                        level: '',
                        diplomaImg: [],
                        diplomaList: [{ name: '注册建造师' }, { name: '项目经理B证' }],
                    },
                ], // 资格证书列表
            },
            addAndEditRules: {
                userName: [
                    {
                        required: true,
                        message: '请输入姓名',
                        trigger: 'blur',
                    },
                ],
                idCard: [
                    {
                        required: true,
                        message: '请输入身份证号码',
                        trigger: 'blur',
                    },
                    {
                        pattern:
                            /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                        message: '请输入正确的身份证号码',
                        trigger: 'blur',
                    },
                ],
                age: [
                    {
                        required: true,
                        message: '请输入年龄',
                        trigger: 'blur',
                    },
                    {
                        pattern: /^(1[01][0-9]|120|[1-9][0-9]?)$/,
                        message: '请输入正确的年龄',
                        trigger: 'blur',
                    },
                ],
                education: [
                    {
                        required: true,
                        message: '请输入学历',
                        trigger: 'blur',
                    },
                ],
                almaMater: [
                    {
                        required: true,
                        message: '请输入毕业日期及院校',
                        trigger: 'blur',
                    },
                ],
                title: [
                    {
                        required: true,
                        message: '请输入职称',
                        trigger: 'blur',
                    },
                ],
                diploma: [
                    {
                        required: true,
                        message: '请输入资格证书',
                        trigger: 'blur',
                    },
                ],
                diplomaNum: [
                    {
                        required: true,
                        message: '请输入证书编码',
                        trigger: 'blur',
                    },
                ],
                isNormal: [
                    {
                        required: true,
                        message: '请选择养老保险',
                        trigger: 'blur',
                    },
                ],
                diplomaImg: [
                    {
                        required: true,
                        message: '请上传上述资格证书照片',
                        trigger: 'blur',
                    },
                ],
                idCardFront: [
                    {
                        required: true,
                        message: '请上传身份证正面照片',
                        trigger: 'blur',
                    },
                ],
                idCardBack: [
                    {
                        required: true,
                        message: '请上传身份证反面照片',
                        trigger: 'blur',
                    },
                ],
            },
        }
    },
    methods: {
        onCancel() {
            this.$emit('closeDialogOuter')
        },
        onConfirm() {
            this.$refs.addAndEditFormRef.validate(async (valid) => {
                if (valid) {
                    // 组装参数
                    const {
                        userName, // 姓名
                        idCard, // 身份证号码
                        // age, // 年龄
                        education, // 学历
                        almaMater, // 毕业日期
                        title, // 职称
                        position, // 职务
                        major, // 专业
                        // diploma, // 资格证书
                        // diplomaNum, // 证书编码
                        // level, // 级别
                        // isNormal, // 养老保险
                        idCardFront, // 身份证正面
                        idCardBack, // 身份证反面
                        // diplomaImg, // 上述资格证书照片
                        otherImg, // 其他资质照片
                        id,
                        certificateList,
                    } = this.addAndEditForm

                    const tbFileSourceVoList = []
                    const certificateListTemp = []
                    // fileType 1.身份证正面 2.身份证反面 3.资格证书照片 4.其他资质照片
                    if (idCardFront.length > 0) {
                        idCardFront.forEach((item) => {
                            if (item.response && item.response.code === 200) {
                                const { data } = item.response
                                const { fileSuffix, filePath, fileName } = data[0]
                                tbFileSourceVoList.push({
                                    fileSuffix,
                                    filePath,
                                    fileName,
                                    fileType: 1,
                                })
                            } else {
                                tbFileSourceVoList.push({
                                    fileSuffix: item.fileSuffix,
                                    filePath: item.filePath,
                                    fileName: item.fileName,
                                    fileType: 1,
                                })
                            }
                        })
                    }
                    if (idCardBack.length > 0) {
                        idCardBack.forEach((item) => {
                            if (item.response && item.response.code === 200) {
                                const { data } = item.response
                                const { fileSuffix, filePath, fileName } = data[0]
                                tbFileSourceVoList.push({
                                    fileSuffix,
                                    filePath,
                                    fileName,
                                    fileType: 2,
                                })
                            } else {
                                tbFileSourceVoList.push({
                                    fileSuffix: item.fileSuffix,
                                    filePath: item.filePath,
                                    fileName: item.fileName,
                                    fileType: 2,
                                })
                            }
                        })
                    }

                    // if (diplomaImg.length > 0) {
                    //     diplomaImg.forEach((item) => {
                    //         if (item.response && item.response.code === 200) {
                    //             const { data } = item.response
                    //             const { fileSuffix, filePath, fileName } = data[0]
                    //             tbFileSourceVoList.push({
                    //                 fileSuffix,
                    //                 filePath,
                    //                 fileName,
                    //                 fileType: 3,
                    //             })
                    //         } else {
                    //             tbFileSourceVoList.push({
                    //                 fileSuffix: item.fileSuffix,
                    //                 filePath: item.filePath,
                    //                 fileName: item.fileName,
                    //                 fileType: 3,
                    //             })
                    //         }
                    //     })
                    // }
                    if (certificateList.length > 0) {
                        certificateList.forEach((item) => {
                            const info = {
                                diploma: item.diploma,
                                diplomaNum: item.diplomaNum,
                                level: item.level,
                                tbFileSourceVoList: [],
                            }
                            if (item.diplomaImg.length > 0) {
                                item.diplomaImg.forEach((j) => {
                                    if (j.response && j.response.code === 200) {
                                        const { data } = j.response
                                        const { fileSuffix, filePath, fileName } = data[0]
                                        info.tbFileSourceVoList.push({
                                            fileSuffix,
                                            filePath,
                                            fileName,
                                            fileType: 3,
                                        })
                                    } else {
                                        info.tbFileSourceVoList.push({
                                            fileSuffix: j.fileSuffix,
                                            filePath: j.filePath,
                                            fileName: j.fileName,
                                            fileType: 3,
                                        })
                                    }
                                })
                            }
                            certificateListTemp.push(info)
                        })
                    }
                    if (otherImg.length > 0) {
                        otherImg.forEach((item) => {
                            if (item.response && item.response.code === 200) {
                                const { data } = item.response
                                const { fileSuffix, filePath, fileName } = data[0]
                                tbFileSourceVoList.push({
                                    fileSuffix,
                                    filePath,
                                    fileName,
                                    fileType: 4,
                                })
                            } else {
                                tbFileSourceVoList.push({
                                    fileSuffix: item.fileSuffix,
                                    filePath: item.filePath,
                                    fileName: item.fileName,
                                    fileType: 4,
                                })
                            }
                        })
                    }

                    const params = {
                        userName,
                        idCard,
                        // age,
                        education,
                        almaMater,
                        title,
                        position,
                        major,
                        // diploma,
                        // diplomaNum,
                        // level,
                        // isNormal,
                        tbFileSourceVoList,
                        certificateList: certificateListTemp,
                    }

                    if (this.formType === 3) {
                        params.id = id
                    }
                    const filePaths = this.deleteFileList.map((item) => item.filePath)
                    if (filePaths.length > 0) {
                        deleteImgAPI({ filePaths: filePaths.join(',') })
                    }
                    const API = this.formType === 1 ? addKeyPersonAPI : editKeyPersonAPI
                    const res = await API(params)
                    if (res.code === 200) {
                        this.$modal.msgSuccess(this.formType === 1 ? '新增成功' : '编辑成功')
                        this.$emit('closeDialogOuter', true)
                    }
                }
            })
        },
        deleteFile(filePath) {
            this.deleteFileList.push(filePath)
        },
        deleteFileListFun() {
            const { idCardFront, idCardBack, diplomaImg, otherImg } = this.addAndEditForm
            const fileList = [...idCardFront, ...idCardBack, ...diplomaImg, ...otherImg]
            const deleteFileList = []
            this.deleteFileList.forEach((item) => {
                if (item.isNew) {
                    deleteFileList.push(item.filepath)
                }
            })

            fileList.forEach((item) => {
                if (item.response && item.response.code === 200) {
                    const { data } = item.response
                    const { filePath } = data[0]

                    deleteFileList.push(filePath)
                }
            })

            if (deleteFileList.length > 0) {
                deleteImgAPI({ filePaths: deleteFileList.join(',') })
            }
        },

        // 增加资格证书
        onAddDiploma() {
            this.addAndEditForm.certificateList.push({
                diploma: '',
                diplomaNum: '',
                level: '',
                diplomaImg: [],
                diplomaList: this.diplomaList,
            })
        },
        // 删除资格证书
        onDeleteDiploma(index) {
            this.addAndEditForm.certificateList.splice(index, 1)
        },

        // 上传成功
        uploadSuccess() {},

        // 资格证书选择
        onDiplomaChange(value, index) {
            if (!value) return
            const isRepeat = this.addAndEditForm.certificateList[index].diplomaList.some((item) => item.name === value)
            if (!isRepeat) {
                this.addAndEditForm.certificateList[index].diplomaList.push({ name: value })
            }
        },

        // 资格证书失去焦点
        onDiplomaBlur(event, index) {
            console.log(event, index)
            if (!event.target.value) return
            const isRepeat = this.addAndEditForm.certificateList[index].diplomaList.some(
                (item) => item.name === event.target.value,
            )
            if (!isRepeat) {
                this.addAndEditForm.certificateList[index].diplomaList.push({ name: event.target.value })
                this.addAndEditForm.certificateList[index].diploma = event.target.value
            }
        },
    },
    watch: {
        editRow: {
            handler(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    Object.assign(this.addAndEditForm, { ...newVal })

                    if (this.addAndEditForm.certificateList.length > 0) {
                        this.addAndEditForm.certificateList.forEach((item, index) => {
                            this.$set(this.addAndEditForm.certificateList[index], 'diplomaList', this.diplomaList)

                            if (!this.diplomaList.includes(item.diploma)) {
                                this.addAndEditForm.certificateList[index].diplomaList.push({
                                    name: item.diploma,
                                    value: item.diploma,
                                })
                            }
                        })
                    }

                    this.addAndEditForm.idCardFront = this.addAndEditForm.tbFileSourceVoList
                        .filter((item) => item.fileType == 1)
                        .map((e) => {
                            return {
                                ...e,
                                url: this.fileViewUrl + e.filePath + '?file_token=' + getToken(),
                            }
                        })
                    this.addAndEditForm.idCardBack = this.addAndEditForm.tbFileSourceVoList
                        .filter((item) => item.fileType == 2)
                        .map((e) => {
                            return {
                                ...e,
                                url: this.fileViewUrl + e.filePath + '?file_token=' + getToken(),
                            }
                        })
                    // this.addAndEditForm.diplomaImg = this.addAndEditForm.tbFileSourceVoList
                    //     .filter((item) => item.fileType == 3)
                    //     .map((e) => {
                    //         return {
                    //             ...e,
                    //             url: this.fileViewUrl + e.filePath + '?file_token=' + getToken(),
                    //         }
                    //     })

                    this.addAndEditForm.otherImg = this.addAndEditForm.tbFileSourceVoList
                        .filter((item) => item.fileType == 4)
                        .map((e) => {
                            return {
                                ...e,
                                url: this.fileViewUrl + e.filePath + '?file_token=' + getToken(),
                            }
                        })

                    if (this.addAndEditForm.certificateList.length > 0) {
                        this.addAndEditForm.certificateList.forEach((item) => {
                            item.diplomaImg = item.tbFileSourceVoList.map((e) => {
                                return { ...e, url: this.fileViewUrl + e.filePath + '?file_token=' + getToken() }
                            })
                        })
                    }
                }
            },
            deep: true,
            immediate: true,
        },
    },
}
</script>

<style scoped>
.diploma-container {
    margin-bottom: 20px;
    border: 1px solid #e5e5e5;
    border-radius: 5px;
    padding: 0 10px;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
}
</style>
