<template>
    <div class="p-2">

        <el-card shadow="hover">
            <el-form style="display: flex;justify-content: space-between;" ref="expertFormRef" :model="form"
                :rules="rules" label-width="11vw">
                <div class="form-left">

                    <el-form-item label="专家姓名：" prop="expertName">
                        <el-input v-model="form.expertName" placeholder="此处输入专家姓名" />
                    </el-form-item>

                    <el-form-item label="性别：" prop="sex">
                        <el-select v-model="form.sex" placeholder="此处选择性别" clearable>
                            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                                :value="parseInt(dict.value)" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="出生日期：" prop="birthDate">
                        <el-date-picker v-model="form.birthDate" type="date" placeholder="请选择出生日期" size="default" />
                    </el-form-item>

                    <el-form-item label="联系方式：" prop="contact">
                        <el-input v-model="form.contact" placeholder="此处输入联系方式" />
                    </el-form-item>

                    <el-form-item label="工作单位：" prop="workUnit">
                        <el-input v-model="form.workUnit" placeholder="此处输入工作单位" />
                    </el-form-item>

                    <el-form-item label="职务：" prop="duty">
                        <el-input v-model="form.duty" placeholder="此处输入职务" />
                    </el-form-item>

                    <el-form-item label="政治面貌：" prop="politics">
                        <el-input v-model="form.politics" placeholder="此处输入政治面貌" />
                    </el-form-item>

                    <el-form-item label="毕业院校：" prop="graduateSchool">
                        <el-input v-model="form.graduateSchool" placeholder="此处输入毕业院校" />
                    </el-form-item>

                    <el-form-item label="专业：" prop="major">
                        <el-input v-model="form.major" placeholder="此处输入专业" />
                    </el-form-item>

                    <el-form-item label="邮箱：" prop="email">
                        <el-input v-model="form.email" placeholder="此处输入邮箱" />
                    </el-form-item>

                    <el-form-item label="专业技术资格及取得时间：" prop="professional">
                        <el-input v-model="form.professional" placeholder="此处输入资格证书名称" />
                        <el-date-picker v-model="form.professionalAcquisitionDate" type="date" placeholder="此处选择取得时间"
                            size="default" />
                    </el-form-item>

                    <div class="current-major">
                        <el-form-item label="现从事专业及年限：" prop="workProfessial">
                            <el-input v-model="form.workProfessial" placeholder="此处输入现从事专业" />
                        </el-form-item>

                        <el-form-item prop="workProfessialYear">
                            <el-input v-model="form.workProfessialYear" placeholder="年限" />
                            <span style="font-size: 1.2rem;padding-right: 10px">年</span>
                        </el-form-item>
                    </div>

                    <div class="approval">
                        <el-form-item label="提交人：">
                            <!-- <el-input v-model="form.workUnit" /> -->
                            <span>{{ `提交人` }}</span>
                        </el-form-item>
                        <el-form-item label="审批人：">
                            <span>{{ `审批人` }}</span>
                        </el-form-item>
                        <el-form-item label="审批类型：">
                            <span>{{ `审批类型` }}</span>
                        </el-form-item>
                        
                        <el-form-item label="审批意见：">
                            <el-input v-model="form.graduateSchool" placeholder="此处输入审批意见" />
                        </el-form-item>

                        <div class="app-btns">
                            <p @click="handlePass">审批通过</p>
                            <p @click="handleReject" style="background-color: #f56c6c;">审批驳回</p>
                        </div>

                    </div>

                    <div class="form-buttons">
                        <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
                        <el-button type="danger" @click="cancel">取消</el-button>
                    </div>
                </div>


                <!-- 表单左边部分结束 右边部分开始 -->

                <div class="form-right">
                    <!-- 照片 -->
                    <el-form-item label="照片：" prop="photograph">
                        <el-upload :limit="1" class="avatar-uploader" :action="upload.url" :headers="upload.headers"
                            :show-file-list="false" :on-success="handleAvatarSuccess" :on-error="handleUploadError"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>

                            <template #tip>
                                <div class="text-left el-upload__tip">
                                    <span>请选择图片上传：大小128 * 180像素，支持jpg、png等格式，图片需小于10M，仅一张。</span>

                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>



                    <!-- 从事工作或研究领域（可多选） -->
                    <el-form-item label="从事工作或研究领域（可多选）：">
                        <el-checkbox-group @change="boxChange" v-model="form.performWork">
                            <el-checkbox v-for="(item, index) of fieldOptions" :key="index" :value="item.label"
                                :label="item.label" />


                            <el-input :disabled="otherInputDisable" v-model="form.otherDescribe" placeholder="
