<template>
	<div class="system-dept-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="deptDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="员工照片" :rules="[{ required: true, message: '员工照片不能为空' }]">
							<el-upload
								class="avatar-uploader"
								:action="state.action"
								:show-file-list="false"
								:on-success="handleAvatarSuccess"
								:before-upload="beforeAvatarUpload"
								:drag="true"
							>
								<img v-if="state.ruleForm.img_url" :src="state.ruleForm.img_url" class="avatar" />
								<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
							</el-upload>
							<span class="ml10">尺寸316*316，小于2MB</span>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="员工性别" :rules="[{ required: true, message: '员工性别不能为空' }]">
                            <el-radio-group v-model="state.ruleForm.gender">
                                <!-- <el-radio-button :label="0">保密</el-radio-button>
                                <el-radio-button :label="1">男</el-radio-button>
                                <el-radio-button :label="2">女</el-radio-button> -->
								<el-radio :label="0">保密</el-radio>
                                <el-radio :label="1">男</el-radio>
                                <el-radio :label="2">女</el-radio>
                            </el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<!--  prop="name" -->
						<el-form-item label="员工姓名" :rules="[{ required: true, message: '员工姓名不能为空' }]">
							<el-input v-model="state.ruleForm.name" placeholder="请输入员工姓名" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="所在部门" :rules="[{ required: true, message: '所在部门不能为空' }]">
							<el-cascader
								:options="state.departmentList"
								:props="{ checkStrictly: true, value: 'id', label: 'name' }"
								placeholder="请选择所在部门"
								clearable
								class="w100"
								v-model="state.ruleForm.department_id"
								@change="getDepartId"
							>
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<!--  prop="id_card" -->
						<el-form-item label="身份证号" :rules="[{ required: true, message: '身份证号不能为空' }]">
							<el-input v-model="state.ruleForm.id_card" placeholder="请输入身份证号" clearable @change="autoComputer($event)"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角　　色" :rules="[{ required: true, message: '角色不能为空' }]">
                            <el-select v-model="state.ruleForm.role_id" placeholder="请选择角色">
                                <el-option
                                v-for="item in state.roleList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
								:disabled="item.valid==0"
                                />
                            </el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<!--  prop="phone" -->
						<el-form-item label="联系电话" :rules="[{ required: true, message: '联系电话不能为空' }]">
							<el-input v-model="state.ruleForm.phone" placeholder="请输入联系电话" clearable></el-input>
						</el-form-item>
					</el-col>

					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="状态">
                            <el-select v-model="state.ruleForm.valid" placeholder="请选择状态">
                                <el-option
                                v-for="item in state.options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                :disabled="item.disabled"
                                />
                            </el-select>
						</el-form-item>
					</el-col> -->

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="状　　态" :rules="[{ required: true, message: '状态不能为空' }]">
                            <el-radio-group v-model="state.ruleForm.valid">
                                <el-radio :label="1">启用</el-radio>
                                <el-radio :label="0">禁用</el-radio>
                            </el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<!--  prop="age" -->
						<el-form-item label="年　　龄" :rules="[{ required: true, message: '年龄不能为空' }]">
							<el-input v-model="state.ruleForm.age" type="number" placeholder="请输入年龄" clearable min="0"
							 @input="verifyNumberIntegerAndFloat('age',$event)"></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.ruleForm.id==0">
						 <!-- prop="password" -->
						<el-form-item label="初始密码" :rules="[{ required: true, message: '初始密码不能为空' }]">
							<el-input v-model="state.ruleForm.password" type="password" show-password placeholder="请输入初始密码" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="入职日期" :rules="[{ required: true, message: '入职日期不能为空' }]">
							<el-date-picker
								v-model="state.ruleForm.entry_date"
								type="date"
								placeholder="请选择入职日期"
								size="default"
                                value-format="YYYY-MM-DD"
							/>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="工　　号" :rules="[{ required: false, message: '工号不能为空' }]">
							<el-input v-model="state.ruleForm.card_num" type="text" placeholder="请输入工号" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-divider content-position="left">工资信息</el-divider>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="工资类型" :rules="[{ required: true, message: '状态不能为空' }]">
                            <el-radio-group v-model="state.ruleForm.salary_type">
                                <el-radio :label="1">计件</el-radio>
                                <el-radio :label="2">非计件</el-radio>
                            </el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="11" :md="11" :lg="11" :xl="11" class="mb20">
						<el-form-item label="基本工资" :rules="[{ required: true, message: '基本工资不能为空' }]">
							<el-input v-model="state.ruleForm.base_salary" type="number" placeholder="填写工资基数金额" clearable min="0"
							 @input="verifyNumberIntegerAndFloat('base_salary',$event)"></el-input>
						</el-form-item>
					</el-col>
					<span class="mt5">元</span>
					
					<el-col :xs="24" :sm="11" :md="11" :lg="11" :xl="11" class="mb20">
						<el-form-item label="加班工资" :rules="[{ required: true, message: '加班工资不能为空' }]">
							<el-input v-model="state.ruleForm.over_salary" type="number" placeholder="填写工资基数金额" clearable min="0"
							 @input="verifyNumberIntegerAndFloat('over_salary',$event)"></el-input>
						</el-form-item>
					</el-col>
					<span class="mt5">元</span>
					
					<el-col :xs="24" :sm="11" :md="11" :lg="11" :xl="11" class="mb20">
						<el-form-item label="计时工资" :rules="[{ required: true, message: '计时工资不能为空' }]">
							<el-input v-model="state.ruleForm.hourly_salary" type="number" placeholder="填写工资基数金额" clearable min="0"
							 @input="verifyNumberIntegerAndFloat('hourly_salary',$event)"></el-input>
						</el-form-item>
					</el-col>
					<span class="mt5">元/小时</span>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemDeptDialog">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus';
