<template>
    <ProDrawer ref="proDrawerRef" @handle-cancel="handleCancel" @handle-confirm="handleConfirm">
        <el-form ref="formRef" :rules="rules" :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="模板名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" maxlength="20" show-word-limit />
            </el-form-item>
            <el-form-item label="模板类型" prop="postId">
                <el-radio-group v-model="form.postId">
                    <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="模板内容" prop="templateFormList">
                <el-button type="primary" plain @click="handleAddItem">新增模板项</el-button>
            </el-form-item>
            <add-item
                v-for="(item, index) in form.templateFormList"
                :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'
import { postLists } from '@/api/account_center/postion'
import type { FormInstance } from 'element-plus'
import { templateAdd, templateDetail, templateEdit } from '@/api/summary'
import feedback from '@/utils/feedback'

export interface Item {
    formType: number
    formTitle: string
}

interface IForm {
    id: string
    name: string
    postId: number | null
    isDefault: number
    templateFormList: Item[]
}
const emit = defineEmits(['refreshList'])

const proDrawerRef = ref<InstanceType<typeof ProDrawer>>()
const types = ref<any[]>([])
const fetchPosition = async () => {
    try {
        const result = await postLists()
        types.value = result.lists.map(item => ({
            label: item.name,
            value: item.id
        }))
    } catch (error) {}
}
fetchPosition()
const validateTemplateFormList = (rule: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error('请新增模板内容'))
    } else {
        if (value.length > 0) {
            const findItem = value.find(item => item.formTitle === '')
            if (findItem) {
                return callback(new Error('表单标题不能为空'))
            } else {
                callback()
            }
        }
    }
}
const formRef = ref<FormInstance>()
const rules = reactive({
    name: { required: true, message: '请输入模板名称', trigger: 'blur' },
    postId: { required: true, message: '请选择模板类型', trigger: 'change' },
    templateFormList: [{ required: true, message: '请新增模板内容', trigger: 'blur' }, { validator: validateTemplateFormList }]
})
const form = ref<IForm>({
    id: '',
    name: '',
    postId: null,
    isDefault: 1,
    templateFormList: []
})
const handleAddItem = () => {
    form.value.templateFormList.push({
        formType: 1,
        formTitle: ''
    })
}
const handleCopyItem = (index: number) => {
    form.value.templateFormList.splice(index + 1, 0, {
        formType: 1,
        formTitle: ''
    })
}
const handleDeleteItem = (index: number) => {
    form.value.templateFormList.splice(index, 1)
}
const openDrawer = (params: IParams) => {
    clearForm()
    const { data } = params
    if (data.id) fetchDetail(data.id)
    proDrawerRef.value?.openDrawer(params)
}
const handleCancel = (callback: () => void) => {
    callback()
}
const handleConfirm = (callback: () => void) => {
    const { id } = form.value
    formRef.value?.validate(async valid => {
        if (!valid) return
        try {
            const api = id ? templateEdit : templateAdd
            await api(form.value)
            const msg = id ? '编辑' : '新增'
            feedback.msgSuccess(`${msg}成功`)
            callback()
            emit('refreshList')
        } catch (error) {}
    })
}

const fetchDetail = async (id: number) => {
    try {
        const result = await templateDetail({ id })
        setFormData(result)
    } catch (error) {}
}
const setFormData = result => {
    for (const key in result) {
        if (Object.prototype.hasOwnProperty.call(form.value, key) && (result[key] != null || result[key] !== undefined)) {
            form.value[key] = result[key]
        }
    }
}
const clearForm = () => {
    form.value = {
        id: '',
        name: '',
        postId: null,
        isDefault: 1,
        templateFormList: []
    }
    formRef.value?.resetFields()
}
defineExpose({
    openDrawer
})
</script>
<style scoped></style>
