<template>
	<Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
		<el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
	
			<el-form-item label="项目" prop="projectId">
				<el-select v-model="formData.projectId" 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="photo">
				<UploadImg v-model="formData.photo" />
			</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="status">
				<el-select v-model="formData.status" placeholder="请选择状态">
					<el-option v-for="dict in getIntDictOptions(DICT_TYPE.TECHNICIAN_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="150px" />
			</el-form-item>
			<el-form-item label="备注" prop="remark">
				<el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
			</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 { LitemallTechnicianApi, LitemallTechnicianVO } from '@/api/subscribe/technician'
	import { ProjectApi, ProjectVO } from '@/api/subscribe/project'
	/** 人员管理 表单 */
	defineOptions({ name: 'LitemallTechnicianForm' })

	const { t } = useI18n() // 国际化
	const message = useMessage() // 消息弹窗
	const option = ref<ProjectVO[]>([]);
	const dialogVisible = ref(false) // 弹窗的是否展示
	const dialogTitle = ref('') // 弹窗的标题
	const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
	const formType = ref('') // 表单的类型：create - 新增；update - 修改
	const formData = ref({
		id: undefined,
		projectId: undefined,
		photo: undefined,
		serviceTime: '',
		serviceTimeArray: [{}],
		serviceScope: undefined,
		status: undefined,
		content: undefined,
		remark: undefined,
	})
	const formRules = reactive({
		// techSn: [{ required: true, message: '人员编号不能为空', trigger: 'blur' }],
		type: [{ required: true, message: '人员类型不能为空', trigger: 'change' }],
		technicianName: [{ required: true, message: '人员名称不能为空', trigger: 'blur' }],
		brandId: [{ required: true, message: '门店不能为空', trigger: 'blur' }],
		// status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
	})
	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 getProjectName = async () => {
    try {
      option.value = await ProjectApi.getProjectName()
    } 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 LitemallTechnicianApi.getLitemallTechnician(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 LitemallTechnicianVO
			if (formType.value === 'create') {
				await LitemallTechnicianApi.createLitemallTechnician(data)
				message.success(t('common.createSuccess'))
			} else {
				await LitemallTechnicianApi.updateLitemallTechnician(data)
				message.success(t('common.updateSuccess'))
			}
			dialogVisible.value = false
			// 发送操作成功的事件
			emit('success')
		} finally {
			formLoading.value = false
		}
	}


	/** 重置表单 */
	const resetForm = () => {
		formData.value = {
			id: undefined,
			projectId: undefined,
			photo: undefined,
			serviceTime: '',
			serviceScope: undefined,
			status: undefined,
			content: undefined,
			remark: undefined,
			serviceTimeArray: [{}],
		}
		formRef.value?.resetFields()
	}

	/** 初始化 **/
	onMounted(() => {
		getProjectName()
	})
</script>
<style>
	.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;
	}
</style>
