<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <el-row v-show="showSearch">
                <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
                    <el-form-item :label="t('formoption.type')" prop="type">
                        <el-select v-model="state.queryForm.type" :placeholder="t('formoption.inputTypeTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.FORM_DATA_TYPE" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="t('formoption.formType')" prop="formType">
                        <el-select v-model="state.queryForm.formType" :placeholder="t('formoption.inputFormTypeTip')" clearable
                                   filterable
                                   @change="formTypeChange">
                            <el-option v-for="(item, index) in DIC_PROP.FORM_TYPE" :key="index" :label="item.label"
                                       :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="t('formoption.formId')" prop="formId">
                        <el-select v-model="state.queryForm.formId" :placeholder="t('formoption.inputFormIdTip')" clearable filterable>
                            <el-option v-for="(item, index) in dicData.formIdByType" :key="index"
                                       :label="item.formName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('formoption.defFlowId')" prop="defFlowId">
                        <el-select v-model="state.queryForm.defFlowId" :placeholder="t('formoption.inputDefFlowIdTip')"
                                   clearable filterable @change="cascadeChange('defFlowId', ['flowNodeId'])">
                            <el-option v-for="(item, index) in dicData.defFlowId" :key="index" :label="item.flowName"
                                       :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="t('formoption.flowNodeId')" prop="flowNodeId">
                        <el-select v-model="state.queryForm.flowNodeId" :placeholder="t('formoption.inputFlowNodeIdTip')" clearable filterable>
                            <el-option v-for="(item, index) in cascadeDic.flowNodeId" :key="index" :label="item.nodeName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="search" type="primary" @click="getDataList">
                            {{ $t('common.queryBtn') }}
                        </el-button>
                        <el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <div class="mb8" style="width: 100%">
                    <el-button icon="CirclePlus" type="primary" class="ml10" @click="openFormDefPerm('add', null, '0')"
                               v-auth="'jsonflow_formoption_add'">字段定义
                    </el-button>
                    <el-button icon="Setting" type="primary" class="ml10" @click="openFormDefPerm('add', null, '1')"
                               v-auth="'jsonflow_formoption_add'">权限配置
                    </el-button>
                    <el-button icon="Pointer" type="primary" class="ml10" @click="handlePrintTemplate"
                               v-auth="'jsonflow_formoption_add'">打印设计
                    </el-button>
                    <el-button plain :disabled="multiple" icon="Delete" type="primary" class="ml10"
                               v-auth="'jsonflow_formoption_del'" @click="handleDelete(selectObjs)">
                        {{ $t('common.delBtn') }}
                    </el-button>
                    <right-toolbar v-model:showSearch="showSearch" class="ml10" style="float: right;margin-right: 20px"
                                   :export="'jsonflow_formoption_export'" @exportExcel="exportExcel"
                                   @queryTable="getDataList"></right-toolbar>
                </div>
            </el-row>
            <el-table :data="state.dataList" v-loading="state.loading" style="width: 100%"
                      @selection-change="handleSelectionChange" @sort-change="sortChangeHandle">
                <el-table-column type="selection" width="40" align="center" />
                <el-table-column fixed="left" type="index" :label="t('formoption.index')" width="40" />
                <el-table-column prop="type" :label="t('formoption.type')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.FORM_DATA_TYPE" :value="scope.row.type"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="formType" :label="t('formoption.formType')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.FORM_TYPE" :value="scope.row.formType"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="formName" :label="t('formoption.formName')" show-overflow-tooltip/>
                <el-table-column prop="path" :label="t('formoption.path')" show-overflow-tooltip/>
                <el-table-column prop="defFlowId" :label="t('formoption.defFlowId')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="dicData.defFlowId" :value="scope.row.defFlowId"
                                      :valueKey="'id'" :showKey="'flowName'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="flowNodeId" :label="t('formoption.flowNodeId')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="dicData.flowNodeId" :value="scope.row.flowNodeId"
                                      :valueKey="'id'" :showKey="'nodeName'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="propId" :label="t('formoption.propId')" show-overflow-tooltip/>
                <el-table-column prop="label" :label="t('formoption.label')" show-overflow-tooltip/>
                <el-table-column prop="prop" :label="t('formoption.prop')" show-overflow-tooltip/>
                <el-table-column prop="subForm" :label="t('formoption.subForm')" show-overflow-tooltip/>
                <el-table-column prop="propType" :label="t('formoption.propType')" show-overflow-tooltip/>
                <el-table-column prop="permType" :label="t('formoption.permType')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.FORM_PERM_TYPE" :value="scope.row.permType"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="printInfo" :label="t('formoption.printInfo')" show-overflow-tooltip/>
                <el-table-column :label="$t('common.action')" fixed="right" width="100">
                    <template #default="scope">
                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.viewBtn') }}
                            </template>
                            <el-button text type="primary" icon="view" @click="formDialogRef.openDialog('view', scope.row.id)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.editBtn') }}
                            </template>
                            <el-button icon="edit-pen" text type="primary" @click="handleRowEdit(scope.row)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.delBtn') }}
                            </template>
                            <el-button icon="delete" text type="primary" @click="handleDelete([scope.row.id])">
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
        </div>

        <!-- 编辑、新增  -->
        <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

        <!-- 打印模板设计器 -->
        <el-drawer class="tinymce-print-drawer" append-to-body direction="rtl"
                   v-model="data.showTinymceEditor" size="100%"
                   :title="data.tinymceTitle" @close="getDataList">
            <tinymce-editor v-if="data.showTinymceEditor" :currFlowForm="data.currFlowForm"></tinymce-editor>
        </el-drawer>

        <el-dialog title="新增或修改" v-model="data.formDefPermVisible" width="80%"
                   v-if="data.formDefPermVisible"
                   :close-on-click-modal="false" draggable>
            <form-def-perm :formDefPerm="data.formDefPerm" ref="formDefPermRef" @refresh="getDataList(false)" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="FormOption">
    import { BasicTableProps, useTable } from "/@/hooks/table";
    import { fetchList, delObjs } from "/@/api/jsonflow/form-option";
    import { useMessage, useMessageBox } from "/@/hooks/message";
    import { useI18n } from "vue-i18n";
    import {onCascadeChange, onLoadDicUrl} from "/@/flow/components/convert-name/convert";
    import {DIC_PROP} from "/@/flow/support/dict-prop";
    import {deepClone} from "/@/utils/other";

    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    const FormDefPerm = defineAsyncComponent(() => import('./form-def-perm.vue'));
    const TinymceEditor = defineAsyncComponent(() => import('/@/flow/components/tinymce/TinymceEditor.vue'));
    const { t } = useI18n()

    // 定义查询字典
    const dicData = reactive({});
    const cascadeDic = reactive({});
    const onLoad = onLoadDicUrl({key: "defFlowId"}, {key: "flowNodeId"}, {key: "formId"});
    const onCascade = onCascadeChange(cascadeDic, {key: "defFlowId", cascades: ["flowNodeId"]});
    onMounted(() => {
        onLoad(dicData);
    });
    function cascadeChange(key, cascades){
        onCascade(state.queryForm, {key: key, cascades: cascades});
    }

    // 定义变量内容
    const formDialogRef = ref()
    const formDefPermRef = ref()
    // 搜索变量
    const queryRef = ref()
    const showSearch = ref(true)
    // 多选变量
    const selectObjs = ref([]) as any
    const multiple = ref(true)

    const state: BasicTableProps = reactive<BasicTableProps>({
        queryForm: {},
        pageList: fetchList,
        descs: ["create_time"]
    })

    //  table hook
    const {
        getDataList,
        currentChangeHandle,
        sizeChangeHandle,
        sortChangeHandle,
        downBlobFile
    } = useTable(state)

    // 清空搜索条件
    const resetQuery = () => {
        queryRef.value.resetFields()
        // 清空多选
        selectObjs.value = []
        getDataList()
    }

    // 多选事件
    const handleSelectionChange = (objs: any) => {
        selectObjs.value = objs.map(({ id }) => id);
        multiple.value = !objs.length
    }

    // 导出excel
    const exportExcel = () => {
        downBlobFile('/jsonflow/form-option/export', state.queryForm, 'formoption.xlsx')
    }

    // 删除操作
    const handleDelete = async (ids: string[]) => {
        try {
            await useMessageBox().confirm(t('common.delConfirmText'));
        } catch {
            return;
        }

        try {
            await delObjs(ids);
            getDataList();
            useMessage().success(t('common.delSuccessText'));
        } catch (err: any) {
            useMessage().error(err);
        }
    };

    const formTypeChange = (value) => {
        if (value) dicData.formIdByType = dicData.formId.filter(f => f.type === value)
        else dicData.formIdByType = []
        state.queryForm.formId = null
    }

    function handleRowEdit(row){
        if (row.type === DIC_PROP.FORM_DATA_TYPE[2].value) {
            handlePrintTemplate(row, true)
        } else {
            formDialogRef.value.openDialog('edit', row.id)
        }
    }

    const data = reactive({
        currFlowForm: {},
        showTinymceEditor: false,
        formDefPermVisible: false,
        formDefPerm: {},
        tinymceTitle: '',
    })

    const openFormDefPerm = async (type: string, id: string, dataType: string) => {
        data.formDefPermVisible = true
        data.formDefPerm = {type, id, dataType}
    }

    function handlePrintTemplate(row, isExist) {
        data.currFlowForm = {}
        if (isExist) {
            data.currFlowForm = deepClone(row)
            data.currFlowForm.isForm = true
        }
        data.tinymceTitle = "打印模板设计器（自定义打印格式）"
        data.showTinymceEditor = true
    }

</script>

<style lang="scss">
  @import "../../../flow/components/style/flow-drawer.scss";
</style>
