<script lang="ts" setup>
/**
 * @Name: CreateLabelDialog.vue
 * @Description: 负面标签-创建弹窗
 * @Author: xinyan
 */
import { Close, Finished } from '@element-plus/icons-vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';

const props = defineProps({
	rowData: <any>Object,
});
const { rowData } = props;

const loading = ref(false);

const createOpen = defineModel({ default: false });
const createDialog = <Ref>useTemplateRef('createDialog');

const emit = defineEmits(['refresh']);

interface RuleForm {
	raw_label: any;
	kind: any;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
	raw_label: '',
	kind: '',
});

const rules = reactive<FormRules<RuleForm>>({
	raw_label: [{ required: true, message: '请输入原始标签', trigger: 'blur' }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			const body = {
				review: rowData.id,
				raw_label: ruleForm.raw_label,
				kind: ruleForm.kind,
			};
			const res = await useResponse(api.createNegativeTags, body, loading);
			if (res.code === 2000) {
        ElMessage.success({ message: '创建成功', plain: true, icon: 'CirclePlus' });
				createOpen.value = false;
				emit('refresh');
			}
		} else {
			// createOpen.value = false;
			ElMessage.error('创建失败，请检查表单');
		}
	});
};

function cancelDialog() {
	resetForm(ruleFormRef.value);
	createDialog.value.visible = false;
}

const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
};
</script>

<template>
	<el-dialog
		ref="createDialog"
		v-model="createOpen"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
		:title="`负面标签 - 创建 `"
		style="width: 35%"
	>
		<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="mx-2.5 mt-5" label-width="auto" status-icon>
			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item class="font-medium" label="原始标签" prop="raw_label">
						<el-input v-model="ruleForm.raw_label" type="textarea" maxlength="150" show-word-limit :autosize="{ minRows: 2, maxRows: 4 }"/>
					</el-form-item>
					<el-form-item class="font-medium" label="类别" prop="kind">
						<el-input v-model="ruleForm.kind" type="textarea" maxlength="150" show-word-limit/>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<el-button :icon="Close" @click="cancelDialog">取 消</el-button>
			<el-button :icon="Finished" :loading="loading" type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
		</template>
	</el-dialog>
</template>

<style scoped></style>
