<script lang="ts" setup>
/**
 * @Name: CreateComputer.vue
 * @Description:
 * @Author: xinyan
 */
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';

const showDialog = defineModel({ default: false });
const emit = defineEmits([ 'refresh' ]);

const { shopOptions, userOptions } = defineProps<{
  shopOptions: any;
  userOptions: any;
}>();

// 图片处理
const upload = ref<UploadInstance>();

// 表单数据
interface RuleForm {
	computerNumber: string;
	computerType: string;
	station: string;
	shop: string;
	user: string;
	macaddress: string;
	ipaddress: string;
	images: UploadFile[];
}

const ruleFormRef = ref<FormInstance>();
const formData = reactive<RuleForm>({
	computerNumber: '',
	computerType: '',
	station: '',
	shop: '',
	user: '',
	macaddress: '',
	ipaddress: '',
	images: [],
});

const rules = reactive<FormRules<RuleForm>>({
	computerNumber: [{ required: true, message: '请输入电脑编号', trigger: 'blur' }],
	computerType: [{ required: true, message: '请输入电脑类型', trigger: 'blur' }],
	station: [{ required: true, message: '请输入工位号', trigger: 'blur' }],
	shop: [{ required: true, message: '请输入所属商铺', trigger: 'blur' }],
	user: [{ required: true, message: '请输入电脑使用人', trigger: 'blur' }],
	macaddress: [{ required: true, message: '请输入MAC地址', trigger: 'blur' }],
	ipaddress: [{ required: true, message: '请输入IP地址', trigger: 'blur' }],
});

// 超过图片限制时触发的回调
const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles();
	const file = files[0] as UploadRawFile;
	file.uid = genFileId();
	upload.value!.handleStart(file);
};

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			handleSave();
			showDialog.value = false;
      emit('refresh');
		} else {
			ElMessage.error('添加失败');
		}
	});
};

// 保存操作
async function handleSave() {
	const bodyData = new FormData();
	const fieldsToAppend = ['computerNumber', 'computerType', 'station', 'user', 'macaddress', 'ipaddress'];

	fieldsToAppend.forEach((field) => {
		bodyData.append(field, formData[field as keyof RuleForm]);
	});

	const shopValue = Array.isArray(formData.shop) ? formData.shop.join(',') : formData.shop;
	bodyData.append('shops', shopValue);

	if (formData.images.length > 0 && formData.images[0].raw) {
		bodyData.append('images', formData.images[0].raw);
	}
	const resp = await useResponse(bodyData, api.createComputer);
	if (resp.code === 2000) {
		ElMessage.success('添加成功');
	}
}

// 取消操作
const handleCancel = () => {
	showDialog.value = false;
};

onMounted(() => {});
</script>

<template>
	<el-dialog v-model="showDialog" :close-on-click-modal="false" title="新增电脑信息" width="35%">
		<el-form ref="ruleFormRef" :model="formData" :rules="rules" class="computer-info-form" label-width="auto" status-icon>
			<el-form-item label="电脑编号：" prop="computerNumber">
				<el-input v-model="formData.computerNumber" placeholder="请输入电脑编号" />
			</el-form-item>
			<el-form-item label="电脑类型：" prop="computerType">
				<el-input v-model="formData.computerType" placeholder="请输入电脑类型" />
			</el-form-item>
			<el-form-item label="工位号：" prop="station">
				<el-input v-model="formData.station" placeholder="请输入工位号" />
			</el-form-item>
			<el-form-item label="所属店铺：" prop="shop">
				<el-select v-model="formData.shop" clearable collapse-tags filterable multiple placeholder="请选择店铺">
					<el-option v-for="shop in shopOptions" :key="shop.value" :label="shop.label" :value="shop.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="电脑使用人：" prop="user">
				<el-select v-model="formData.user" placeholder="请选择电脑使用人">
					<el-option v-for="user in userOptions" :key="user.value" :label="user.label" :value="user.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="MAC地址：" prop="macaddress">
				<el-input v-model="formData.macaddress" placeholder="请输入MAC地址" />
			</el-form-item>
			<el-form-item label="使用IP地址：" prop="ipaddress">
				<el-input v-model="formData.ipaddress" placeholder="请输入IP地址" />
			</el-form-item>
			<!-- 电脑图片上传 -->
			<el-form-item :key="images" label="电脑图片：">
				<el-upload
					ref="upload"
					v-model:file-list="formData.images"
					:auto-upload="false"
					:limit="1"
					:on-exceed="handleExceed"
					action="#"
					list-type="picture-card"
				>
					<el-icon>
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
				<el-button @click="handleCancel">取消</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style scoped>
.dialog-footer {
	margin-bottom: 10px;
	text-align: center;
}
</style>
