<script lang="ts" setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { save, nameCheck, findOne, categoryTemplateNameCheck } from '@/api/template'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus-secondary'
import { useI18n } from '@/hooks/web/useI18n'
import { imgUrlTrans } from '@/utils/imgUtils'
import { findCategories } from '@/api/template'
import AddTemplateClass from '@/viewsnew/TemplateResource/addclass.vue'
const props = defineProps({
    classList: {
        type: Array,
        required: true
    },
    optType: {
        type: String,
        required: true,
        default: 'insert'
    },

})
const emits = defineEmits(['closeTemplateDialog', 'init'])
const { t } = useI18n()
const importform = ref({ name: '' })
const ruleFormRef = ref<FormInstance>()
const pid = ref('')
const filesRef = ref(null)
const maxImageSize = 35000000
const dialogVisible = ref(false)
const state = reactive({
    categories: [],
    nameList: [],
    importTemplateInfo: {
        snapshot: ''
    },
    templateInfoRules: {
        name: [
            {
                required: true,
                message: t('commons.input_content'),
                trigger: 'change'
            },
            {
                max: 50,
                message: t('commons.char_can_not_more_50'),
                trigger: 'change'
            }
        ],
        categories: [
            {
                required: true,
                message: t('commons.input_content'),
                trigger: 'change'
            }
        ]
    },
    recover: false,
    templateInfo: {
        id: null,
        level: '1',
        pid: pid,
        categories: [],
        dvType: 'dashboard',
        nodeType: 'template',
        name: '',
        templateStyle: null,
        templateData: null,
        dynamicData: null,
        appData: null,
        staticResource: null,
        snapshot: '',
        version: null
    },
    templateCategories: []
})
const handleFileChange = e => {
    const file = e.target.files[0]
    const reader = new FileReader()
    if (file.size > maxImageSize) {
        ElMessage.success(t('template_manage.template_size_hint'))
        return
    }
    reader.onload = res => {
        const result = res.target.result as string
        state.importTemplateInfo = JSON.parse(result)
        state.templateInfo.name = state.importTemplateInfo['name']
        state.templateInfo.dvType = state.importTemplateInfo['dvType']
        state.templateInfo.templateStyle = state.importTemplateInfo['canvasStyleData']
        state.templateInfo.templateData = state.importTemplateInfo['componentData']
        state.templateInfo.snapshot = state.importTemplateInfo.snapshot
        state.templateInfo.dynamicData = state.importTemplateInfo['dynamicData']
        state.templateInfo.appData = state.importTemplateInfo['appData']
        state.templateInfo.staticResource = state.importTemplateInfo['staticResource']
        state.templateInfo['nodeType'] = state.importTemplateInfo['nodeType'] || 'template'
        state.templateInfo['version'] = state.importTemplateInfo['version']
    }

    importform.value.name = state.importTemplateInfo['name']
    console.log(importform.value.name, 9999)
    reader.readAsText(file)
}
const goFile = () => {
    filesRef.value.click()
}
const classBackground = computed(() => {
    if (state.templateInfo.snapshot) {
        return {
            background: `url(${imgUrlTrans(state.templateInfo.snapshot)}) no-repeat`
        }
    } else {
        return {}
    }
})
onMounted(() => {
    queryclass()
})
function queryclass() {
    const request = {
        templateType: 'self',
        level: '0'
    }
    findCategories(request).then(res => {
        state.templateCategories = res.data
        console.log(res.data)
    })
}
function saveTemplate() {
    if (!state.templateInfo.name) {
        ElMessage.warning(t('chart.name_can_not_empty'))
        return false
    }
    if (state.templateInfo.name.length > 50) {
        ElMessage.warning(t('commons.char_can_not_more_50'))
        return false
    }
    if (!state.templateInfo.templateData) {
        ElMessage.warning(t('chart.template_can_not_empty'))
        return false
    }

    if (!state.templateInfo.categories.length) {
        ElMessage.warning(t('template_manage.please_select_catalog'))
        return false
    }
    if (props.optType === 'insert') {
        importTemplate()
    } else {
        editTemplate()
    }
}
const editTemplate = () => {
    const nameCheckRequest = {
        pid: state.templateInfo.pid,
        id: state.templateInfo.id,
        name: state.templateInfo.name,
        categories: state.templateInfo.categories,
        optType: props.optType
    }
    // 全局名称校验
    nameCheck(nameCheckRequest).then(response => {
        if (response.data.indexOf('exist') > -1) {
            ElMessage.warning('当前分类存在相同模板名称，是否覆盖')
        } else {
            save(state.templateInfo).then(() => {
                ElMessage.success('导入成功')
                emits('init')
                emits('closeTemplateDialog')
            })
        }
    })
}
const importTemplate = () => {
    const nameCheckRequest = {
        pid: state.templateInfo.pid,
        name: state.templateInfo.name,
        categories: state.templateInfo.categories,
        optType: props.optType
    }
    categoryTemplateNameCheck(nameCheckRequest).then(response => {
        if (response.data.indexOf('exist') > -1) {
            ElMessageBox.confirm('提示', {
                tip: '当前分类存在相同模板名称，是否覆盖？',
                confirmButtonType: 'danger',
                type: 'warning',
                autofocus: false,
                showClose: false
            }).then(() => {
                save(state.templateInfo).then(() => {
                    ElMessage.success('导入成功')
                    emits('init')
                    emits('closeTemplateDialog')
                })
            })
        } else {
            // 全局名称校验
            nameCheck(nameCheckRequest).then(response => {
                if (response.data.indexOf('exist') > -1) {
                    ElMessage.warning('当前名称已在模版管理中存在，请修改')
                } else {
                    save(state.templateInfo).then(() => {
                        ElMessage.success(t('导入成功'))
                        emits('init')
                        emits('closeTemplateDialog')
                    })
                }
            })
        }
    })
}

