<template>
    <!-- 新增修改弹框 -->
    <div>
        <el-form label-width="auto" :model="addOrEditForm" :rules="formRules" ref="addOrEditFormRef">
            <el-form-item label="姓名：" prop="userName">
                <el-input
                    v-model="addOrEditForm.userName"
                    clearable
                    placeholder="请输入姓名"
                    maxlength="30"
                    style="width: 100%"
                />
            </el-form-item>
            <el-form-item label="联系方式：" prop="userPhone">
                <el-input
                    v-model="addOrEditForm.userPhone"
                    placeholder="请输入联系方式"
                    clearable
                    maxlength="11"
                    style="width: 100%"
                />
            </el-form-item>
            <el-form-item label="身份证号：" prop="idCar">
                <el-input
                    v-model="addOrEditForm.idCar"
                    clearable
                    placeholder="请输入身份证号"
                    maxlength="18"
                    style="width: 100%"
                />
            </el-form-item>
            <el-form-item label="单位：" prop="unitId">
                <el-select placeholder="请选择单位" style="width: 100%" v-model="addOrEditForm.unitId">
                    <el-option v-for="item in companyList" :key="item.id" :label="item.unitName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="班组：" prop="teamId">
                <el-select placeholder="请选择班组" style="width: 100%" v-model="addOrEditForm.teamId">
                    <el-option v-for="item in groupList" :key="item.id" :label="item.teamName" :value="item.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="工种：" prop="workType">
                <el-select placeholder="请选择工种" style="width: 100%" v-model="addOrEditForm.workType">
                    <el-option
                        :label="item.label"
                        :value="item.value"
                        :key="item.value"
                        v-for="item in dict.type.work_type"
                    />
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="人员状态：" prop="status">
                <el-select placeholder="请选择人员状态" style="width: 100%" v-model="addOrEditForm.status">
                    <el-option label="在场" value="0" />
                    <el-option label="休息" value="1" />
                    <el-option label="离场" value="2" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="性别：" prop="sex">
                <el-select placeholder="请选择性别" style="width: 100%" v-model="addOrEditForm.sex">
                    <el-option label="男" value="1" />
                    <el-option label="女" value="2" />
                </el-select>
            </el-form-item>

            <el-form-item label="年龄：" prop="age">
                <el-input clearable placeholder="请输入年龄" style="width: 100%" v-model="addOrEditForm.age" />
            </el-form-item>
            <el-form-item label="人脸照片：" prop="carImage">
                <!-- <el-upload
                    :headers="headers"
                    :action="uploadFileUrl"
                    accept="image/*"
                    :limit="1"
                    :file-list="addOrEditForm.fileList"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-exceed="handleExceed"
                    :on-success="handleSuccess"
                >
                    <div slot="tip" class="el-upload__tip" style="color: #c0c4cc; font-size: 15px">上传人脸照片</div>
                    <i class="el-icon-plus"></i>
                </el-upload> -->
                <el-upload
                    :limit="1"
                    :action="uploadFileUrl"
                    list-type="picture-card"
                    :file-list="addOrEditForm.fileList"
                    :headers="headers"
                    :on-remove="handleRemove"
                    :on-preview="handlePreview"
                    :on-success="handleSuccess"
                    :before-upload="handleBeforeUpload"
                    :show-file-list="true"
                    :on-exceed="handleExceed"
                >
                    <i class="el-icon-plus"></i>
                </el-upload>
                <div>
                    1、上传图片文件格式支持PNG、JPG、JPEG； <br />
                    2、图片大小不超过10MB； <br />
                </div>
            </el-form-item>

            <el-form-item label="岗位：" prop="postUnit">
                <el-select placeholder="请选择岗位" style="width: 100%" v-model="addOrEditForm.postUnit">
                    <el-option
                        :label="item.label"
                        :value="item.value"
                        :key="item.value"
                        v-for="item in dict.type.post_type"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="入场工程：" prop="proId">
                <el-select v-model="addOrEditForm.proId" placeholder="请选择入场工程" style="width: 100%">
                    <el-option v-for="item in unitList" :key="item.id" :label="item.unitName" :value="item.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="民族：" prop="nationality">
                <el-input
                    v-model="addOrEditForm.nationality"
                    placeholder="请输入民族"
                    clearable
                    maxlength="30"
                    style="width: 100%"
                />
            </el-form-item>
            <el-form-item label="地址：" prop="address">
                <el-input
                    v-model="addOrEditForm.address"
                    placeholder="请输入地址"
                    clearable
                    maxlength="30"
                    style="width: 100%"
                />
            </el-form-item>
            <!-- <el-form-item label="是否关键人员：" prop="keyPersonnel">
                        <el-radio-group v-model="addOrEditForm.keyPersonnel">
                            <el-radio-button label="1">是</el-radio-button>
                            <el-radio-button label="0">否</el-radio-button>
                        </el-radio-group>
                    </el-form-item> -->
        </el-form>

        <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
            <img :src="previewUrl" style="display: block; max-width: 100%; margin: 0 auto" />
        </el-dialog>
    </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getGroupListAPI, getCompanyListAPI } from '@/api/common.js'
