<template>
    <ProDrawer ref="proDrawerRef" @handle-cancel="handleCancel" @handle-confirm="handleConfirm">
        <el-form v-model="form">
            <el-form-item label="设置为默认模板">
                <el-switch v-model="form.isDefault" :active-value="1" :inactive-value="0" />
            </el-form-item>
            <el-form-item label="模板名称">
                <el-input v-model="form.templateName" placeholder="请输入" maxlength="20" show-word-limit />
            </el-form-item>
            <el-form-item label="模板类型">
                <el-radio-group v-model="form.templateType">
                    <el-radio v-for="type in types" :key="type.value" :label="type.value">{{ type.label }}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="模板内容">
                <el-button type="primary" plain @click="handleAddItem">新增模板项</el-button>
            </el-form-item>
            <add-item
                v-for="(item, index) in form.templateItems"
                :key="index"
                :item="item"
                :index="index"
                @handle-copy-item="handleCopyItem"
                @handle-delete-item="handleDeleteItem"
            />
        </el-form>
    </ProDrawer>
</template>

<script setup lang="ts">
import ProDrawer, { type IParams } from '@/components/ProDrawer/index.vue'
import addItem from './add-item.vue'

export interface Item {
    formType: number
    formTitle: string
}
interface IForm {
    templateName: string
    templateType: number
    isDefault: number
    templateItems: Item[]
}
const emit = defineEmits(['refreshList'])
const proDrawerRef = ref<InstanceType<typeof ProDrawer>>()

const types = ref([
    { label: '电销', value: 1 },
    { label: '招生', value: 2 }
])
const form = ref<IForm>({
    templateName: '',
    templateType: 1,
    isDefault: 1,
    templateItems: []
})
const handleAddItem = () => {
    form.value.templateItems.push({
        formType: 1,
        formTitle: ''
    })
}
const handleCopyItem = (index: number) => {
    form.value.templateItems.splice(index, 0, {
        formType: 1,
        formTitle: ''
    })
}
const handleDeleteItem = (index: number) => {
    form.value.templateItems.splice(index, 1)
}
const openDrawer = (params: IParams) => {
    proDrawerRef.value?.openDrawer(params)
}
const handleCancel = (callback: () => void) => {
    callback()
}
const handleConfirm = (callback: () => void) => {
    callback()
    emit('refreshList')
}
defineExpose({
    openDrawer
})
</script>
<style scoped></style>
