<template>
    <div class="univer-container">
        <div ref="container" class="univer" />
        <el-button size="small" @click="getData" type="primary" plain
            >保存</el-button
        >
    </div>
</template>
<script lang="ts" setup>
import "@univerjs/sheets-data-validation/lib/index.css";

import {
    Univer,
    UniverInstanceType,
    Workbook,
    LocaleType,
    IWorkbookData,
    Tools,
    useDependency,
    IUniverInstanceService,
    IPermissionService,
    ICommandService,
    DataValidationType,
} from "@univerjs/core";
import { defaultTheme } from "@univerjs/design";
import { UniverDocsPlugin } from "@univerjs/docs";
import { UniverDocsUIPlugin } from "@univerjs/docs-ui";
import { UniverFormulaEnginePlugin } from "@univerjs/engine-formula";
import { UniverRenderEnginePlugin } from "@univerjs/engine-render";
import {
    UniverSheetsPlugin,
    getSheetCommandTarget,
    AddRangeProtectionMutation,
    RangeProtectionPermissionEditPoint,
} from "@univerjs/sheets";
import { UniverSheetsFormulaPlugin } from "@univerjs/sheets-formula";
import { UniverSheetsUIPlugin } from "@univerjs/sheets-ui";
import { UniverUIPlugin } from "@univerjs/ui";
import { UniverDataValidationPlugin } from "@univerjs/data-validation";
import {
    UniverSheetsDataValidationPlugin,
    DATA_VALIDATION_PLUGIN_NAME,
} from "@univerjs/sheets-data-validation";
import { FUniver } from "@univerjs/facade";

import DesignZhCN from "@univerjs/design/locale/zh-CN";
import UIZhCN from "@univerjs/ui/locale/zh-CN";
import DocsUIZhCN from "@univerjs/docs-ui/locale/zh-CN";
import SheetsZhCN from "@univerjs/sheets/locale/zh-CN";
import SheetsUIZhCN from "@univerjs/sheets-ui/locale/zh-CN";
import SheetsDataValidationZhCN from "@univerjs/sheets-data-validation/locale/zh-CN";

import { PETITION_COMPLAINT_HEAD_DATA } from '@/data/excelData'

/**
 *
 * The ability to import locales from virtual modules and automatically import styles is provided by Univer Plugins. For more details, please refer to: https://univer.ai/guides/sheet/advanced/univer-plugins.
 * If you encounter issues while using the plugin or have difficulty understanding how to use it, please disable Univer Plugins and manually import the language packs and styles.
 *
 * 【从虚拟模块导入语言包】以及【自动导入样式】是由 Univer Plugins 提供的能力，详情参考：https://univer.ai/zh-CN/guides/sheet/advanced/univer-plugins
 * 如果您在使用该插件的时候出现了问题，或者无法理解如何使用，请禁用 Univer Plugins，并手动导入语言包和样式
 */
// import { zhCN, enUS } from 'univer:locales'

const { data } = defineProps({
    // workbook data
    data: {
        type: Object,
        default: () => ({}),
    },
});

const univerRef = ref<Univer | null>(null);
const workbook = ref<Workbook | null>(null);
const container = ref<HTMLElement | null>(null);

onMounted(() => {
    init(PETITION_COMPLAINT_HEAD_DATA)
});

onBeforeUnmount(() => {
    destroyUniver();
});

let univer;
/**
 * Initialize univer instance and workbook instance
 * @param data {IWorkbookData} document see https://univer.ai/typedoc/@univerjs/core/interfaces/IWorkbookData
 */
const init = (data = {}) => {
    univer = new Univer({
        theme: defaultTheme,
        locale: LocaleType.ZH_CN,
        locales: {
            [LocaleType.ZH_CN]: Tools.deepMerge(
                SheetsZhCN,
                DocsUIZhCN,
                SheetsUIZhCN,
                UIZhCN,
                DesignZhCN,
                SheetsDataValidationZhCN
            ),
        },
    });
    univerRef.value = univer;

    // core plugins
    // univer.registerPlugin(UniverRenderEnginePlugin);
    // univer.registerPlugin(UniverFormulaEnginePlugin);
    univer.registerPlugin(UniverUIPlugin, {
        container: container.value!,
        toolbar: false
    });

    // doc plugins
    univer.registerPlugin(UniverDocsPlugin, {
        hasScroll: false,
    });
    univer.registerPlugin(UniverDocsUIPlugin);

    // sheet plugins
    univer.registerPlugin(UniverSheetsPlugin);
    univer.registerPlugin(UniverSheetsUIPlugin);
    univer.registerPlugin(UniverSheetsFormulaPlugin);
    univer.registerPlugin(UniverDataValidationPlugin);
    univer.registerPlugin(UniverSheetsDataValidationPlugin);

    // create workbook instance
    workbook.value = univer.createUnit<IWorkbookData, Workbook>(
        UniverInstanceType.UNIVER_SHEET,
        data
    );

    const univerAPI = FUniver.newAPI(univer);
    console.log(univerAPI);
    const injector = univer.__getInjector();
    const get = injector.get.bind(injector);
    const permissionService = get(IPermissionService);
    const commandService = get(ICommandService);
    const unitId = data.id;
    const sheet = workbook.value.getActiveSheet();
    const subUnitId = sheet.getSheetId();

    commandService.executeCommand(AddRangeProtectionMutation.id, {
        unitId,
        subUnitId,
        rules: [
            {
                permissionId: "xx1",
                id: "33dddxx",
                name: "sxx",
                unitType: 3,
                unitId,
                subUnitId,
                ranges: [
                    {
                        startRow: 0,
                        endRow: 1,
                        startColumn: 0,
                        endColumn: 2,
                    },
                ],
            },
        ],
    });
    setTimeout(() => {
        console.log("setTimeout");
        console.log(permissionService)
        console.log(new RangeProtectionPermissionEditPoint(unitId, subUnitId, "xx1").id)
        permissionService.updatePermissionPoint(
            new RangeProtectionPermissionEditPoint(unitId, subUnitId, "xx1").id,
            false
        );
    }, 600);
};

/**
 * Destroy univer instance and workbook instance
 */
const destroyUniver = () => {
    toRaw(univerRef.value)?.dispose();
    univerRef.value = null;
    workbook.value = null;
};

/**
 * Get workbook data
 */
const getData = () => {
    if (!workbook.value) {
        throw new Error("Workbook is not initialized");
    }
    console.log(workbook.value);

    console.log(workbook.value.save());
    return;
};

defineExpose({
    getData,
    destroyUniver,
});
</script>
  <style lang="scss" scoped>
.univer-container {
    height: 100%;
    position: relative;
    padding: 10px;
    .univer {
        height: calc(100% - 20px);
        border: 1px solid #aaa;
        box-sizing: border-box;
    }
}
.el-button {
    position: absolute;
    top: 14px;
    left: 20px;
    z-index: 11;
}
</style>