import {
    addTtSysUser,
    updateTtSysUserApi,
    queryUnitListAllApi,
    getTtSysUserByIdApi,
} from '@/api/personnel-manage/index.js'

export default {
    dicts: ['post_type', 'work_type'],
    props: {
        rowData: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        return {
            dialogVisible: false,
            dialogImageUrl: '',
            uploadFileUrl: process.env.VUE_APP_BASE_API + '/file/upload',
            headers: {
                Authorization: 'Bearer ' + getToken(),
            },
            fileType: ['png', 'jpg', 'jpeg'],
            previewUrl: '',
            row: {},
            // 新增或修改接口
            addOrEditForm: {
                userName: '', // 姓名
                userPhone: '', // 联系方式
                idCar: '', // 身份证号
                teamId: '', // 班组
                unitId: '', // 单位
                workType: '', // 工种
                sex: '', // 性别
                nationality: '', // 民族
                age: '', // 年龄
                postUnit: '', //岗位
                proId: '', // 入场工程
                carImage: '', // 人脸照片
                fileList: [],
                address: '',
                status: '', // 人员状态/
            },
            facePhotoList: [], // 人脸照片列表
            // 工程-下拉
            unitList: [],
            // 表单校验规则
            formRules: {
                userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
                idCar: [
                    { required: true, message: '请输入身份证号', trigger: 'blur' },
                    {
                        pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
                        message: '请输入正确的身份证号',
                        trigger: 'blur',
                    },
                ],
                unitId: [{ required: true, message: '请选择单位', trigger: 'change' }],
                teamId: [{ required: true, message: '请选择班组', trigger: 'change' }],
                status: [{ required: true, message: '请选择人员状态', trigger: 'change' }],
                sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
                // nationality: [{ required: true, message: '请输入民族', trigger: 'blur' }],
                age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
                userPhone: [
                    { required: true, message: '请输入联系方式', trigger: 'blur' },
                    {
                        pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
                        message: '请输入正确的手机号',
                        trigger: 'blur',
                    },
                ],
                workType: [{ required: true, message: '请选择工种', trigger: 'change' }],
                keyPersonnel: [{ required: true, message: '请选择是否关键人员', trigger: 'change' }],
                carImage: [{ required: true, message: '请上传人脸图片', trigger: 'change' }],
            },

            // 班组
            groupList: [],
            // 单位
            companyList: [],
        }
    },
    created() {
        this.row = this.rowData
        this.getProjectListAll()
        if (!this.row.isAdd) {
            this.getDetail()
        }

        this.getGroupAndCompanyListData()
    },
    methods: {
        // 获取工程下拉
        async getProjectListAll() {
            try {
                const res = await queryUnitListAllApi()
                console.log('🚀 ~ getProjectListAll ~ res:', res)
                if (res.code === 200) {
                    this.unitList = res.data
                    this.companyList = res.data
                }
            } catch (error) {
                console.error('🚀 ~ getProjectListAll ~ error:', error)
            }
        },
        // 编辑-详情
        async getDetail() {
            try {
                const res = await getTtSysUserByIdApi({ id: this.row.id })
                console.log('🚀 ~ getDetail ~ res:', res)
                const location = window.location.origin
                if (res.code === 200) {
                    this.addOrEditForm = res.data
                    this.addOrEditForm.fileList = [
                        {
                            name: res.data.photos,
                            url: location + '/statics' + res.data.carImage,
                        },
                    ]
                }
            } catch (error) {
                console.error('🚀 ~ getDetail ~ error:', error)
            }
        },
        handleEdit(row) {
            console.log('🚀 ~ handleEdit ~ :', row)
        },
        handleExceed(file) {
            // 超过数量
            this.$modal.msgError(`上传的人脸图片数量不能超过 1 个`)
        },
        handleRemove(file, fileList) {
            this.addOrEditForm.fileList = this.addOrEditForm.fileList.filter((item) => item.uid !== file.uid)
            this.addOrEditForm.carImage = ''
        },
        // handlePictureCardPreview(file) {
        //     console.log('🚀 ~ handlePictureCardPreview ~ file:', file)
        //     // 预览
        //     this.dialogImageUrl = file.url
        //     this.dialogVisible = true
        // },
        handleBeforeUpload(file) {
            const isSvg = this.fileType.some((e) => file.type.includes(e))
            if (!isSvg) {
                this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('、')}格式的文件!`)
                return false
            }
            const isLt = file.size / 1024 / 1024 < 10
            if (!isLt) {
                this.$modal.msgError(`背景图片大小不能超过 10 MB`)

                return false
            }

            this.$modal.loading('图片正在上传，请稍候...')
        },
        handleSuccess(res, file, fileList) {
            if (res.code === 200) {
                this.addOrEditForm.carImage = res.data.name
            } else {
                this.addOrEditForm.fileList = []
                this.addOrEditForm.carImage = ''
            }
            this.$modal.closeLoading()
        },
        // 预览
        handlePreview(file) {
            this.dialogInnerVisible = true
            this.previewUrl = file.url
        },
        // 表单提交
        onSubmitForm() {
            this.$refs.addOrEditFormRef.validate(async (valid) => {
                if (valid) {
                    console.log(' this.addOrEditForm', this.addOrEditForm)

                    const {
                        userName, // 姓名
                        userPhone, // 联系方式
                        idCar, // 身份证号
                        teamId, // 班组
                        unitId, // 单位
                        workType, // 工种
                        sex, // 性别
                        nationality, // 民族
                        age, // 年龄
                        postUnit, //岗位
                        proId, // 入场工程
                        carImage, // 人脸照片
                        address,
                        status,
                        id,
                    } = this.addOrEditForm

                    const params = {
                        userName, // 姓名
                        userPhone, // 联系方式
                        idCar, // 身份证号
                        teamId, // 班组
                        unitId, // 单位
                        workType, // 工种
                        sex, // 性别
                        nationality, // 民族
                        age, // 年龄
                        postUnit, //岗位
                        proId, // 入场工程
                        carImage, // 人脸照片
                        address,
                        status,
                    }

                    // const formData = new FormData()
                    // for(const key in params) {
                    //     formData.append(key,params[key])
                    // }
                    try {
                        console.log('🚀 ~ onSubmitForm ~ params:', this.addOrEditForm)
                        if (this.row.isAdd) {
                            addTtSysUser(params).then((res) => {
                                console.log(res, '新增结果')

                                if (res.code === 200) {
                                    this.$modal.msgSuccess('新增成功')
                                }
                                this.$emit('closeDialog')
                            })
                        } else {
                            params.id = id
                            params.status = status
                            updateTtSysUserApi(params).then((res) => {
                                console.log(res, '修改结果')
                                this.$emit('closeDialog')
                                if (res.code === 200) {
                                    this.$modal.msgSuccess('修改成功')
                                }
                            })
                        }
                    } catch (error) {
                        console.error('🚀 ~ onSubmitForm ~ error:', error)
                    }
                }
            })
        },

        // 获取班组和单位
        async getGroupAndCompanyListData() {
            const { data: res } = await getGroupListAPI()
            this.groupList = res
            // const result = await getCompanyListAPI()
            // console.log('result', result)
            // this.companyList = result
        },
    },
}
</script>

<style lang="scss" scoped></style>
