<template>
	<Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
		<el-form ref="formRef" :model="formData" :rules="formRules" label-width="90px" v-loading="formLoading">
			<!--     <el-form-item label="所属机构" prop="organizationId">
        <el-input v-model="formData.organizationId" placeholder="请输入机构id" />
      </el-form-item> -->
			<el-form-item label="所属机构" prop="organizationId">
				<el-select v-model="formData.organizationId" placeholder="请选择机构" clearable class="!w-240px">
					<el-option v-for="organizationNameOptions in option" :key="organizationNameOptions.id"
						:label="organizationNameOptions.name" :value="organizationNameOptions.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="编号" prop="serialNumber">
				<el-input v-model="formData.serialNumber" placeholder="请输入编号" />
			</el-form-item>
			<el-form-item label="类型" prop="type">
				<el-select v-model="formData.type" placeholder="请选择类型">
					<el-option v-for="dict in getIntDictOptions(DICT_TYPE.STAFF_TYPE)" :key="dict.value"
						:label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="名称" prop="name">
				<el-input v-model="formData.name" placeholder="请输入名称" />
			</el-form-item>
			<el-form-item label="性别" prop="sex">
				<el-select v-model="formData.sex" placeholder="请选择性别">
					<el-option v-for="dict in getIntDictOptions(DICT_TYPE.STALL_SEX)" :key="dict.value"
						:label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="照片" prop="photo">
				<UploadImg v-model="formData.photo" />
			</el-form-item>
			<el-form-item label="手机号" prop="phone">
				<el-input v-model="formData.phone" placeholder="请输入手机号" />
			</el-form-item>

			<el-form-item label="服务时间段" prop="serviceTime">
				<div v-for="(item, index) in timeRanges" :key="index" class="time-range">
					<div class="left">
						<el-time-select
						      v-model="item.start"
						      :max-time="item.end"
						      class="mr-4"
						      placeholder="开始时间"
						      start="07:00"
						      step="00:05"
						      end="23:30"
						    />
					</div>
					<div class="center">
						-
					</div>
					<div class="right">
						<el-time-select
						  v-model="item.end"
						  :min-time="item.start"
						  placeholder="结束时间"
						  start="07:00"
						  step="00:05"
						  end="23:30"
						/>
					</div>
					<el-button @click="removeTime(index)" type="danger" size="mini">移除</el-button>
				</div>

				<el-button @click="addTime" type="primary" size="small">添加时间段</el-button>
			</el-form-item>


			<el-form-item label="服务范围" prop="serviceScope">
				<el-input v-model="formData.serviceScope" placeholder="请输入服务范围" />
			</el-form-item>
			<el-form-item label="约满标记" prop="sign">
				<el-select v-model="formData.sign" placeholder="请选择约满标记">
					<el-option v-for="dict in getIntDictOptions(DICT_TYPE.STAFF_FULL)" :key="dict.value"
						:label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="状态" prop="status">
				<el-select v-model="formData.status" placeholder="请选择状态">
					<el-option v-for="dict in getIntDictOptions(DICT_TYPE.STAFF_STATUS)" :key="dict.value"
						:label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="介绍" prop="content">
				<Editor v-model="formData.content" height="300px" />
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
			<el-button @click="dialogVisible = false">取 消</el-button>
		</template>
	</Dialog>