function cancel() {
    emits('closeTemplateDialog')
}
function addclassclick() {
    dialogVisible.value = true
}
function closeClassDialog() {
    dialogVisible.value = false
}
function classrefresh(){
    queryclass()
}
</script>
<template>
    <div class="template-import">
        <el-form ref="ruleFormRef" :model="state.templateInfo" label-width="80px">
            <el-form-item label="模板名称" prop="name">
                <div class="flex-template">
                    <el-input v-model="state.templateInfo.name" />
                    <el-button style="margin-left: 10px" icon="Upload" @click="goFile">导入模板</el-button>
                </div>
                <input id="input" ref="filesRef" type="file" accept=".DET2,.DET2APP" hidden
                    @change="handleFileChange" />
            </el-form-item>
            <el-row v-show="!!state.templateInfo.snapshot" class="preview" :style="classBackground" />
            <el-form-item label="分类" prop="name">
                <el-select v-model="state.templateInfo.categories" multiple placeholder="请选择分类" style="width: 100%">
                    <el-option v-for="item in state.templateCategories" :key="item.id" :label="item.name"
                        :value="item.id" />
                    <template #footer>
                        <div class="class-add" @click="addclassclick">
                            添加分类
                        </div>
                    </template>
                </el-select>
            </el-form-item>
        </el-form>
        <div style="display: flex;justify-content: flex-end;">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="saveTemplate">确定</el-button>
        </div>
        <el-dialog v-model="dialogVisible" append-to-body title="添加分类" width="30%" :before-close="closeClassDialog">
            <AddTemplateClass v-if="dialogVisible" @classrefresh="classrefresh" @closeClassDialog="closeClassDialog" />
        </el-dialog>
    </div>
</template>

<style lang="less" scoped>
.preview {
    margin-top: -8px;
    border: 1px solid #e6e6e6;
    height: 300px !important;
    overflow: auto;
    background-size: 100% 100% !important;
    border-radius: 4px;
    margin-bottom: 10px;
}

.flex-template {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-input {
        margin-right: 2px;
        flex: 1;
    }
}

.class-add {
    width: 100%;
    background-color: transparent;
    padding: 10px;
    font-size: 14px;
    cursor: pointer;
}

.class-add:hover {
    background-color: #434343;
    ;
}
</style>