此处输入其他领域具体内容" />
                        </el-checkbox-group>
                    </el-form-item>

                    <!-- 主要工作经历 -->
                    <el-form-item label="主要工作经历：">
                        <el-input v-model="form.workExperience" maxlength="3000" style="width: 240px"
                            placeholder="此处输入主要工作经历" show-word-limit type="textarea"
                            :autosize="{ minRows: 2, maxRows: 5 }" />
                    </el-form-item>
                    <!-- 社会兼职情况 -->
                    <el-form-item label="社会兼职情况：">
                        <el-input v-model="form.workPluralistic" maxlength="3000" style="width: 240px"
                            placeholder="此处输入社会兼职情况" show-word-limit type="textarea"
                            :autosize="{ minRows: 2, maxRows: 5 }" />
                    </el-form-item>
                    <!-- 主要论著、业绩成果及获奖情况 -->
                    <el-form-item label="主要论著、业绩成果及获奖情况：">
                        <el-input v-model="form.achievement" maxlength="3000" style="width: 240px"
                            placeholder="此处输入主要论著、业绩成果及获奖情况" show-word-limit type="textarea"
                            :autosize="{ minRows: 2, maxRows: 5 }" />
                    </el-form-item>


                </div>



            </el-form>
        </el-card>



        <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>


</template>

<script setup name="Role" lang="ts">
// import { addRole, changeRoleStatus, dataScope, delRole, getRole, listRole, updateRole, deptTreeSelect } from '@/api/system/role';

import { listExpert, getExpert, delExpert, addExpert, updateExpert } from '@/api/expert/expert/index';
import { RoleVO, RoleForm, RoleQuery, DeptTreeOption } from '@/api/system/role/types';
import { MenuTreeOption, RoleMenuTree } from '@/api/system/menu/types';

import { ExpertInVO, ExpertInForm, ExpertInQuery } from '@/api/expert/in/types';
import { ExpertVO, ExpertForm, ExpertQuery } from '@/api/expert/expert/types';
import $bus from '@/utils/mitt'
import { globalHeaders } from '@/utils/request';

import { getToken } from '@/utils/auth';
const upload = reactive<UploadOption>({
    headers: globalHeaders(),
    url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const otherInputDisable = ref(true);
const buttonLoading = ref(false);
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { approval_status } = toRefs<any>(proxy?.useDict('approval_status'));
const { sys_user_sex } = toRefs<any>(proxy?.useDict('sys_user_sex'));

const roleList = ref<RoleVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
//   const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const menuOptions = ref<MenuTreeOption[]>([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const deptOptions = ref<DeptTreeOption[]>([]);
const openDataScope = ref(false);
const route = useRoute();

/** 数据范围选项*/
const dataScopeOptions = ref([
    { value: '1', label: '全部数据权限' },
    { value: '2', label: '自定数据权限' },
    { value: '3', label: '本部门数据权限' },
    { value: '4', label: '本部门及以下数据权限' },
    { value: '5', label: '仅本人数据权限' }
]);

const queryFormRef = ref<ElFormInstance>();
const expertFormRef = ref<ElFormInstance>();
const dataScopeRef = ref<ElFormInstance>();
const menuRef = ref<ElTreeInstance>();
const deptRef = ref<ElTreeInstance>();

const initForm: ExpertForm = {   //初始表单
    //左边
    expertName: '',//专家姓名
    sex: undefined,//性别
    birthDate: '',//出生年月
    contact: '',//联系方式
    workUnit: '',//工作单位
    duty: '',//职务
    politics: '',//政治面貌
    graduateSchool: '',//毕业院校
    major: '',//专业
    email: '',//邮箱

    professional: '',//资格证书名称
    professionalAcquisitionDate: '',//资格证书取得时间
    workProfessial: '',//现从事专业
    workProfessialYear: 0,//现从事年限

    //右边
    photograph: '',//照片
    performWork: [],//从事工作或研究领域
    performWorkId: '',//从事工作或研究领域
    otherDescribe: '',//其他领域描述
    workExperience: '',//主要工作经历
    workPluralistic: '',//社会兼职情况
    achievement: '',//主要论著、业绩成果及获奖情况
    paperpath: '',//论文
    patentpath: '',//专利
};
const data = reactive<PageData<ExpertForm, ExpertQuery>>({
    form: { ...initForm },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        expertName: '',
        contact: '',
        workUnit: '',
        status: 0,
    },
    rules: {
        expertName: [{ required: true, message: '专家姓名不能为空', trigger: 'blur' }],
        sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        birthDate: [{ required: true, message: '出生日期不能为空', trigger: 'blur' }],
        contact: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
        workUnit: [{ required: true, message: '工作单位不能为空', trigger: 'blur' }],
        duty: [{ required: true, message: '职务不能为空', trigger: 'blur' }],
        politics: [{ required: true, message: '政治面貌不能为空', trigger: 'blur' }],
        graduateSchool: [{ required: true, message: '毕业学校不能为空', trigger: 'blur' }],
        major: [{ required: true, message: '专业不能为空', trigger: 'blur' }],
    }
});

const { form, queryParams, rules } = toRefs(data);

const imageUrl = ref('')
//上传之前
const beforeAvatarUpload = (file: any) => {
    const type = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg'];
    const isJPG = type.includes(file.type);
    //检验文件格式
    if (!isJPG) {
        proxy?.$modal.msgError(`图片格式错误!`);
        return false;
    }
    // 校检文件大小
    const isLt = file.size / 1024 / 1024 < 10;
    if (!isLt) {
        proxy?.$modal.msgError(`上传图片大小不能超过 10 MB!`);
        return false;
    }
    proxy?.$modal.loading('正在上传文件，请稍候...');
    return true;
}
//上传成功
const handleAvatarSuccess = (res: any) => {

    // 如果上传成功
    if (res.code === 200) {
        imageUrl.value = res.data.url

        proxy?.$modal.closeLoading();
    } else {
        proxy?.$modal.msgError('图片插入失败');
        proxy?.$modal.closeLoading();
    }
}
//上传失败
const handleUploadError = (err: any) => {
    proxy?.$modal.msgError('上传文件失败');
};

//checkbox更改事件
const boxChange = (value) => {
    if (value.indexOf("18") != -1) {
        otherInputDisable.value = false;
    } else {
        otherInputDisable.value = true;
    }

}
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handlePass = ()=>{
    
}

const handleReject = ()=>{

}

//预览图片
const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
}

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const fieldOptions = reactive([
    {
        value: 1,
        label: '信息化基础设施建设'
    },
    {
        value: 2,
        label: '网络传输'
    },
    {
        value: 3,
        label: '网络与信息安全'
    },
    {
        value: 4,
        label: '社会管理和公共服务信息'
    },
    {
        value: 5,
        label: '信息资源开发利用'
    },
    {
        value: 6,
        label: '云计算与大数据'
    },
    {
        value: 7,
        label: '移动互联网'
    },
    {
        value: 8,
        label: '信息化项目审计'
    },
    {
        value: 9,
        label: '电子政务'
    },
    {
        value: 10,
        label: '其他领域(需填写)'
    },
]);