</template>
<script setup lang="ts">
	import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
	import { StaffApi, StaffVO } from '@/api/subscribe/staff'
	import { OrganizationApi, OrganizationVO } from '@/api/subscribe/organization'


	/** 预约人员 表单 */
	defineOptions({ name: 'StaffForm' })

	const { t } = useI18n() // 国际化
	const message = useMessage() // 消息弹窗
	const option = ref<OrganizationVO[]>([]);
	const dialogVisible = ref(false) // 弹窗的是否展示
	const dialogTitle = ref('') // 弹窗的标题
	const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
	const formType = ref('') // 表单的类型：create - 新增；update - 修改
	const formData = ref({
		id: undefined,
		organizationId: undefined,
		serialNumber: undefined,
		type: undefined,
		name: undefined,	
		sex: undefined,
		photo: undefined,
		phone: undefined,
		serviceTime: '',
		serviceTimeArray: [{}],
		serviceScope: undefined,
		sign: undefined,
		status: undefined,
		content: undefined,
	})
	const formRules = reactive({
		organizationId: [{ required: true, message: '所属机构不能为空', trigger: 'blur' }],
		serialNumber: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
		type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
		name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
		sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
		photo: [{ required: true, message: '照片不能为空', trigger: 'blur' }],
		phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
		// serviceTime: [{ required: true, message: '服务时间段不能为空', trigger: 'blur' }],
		serviceScope: [{ required: true, message: '服务范围不能为空', trigger: 'blur' }],
		sign: [{ required: true, message: '不能为空', trigger: 'blur' }],
		status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
		content: [{ required: true, message: '介绍不能为空', trigger: 'blur' }]
	})
	const formRef = ref() // 表单 Ref


	const timeRanges = ref([{ start: '', end: '' }]);

	const addTime = () => {
		timeRanges.value.push({ start: '', end: '' });
	};

	const removeTime = (index : number) => {
		if (timeRanges.value.length > 1) {
			timeRanges.value.splice(index, 1);
		}
	};

	//初始化机构名称下拉框
	const getOrganizations = async () => {
		try {
			option.value = await OrganizationApi.getOrganizations()
		} finally {

		}
	}

	/** 打开弹窗 */
	const open = async (type : string, id ?: number) => {
		dialogVisible.value = true
		dialogTitle.value = t('action.' + type)
		timeRanges.value = ([])  //清空timeRanges的数据
		timeRanges.value.push({ start: '', end: '' }); //再将timeRaanges设置为{ start: '', end: '' }
		formType.value = type
		resetForm()
		// 修改时，设置数据
		if (id) {
			formLoading.value = true
			try {
				timeRanges.value = ([]); //修改页面：组件设置为空
				formData.value = await StaffApi.getStaff(id)
				const timeRange = JSON.parse(formData.value.serviceTime)
				for (var i = 0; i < timeRange.length; i++) {
					timeRanges.value.push(timeRange[i]); //原有的时间段push上去
				}
				
			} finally {
				formLoading.value = false
			}
		}
		
	}
	defineExpose({ open }) // 提供 open 方法，用于打开弹窗

	/** 提交表单 */
	const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
	const submitForm = async () => {
		
		// 校验表单
		await formRef.value.validate()
		// 提交请求
		formLoading.value = true
		try {
			formData.value.serviceTime = JSON.stringify(timeRanges.value);
			const data = formData.value as unknown as StaffVO
			if (formType.value === 'create') {
				await StaffApi.createStaff(data)
				message.success(t('common.createSuccess'))
			} else {
				await StaffApi.updateStaff(data)
				message.success(t('common.updateSuccess'))
			}
			dialogVisible.value = false
			// 发送操作成功的事件
			emit('success')
		} finally {
			formLoading.value = false
		}
	}

	/** 重置表单 */
	const resetForm = () => {
		formData.value = {
			id: undefined,
			organizationId: undefined,
			serialNumber: undefined,
			type: undefined,
			name: undefined,
			sex: undefined,
			photo: undefined,
			phone: undefined,
			serviceTime: '',
			serviceTimeArray: [{}],
			serviceScope: undefined,
			sign: undefined,
			status: undefined,
			content: undefined,
		}
		formRef.value?.resetFields()
	}

	/** 初始化 **/
	onMounted(() => {
		getOrganizations()
	})
</script>

<style scoped>
	.time-range {
		margin-bottom: 10px;
		margin-right: 40px;
		/* width: 300px;
  height: 150px; */
		display: flex;
		/* justify-content: space-between; */
	}

	.left {
		width: 150px;
	}

	.center {
		width: 20px;
		text-align: center;
	}

	.right {
		width: 150px;
		margin-right: 20px;
	}

	/* .separator {
  text-align: center;
}
.remove-btn {
  text-align: right;
  margin-top: 5px;
} */
</style>