<template>
    <div class="default-main">
        <div class="mb10 pt10" style="display: flex; justify-content: flex-end">
            <el-upload ref="upload" action="" :auto-upload="false" :show-file-list="false" :limit="1"
                :on-change="beforeUpload">
                <el-button icon="el-icon-Upload" type="primary" class="mr10">导入excel</el-button>
            </el-upload>
            <el-button @click="downloadExcel" class="" type="primary" icon="el-icon-Download">导出</el-button>
            <el-button type="primary" icon="el-icon-Check" @click="preservation">保存</el-button>
            <el-button icon="el-icon-Back" @click="emit('shutDown')">返回</el-button>
        </div>

        <div style="display: flex">
            <div id="luckysheet" :style="{ height: height, flex: 1 }"></div>
            <bind style="width: 410px" class="ml10" @setValue="setValue" />
        </div>
        <!-- 信息框 -->
        <addForm ref="formFer" @submitForm="submitForm" />
    </div>
</template>
<script setup lang="ts">
import { exportExcel } from './export.js'
import { mainHeight } from '@/utils/layout'
import LuckyExcel from 'luckyexcel'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { addTemplate, dateTemplateup, viewCustomReportTemplateById } from '@/api/harmonic-boot/luckyexcel'
import bind from './bind.vue'
import addForm from './form.vue'
const emit = defineEmits(['shutDown'])
const formFer = ref()
const title = ref('')
const list = ref({})
const height = mainHeight(75).height
const options: any = ref({
    container: 'luckysheet',
    title: '', // 表 头名
    lang: 'zh', // 中文
    showtoolbar: true, // 是否显示工具栏
    showinfobar: false, // 是否显示顶部信息栏
    showsheetbar: true, // 是否显示底部sheet按钮
    data: [
        {
            name: 'Cell',
            index: 0,
            defaultRowHeight: 27,
            defaultColWidth: 105,
            chart: [] //图表配置
        }
    ]
})
// 加载luckysheet
const info = () => {
    luckysheet.create(options.value)
}
//绑定value
const setValue = (e: any, frontAndBack: number) => {
    let data = luckysheet.getRange()
    luckysheet.setCellValue(
        data[0].row[0],
        data[0].column[0],
        {
            v: frontAndBack == 0 ? e[e.length - 1] : `~` + e[e.length - 1],
            tr: e
        }
        //  checkedNodes[0].data.label
    )
}
// 下载表格
const downloadExcel = () => {
    exportExcel(luckysheet.getAllSheets(), '报表模板')
}
// 导入
const beforeUpload = (file: any) => {
    LuckyExcel.transformExcelToLucky(file.raw, function (exportJson: any) {
        if (exportJson.sheets == null || exportJson.sheets.length == 0) {
            ElMessage.warning('读取excel文件内容失败,目前只能上传xlsx文件!')
            return
        }
        luckysheet.destroy()
        options.value.title = exportJson.info.name
        exportJson.sheets.forEach((item: any) => {
            // item.celldata = []
            // item.data = []
            item.celldata.forEach((k: any) => {
                k.v.ct.s ? (k.v.v = k.v.ct.s[0].v) : ''
                k.v.ct.s ? (k.v.m = k.v.ct.s[0].v) : ''
            })
        })
        options.value.data = exportJson.sheets
        luckysheet.create(options.value)
    })
}
// 保存
const preservation = () => {
    formFer.value.open(title.value, list.value)
}
// 新增
const submitForm = (formdata: any, text: string) => {
    // let userStr = JSON.stringify(luckysheet.getAllSheets())
    let userStr = luckysheet.getAllSheets()
    userStr.forEach((item: any) => {
        item.data1 = JSON.stringify(item.data)
    })

    let blob = new Blob([JSON.stringify(userStr)], {
        type: 'application/json;charset=UTF-8'
    })
    let files = new window.File([blob], 'content.json', {
        type: 'application/json;charset=UTF-8'
    })
    let params = new FormData()

    params.append('fileContent', files)
    params.append('deptId', formdata.deptId)
    params.append('valueTitle', formdata.deptId)
    params.append('name', formdata.name)
    params.append('reportType', formdata.reportType)
    params.append('reportForm', formdata.reportForm)
    params.append('wiringMethod', formdata.wiringMethod)
    params.append('sort', formdata.sort)
    ElMessage.info('正在保存请稍等!')
    if (text == '新增报表模板') {
        addTemplate(params)
            .then(res => {
                ElMessage.success('新增成功!')
                formFer.value.shutDown()
                emit('shutDown')
            })
            .catch(err => {
                ElMessage.error('保存失败!')
                formFer.value.shutDown()
            })
    } else if (text == '编辑报表模板') {
        params.append('id', list.value.id)
        dateTemplateup(params)
            .then(res => {
                ElMessage.success('编辑成功!')
                formFer.value.shutDown()
                emit('shutDown')
            })
            .catch(err => {
                ElMessage.error('保存失败!')
                formFer.value.shutDown()
            })
    }
}
const open = async (text: string, row?: any) => {
    title.value = text
    if (row) {
        list.value = row
        await viewCustomReportTemplateById({ id: row.id }).then(Response => {
            options.value.data = Response
        })
    }
    info()
}
defineExpose({ open })
onMounted(() => { })
</script>
<style lang="scss" scoped>
:deep(.el-tab-pane) {
    padding: 10px;
}
</style>