import config from '/@/config.ts';
import Department from '/@/api/department/department.ts';
import ruleReg from '/@/utils/ruleReg.ts';
import { Session } from '/@/utils/storage';

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
	console.log('response',response);
	state.ruleForm.img_url = response.data.url;
	// state.ruleForm.img_url = URL.createObjectURL(uploadFile.raw!);
	console.log('state.ruleForm.head_img',state.ruleForm.img_url);
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG and PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const verifyNumberIntegerAndFloat = (type:string,e:any) => {
	switch(type){
		case 'age':
			state.ruleForm.age = ruleReg.verifiyNumberInteger(e);
			break;
		case 'base_salary':
			state.ruleForm.base_salary = ruleReg.verifyNumberIntegerAndFloat(e);
			break;
		case 'over_salary':
			state.ruleForm.over_salary = ruleReg.verifyNumberIntegerAndFloat(e);
			break;
		case 'hourly_salary':
			state.ruleForm.hourly_salary = ruleReg.verifyNumberIntegerAndFloat(e);
			break;
	}
}

const autoComputer = (e:any) => {
	// console.log('e',e);
	state.ruleForm.age = ruleReg.autoComputerID(e,state.ruleForm.name);
	// console.log('state.ruleForm.age',state.ruleForm.age);
}

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const radio1 = ref('男')
const deptDialogFormRef = ref();