/** 重置新增的表单以及其他数据  */
const reset = () => {
    form.value = { ...initForm };
    expertFormRef.value?.resetFields();
};





/** 提交按钮 */
const submitForm = () => {


    expertFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.expertId) {

                form.value.performWorkId = form.value.performWork.join(',');
                delete form.value.performWork;

                await updateExpert(form.value).finally(() => buttonLoading.value = false);
            } else {

                form.value.performWorkId = form.value.performWork.join(',');
                delete form.value.performWork;

                await addExpert(form.value).finally(() => buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("操作成功");
            //   dialog.visible = false;
            //   await getList();

            router.back();
        }
    });
};
/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;

    router.back();
};

onBeforeMount(async () => {
    if (route.query.id) {

        const res = await getExpert(route.query.id.toString());

        res.data.otherDescribe != '' ? otherInputDisable.value = false : otherInputDisable.value = true;

        res.data.performWorkId ? Object.assign(form.value, res.data, { performWork: res.data.performWorkId.toString().split(',') }) : Object.assign(form.value, res.data);
    }
})


</script>

<style lang="scss" scoped>
.p-2 {
    height: 100%;
    overflow-y: scroll;
}

.form-left,
.form-right {
    width: 49%;
    height:auto;
    font-size: 2rem;

}

:deep(.el-form-item) {
    line-height: 4vh;
}

.form-left {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    // .el-form-item:nth-child(11){
    // &>div:nth-child(2){

    // }
    // }
}

// .form-right {}

.form-buttons {
    width: 50%;
    margin: 0 auto;
    display: flex;
    justify-content: space-around;
    margin-top: 2vh;
}

.current-major {
    display: flex;
    justify-content: space-between;
    flex-wrap: nowrap;

    // overflow: hidden;
    .el-form-item:nth-child(1) {
        width: 80%;


    }

    .el-form-item:nth-child(2) {
        :deep(.el-form-item__label) {
            display: none;
        }

        :deep(.el-form-item__content) {
            margin-left: 0 !important;
            width: 100% !important;
            display: flex !important;
            justify-content: space-around !important;

            &>div {
                width: 60%;
            }
        }
    }

}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

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

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

:deep(.el-form-item--default .el-form-item__label) {
    font-size: 1.2rem;
    height: 4vh;
    line-height: inherit;
}

:deep(.el-form-item__content) {
    line-height: 4vh;
}

// .form-right {
//:deep(.el-form-item__label)  {
// justify-content: flex-start;
//}
// }

:deep(.el-textarea) {
    width: 100% !important;
}

:deep(.el-upload) {
    border: 1px dashed #3d3d3d;
    border-radius: 1vw;
}

:deep(.el-textarea__inner) {
    height: 13.5vh !important;
    width: 100% !important;
}

:deep(.el-date-editor.el-input) {
    width: 100%;
}

.el-button {
    width: 6vw;
}

.approval{
    background-color: #f2f2f2;
    position: relative;
    border-radius: 8px;
    padding-right: 1vw;
    span{
        font-size: 1.2rem;
    }

    .app-btns{
        position: absolute;
        width: 10vw;
        right: 1vw;top: 0;
        display: flex;
        justify-content: space-between;
        font-size: 1rem;
        text-align: center;
        p{
            color: #fff;
            padding: 8px;
            border-radius: 5px;
            background-color: #67c23a;
            cursor: pointer;
        }
    }
}
</style>
