<template>
	<el-dialog title="编辑质检模板" v-model="state.dialogVisible" width="769px" draggable @close="close">
		<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="100px">
			<el-row :gutter="10">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="模板名称" prop="name" :rules="[{ required: true, message: '请填写模板名称', trigger: 'blur' }]">
						<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">
					<el-form-item label="质检分类" prop="grouping" :rules="[{ required: true, message: '请选择质检分类', trigger: 'change' }]">
						<el-select v-model="state.ruleForm.grouping" placeholder="请选择质检分类" class="w100">
							<el-option v-for="item in props.templateGrouping" :value="item.key" :key="item.key" :label="item.value" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="模板说明" prop="content" :rules="[{ required: false, message: '请填写模板说明', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.content" placeholder="请填写模板说明" type="textarea"></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="是否启用" prop="isEnable" :rules="[{ required: false, message: '请选择是否启用', trigger: 'change' }]">
						<el-switch
							v-model="state.ruleForm.isEnable"
							inline-prompt
							active-text="启用"
							inactive-text="禁用"
							:active-value="1"
							:inactive-value="0"
						/>
					</el-form-item>
				</el-col>
			</el-row>
			<el-divider content-position="left">
        <el-text tag="b" size="large" class="mr20"> 模板内容 </el-text>
				<el-button link type="primary" @click="addItems"><SvgIcon name="ele-CirclePlus" size="18px" class="mr3" /> 质检项</el-button>
			</el-divider>
			<el-row v-for="(item, index) in state.ruleForm.templateDetails" :key="item.id" :gutter="10">
				<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
					<el-form-item
						label="质检项"
						:prop="`templateDetails.${index}.obj`"
						:rules="[{ required: true, message: '请选择质检项', trigger: 'change' }]"
					>
						<el-select v-model="item.obj" placeholder="请选择质检项" class="w100" value-key="name" @change="changeProject($event, index)">
							<el-option v-for="items in projectArray" :key="items.id" :label="items.name" :value="items" :disabled="items.disabled" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
					<el-form-item label="AI质检" v-if="['YiBin'].includes(themeConfig.appScope)">
						{{ item.isIntelligent === 1 ? '是' : '否' }}
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
					<el-form-item label="扣分值"> {{ item.grade }} <span class="ml5">分</span> </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
					<el-form-item label="">
						<el-button link type="primary" @click="deleteProject(index)"> <SvgIcon name="ele-Delete" /> </el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">确 定 </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="qualityLexiconEdit">
import { reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { templateDetail, templateUpdate } from '@/api/quality/template';
import { projectList } from '@/api/quality/project';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

const props = defineProps({
	templateGrouping: {
		type: Array,
		default: () => [],
	},
});
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
// 定义变量内容
const ruleFormRef = ref<FormInstance>();
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		name: '', // 模板名称
		grouping: '', // 质检分类
		content: '', // 模板说明
		isEnable: 1, // 是否启用
		templateDetails: [
			{
        name: '',
        content: '',
        grade: 0,
        isIntelligent: 0,
        itemId:'',
        templateId: '',
			},
		],
	},
	loading: false, // 确定按钮loading
});
const projectArray = ref<EmptyArrayType>([]); // 质检项
// 打开弹窗
const openDialog = async (row: any) => {
	state.loading = true;
	state.dialogVisible = true;
	try {
		const res = await templateDetail(row.id);
		state.ruleForm = res.result ?? {};
		if (state.ruleForm.templateDetails && state.ruleForm.templateDetails.length) {
			for (let i of state.ruleForm.templateDetails) {
				i.obj = {
          name: i.name,
          describe: i.describe,
          grade: i.grade,
          isIntelligent: i.isIntelligent,
        };
			}
		}
		const response = await projectList({  IsEnable: 1,PageIndex:1,PageSize:999 });
		projectArray.value = response.result?.items ?? [];
    getEnableAcceptType();
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	state.ruleForm.templateDetails = [];
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
  state.ruleForm.templateDetails = [
    {
      name: '',
      content: '',
      grade: 0,
      isIntelligent: 0,
      itemId:'',
      templateId: '',
    }
  ]
};
// 新增质检项
const addItems = () => {
	state.ruleForm.templateDetails.unshift({
		name: '',
		content: '',
		grade: 0,
		isIntelligent: 0,
    itemId:'',
    templateId: '',
	});
	getEnableAcceptType();
};
// 选择质检项
const changeProject = (item: any, index: number | string) => {
  state.ruleForm.templateDetails[index].itemId = item.id;
  state.ruleForm.templateDetails[index].templateId = item.templateId;
  state.ruleForm.templateDetails[index].name = item.name;
  state.ruleForm.templateDetails[index].content = item.describe;
  state.ruleForm.templateDetails[index].grade = item.grade;
  state.ruleForm.templateDetails[index].isIntelligent = item.isIntelligent;
	getEnableAcceptType();
};
// 获取可用的数组
const getEnableAcceptType = () => {
	if (state.ruleForm.templateDetails.length) {
		const array = state.ruleForm.templateDetails.map((v: any) => v.name);
		projectArray.value.forEach((v: any) => {
			v.disabled = array.includes(v.name);
		});
	}
};
// 删除质检项
const deleteProject = (index: number | string) => {
  if (state.ruleForm.templateDetails.length === 1) {
    ElMessage.warning('请至少保留一个质检项');
    return;
  }
	ElMessageBox.confirm(`您确定要删除此质检项，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.ruleForm.templateDetails.splice(index, 1);
			getEnableAcceptType();
		})
		.catch(() => {});
};
// 新增
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		const request = {
			...state.ruleForm,
		};
		templateUpdate(request)
			.then(() => {
				emit('updateList');
				closeDialog(); // 关闭弹窗
				ElMessage.success('操作成功');
				state.loading = false;
			})
			.catch(() => {
				emit('updateList');
				state.loading = false;
			});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