const state = reactive({
	ruleForm: {
		id: 0,
		img_url: '',
		gender: 0,
		name: '',
		department_id: '',
		id_card: '',
		age:<number|string> '',
		phone: '',
		valid: 1,
        role_id: '',
		password: '',
		salary_type: 1,
		base_salary: '',
		over_salary: '',
		hourly_salary: '',
		entry_date: '',
		card_num: '',
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	action: config.host + '/admin/upload/file',
	departmentList: [], //部门列表
	roleList: [], //角色列表
});

const getDepartId = (e: any) => {
	console.log('e',e);
	state.ruleForm.department_id = e[e.length-1];
	console.log('state.ruleForm.department_id',state.ruleForm.department_id);
}

// 打开弹窗
const openDialog = (type: string, row: any) => {
	initAdmin();
	state.dialog.type = type;
	if (type === 'edit') {
		state.ruleForm = {
			id: row.id,
			img_url: row.img_url,
			gender: row.gender,
			name: row.name,
			department_id: row.department_id,
			id_card: row.id_card,
			age: row.age,
			phone: row.phone,
			valid: row.valid,
			role_id: row.role_id,
			password: row.password,
			salary_type: row.salary_type,
			base_salary: row.base_salary,
			over_salary: row.over_salary,
			hourly_salary: row.hourly_salary,
			entry_date: row.entry_date,
			card_num: row.card_num,
		};
		if(state.ruleForm.gender==1){
			radio1.value = '男';
		}else if(state.ruleForm.gender==2){
			radio1.value = '女';
		}else{
			radio1.value = '保密';
		}
		state.dialog.title = '修改员工032';
		state.dialog.submitTxt = '修 改';
	} else {
        state.ruleForm = {
			id: 0,
            img_url: '',
			gender: 0,
			name: '',
			department_id: '',
			id_card: '',
			age:<number|string> '',
			phone: '',
			valid: 1,
			role_id: '',
			password: '',
			salary_type: 1,
			base_salary: '',
			over_salary: '',
			hourly_salary: '',
			entry_date: '',
			card_num: '',
        };
		radio1.value = '保密';
		state.dialog.title = '新增员工031';
		state.dialog.submitTxt = '保 存';
		// 清空表单，此项需加表单验证才能使用
		// nextTick(() => {
		// 	deptDialogFormRef.value.resetFields();
		// });
	}
	state.dialog.isShowDialog = true;
	// getMenuData();
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = async() => {
	if(!ruleReg.emptyReg(state.ruleForm.img_url)){
		return ElMessage.warning("请上传员工照片");
	}
	if(!ruleReg.emptyReg(state.ruleForm.name)){
		return ElMessage.warning("请输入员工姓名");
	}
	if(!ruleReg.emptyReg(state.ruleForm.department_id)){
		return ElMessage.warning("请选择所在部门");
	}
	if(!ruleReg.emptyReg(state.ruleForm.id_card)){
		return ElMessage.warning("请输入身份证号");
	}else{
		if(!ruleReg.checkID(state.ruleForm.id_card)){
			return ElMessage.warning("身份证号格式不正确");
		}
	}
	if(!ruleReg.emptyReg(state.ruleForm.role_id)){
		return ElMessage.warning("请选择角色");
	}
	if(!ruleReg.emptyReg(state.ruleForm.phone)){
		return ElMessage.warning("请输入联系电话");
	}
	if(!ruleReg.emptyReg(state.ruleForm.age)){
		return ElMessage.warning("请输入年龄");
	}
	if(!ruleReg.emptyReg(state.ruleForm.password)){
		return ElMessage.warning("请设置初始密码");
	}
	if(!ruleReg.emptyReg(state.ruleForm.entry_date)){
		return ElMessage.warning("请选择入职日期");
	}
	if(!ruleReg.emptyReg(state.ruleForm.base_salary)){
		return ElMessage.warning("请输入基本工资");
	}
	if(!ruleReg.emptyReg(state.ruleForm.over_salary)){
		return ElMessage.warning("请输入加班工资");
	}
	if(!ruleReg.emptyReg(state.ruleForm.hourly_salary)){
		return ElMessage.warning("请输入计时工资");
	}
	let res: any = null;
	if(state.dialog.type=='edit' || state.ruleForm.id!=0){
		res = await Department.editAdmin(state.ruleForm);
		if(res.code != 0){
            return ElMessage.error(res.msg);
        }
	}else{
		res = await Department.addAdmin(state.ruleForm);
		if(res.code != 0){
            return ElMessage.error(res.msg);
        }
	}
	state.ruleForm.img_url = '';
	ElMessage.success(res.msg);
	closeDialog();
	emit('refresh');
};
const departmentList = (list:any) => {
	list.forEach((item:any)=>{
		if(item.valid!=1){
			item.disabled = true;
		}
		if(item.children){
			departmentList(item.children);
		}
	});
}
// 初始化下拉列表
const initAdmin = async() => {
	console.log("初始化");
	let res = await Department.initAdmin();
	if(res.code != 0){
		return ElMessage.error(res.msg);
	}
	state.departmentList = [];
	state.roleList = [];
	departmentList(res.data.departmentList);
	state.departmentList = res.data.departmentList;
	state.roleList = res.data.roleList;
}
// 初始化人员数据
// const getMenuData = async() => {
//     let res = await Department.detailAdmin(state.id);
// 	if(res.code != 0){
// 		return ElMessage.error(res.msg);
// 	}
// 	state.ruleForm = {
// 		id: res.data.id,
// 		img_url: res.data.img_url,
// 		gender: res.data.gender,
// 		name: res.data.name,
// 		department_id: res.data.department_id,
// 		id_card: res.data.id_card,
// 		age: res.data.age,
// 		phone: res.data.phone,
// 		valid: res.data.valid,
//         role_id: res.data.role_id,
// 		password: res.data.password,
// 	}
// 	if(state.ruleForm.gender==1){
// 		radio1.value = '男';
// 	}else if(state.ruleForm.gender==2){
// 		radio1.value = '女';
// 	}else{
// 		radio1.value = '保密';
// 	}
// };

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss" scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
	.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;
	}
</style>
