<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('flowApplication.formName')" prop="formName" >
                        <el-input :placeholder="t('flowApplication.inputFormNameTip')" v-model="state.queryForm.formName" clearable
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('flowApplication.status')" prop="status" >
                        <el-select v-model="state.queryForm.status" :placeholder="t('flowApplication.inputStatusTip')" clearable style="max-width: 180px">
                            <el-option v-for="(item, index) in DIC_PROP.TEMP_STATUS" :key="index" :label="item.label" :value="item.value"></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-tooltip placement="top">
                        <template #content>
                            {{ $t('jfI18n.oneBtnDesign') }}
                        </template>
                        <el-button v-auth="'order_flowapplication_add'" type="primary" class="ml10" icon="Pointer"
                                   @click="handleDesignFlow(true)">
                        </el-button>
                    </el-tooltip>

<!--                    <el-tooltip placement="top">
                        <template #content>
                            {{ $t('common.addBtn') }}
                        </template>
                        <el-button icon="Plus" type="primary" class="ml10" @click="formDialogRef.openDialog('add')"
                                   v-auth="'jsonflow_tabsoption_add'">
                        </el-button>
                    </el-tooltip>-->

                    <el-tooltip placement="top">
                        <template #content>
                            {{ $t('common.delBtn') }}
                        </template>
                        <el-button plain :disabled="multiple" icon="Delete" type="primary" class="ml10"
                                   v-auth="'order_flowapplication_del'" @click="handleDelete(selectObjs)">
                        </el-button>
                    </el-tooltip>

                    <right-toolbar v-model:showSearch="showSearch" 	:export="'order_flowapplication_export'"
                                   @exportExcel="exportExcel" class="ml10" style="float: right;margin-right: 20px"
                                   @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 type="index" :label="t('flowApplication.index')" width="60" />
<!--                <el-table-column prop="flowKey" :label="t('flowApplication.flowKey')"  show-overflow-tooltip/>-->
                <el-table-column prop="icon" :label="t('flowApplication.icon')"  show-overflow-tooltip>
                    <template #default="scope">
                        <SvgIcon :name="scope.row.icon" :size="20" color="#409EFF"/>
                    </template>
                </el-table-column>
                <el-table-column prop="formName" :label="t('flowApplication.formName')"  show-overflow-tooltip/>
                <el-table-column prop="groupName" :label="t('flowApplication.groupName')"  show-overflow-tooltip/>
<!--                <el-table-column prop="tableName" :label="t('flowApplication.tableName')"  show-overflow-tooltip/>
                <el-table-column prop="permission" :label="t('flowApplication.permission')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="dicData.permission" :value="scope.row.permission"
                                      :valueKey="'roleId'" :showKey="'roleName'"></convert-name>
                    </template>
                </el-table-column>-->
                <el-table-column prop="remark" :label="t('flowApplication.remark')"  show-overflow-tooltip/>
                <el-table-column prop="type" :label="t('flowApplication.type')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.FORM_TYPE" :value="scope.row.type"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" :label="t('flowApplication.status')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.TEMP_STATUS" :value="scope.row.status"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="version" :label="t('flowApplication.version')"  show-overflow-tooltip/>
<!--                <el-table-column prop="createUser" :label="t('flowApplication.createUser')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.createUser" :value="scope.row.createUser"
                                      :valueKey="'userId'" :showKey="'name'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" :label="t('flowApplication.createTime')"  show-overflow-tooltip/>-->
                <el-table-column :label="$t('common.action')" width="200">
                    <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="formDialogRef.openDialog('edit', scope.row.id)">
                            </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>

                        <el-tooltip placement="top" v-if="scope.row.tableName">
                            <template #content>
                                {{ $t('jfI18n.viewForm') }}
                            </template>
                            <el-button icon="ZoomIn" text type="primary" @click="handleViewOrder(scope.row)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip placement="top" v-if="scope.row.defFlowId">
                            <template #content>
                                {{ $t('jfI18n.viewFlow') }}
                            </template>
                            <el-button icon="Share" text type="primary" @click="openPreview(scope.row.defFlowId)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip placement="top" v-if="scope.row.status === '-1' || scope.row.status === '1'">
                            <template #content>
                                {{ $t('jfI18n.printTemplate') }}
                            </template>
                            <el-button icon="Document" text type="primary" @click="handlePrintTemplate(scope.row)">
                            </el-button>
                        </el-tooltip>

                        <el-tooltip placement="top" v-if="scope.row.status === '-1' || scope.row.status === '1'">
                            <template #content>
                                {{ $t('jfI18n.onceMoreDesign') }}
                            </template>
                            <el-button text type="primary" icon="Pointer" v-auth="'order_flowapplication_edit'"
                                       @click.native="handleDesignFlow(true, scope.row)">
                            </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="flow-overflow-drawer" direction="rtl"
                append-to-body size="100%"
                v-model="data.showDesignFlow"
                :with-header="false"
        >
            <flow-form-design v-if="data.showDesignFlow" :currFlowForm="data.currFlowForm" @handleDesignFlow="handleDesignFlow"></flow-form-design>
        </el-drawer>

        <el-dialog v-model="data.showHandleForm"
                top="20px" width="90%"
                title="查看表单" append-to-body>
            <custom-form v-if="data.showHandleForm" :curr-job="data.currFlowForm" @onHandleForm="onHandleForm"></custom-form>
        </el-dialog>

        <!-- 查看表单 -->
        <el-dialog v-model="data.showViewOrder" top="20px" width="90%"
                   title="查看表单" append-to-body>
            <form-render v-if="data.showViewOrder" :currFlowForm="data.currFlowForm" :renderType="'-1'"></form-render>
        </el-dialog>

        <!-- 查看流程图 -->
        <el-drawer
                class="flow-overflow-drawer" direction="rtl"
                append-to-body size="90%"
                v-model="data.showFlowPic"
        >
            <flow-photo :currJob="data.currFlowForm" v-if="data.showFlowPic"></flow-photo>
        </el-drawer>

        <!-- 打印模板设计器 -->
        <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>
    </div>
</template>

<script setup lang="ts" name="systemFlowApplication">
    import { BasicTableProps, useTable } from "/@/hooks/table";
    import {fetchList, delObjs, putObj} from "/@/api/order/flow-application";
    import { useMessage, useMessageBox } from "/@/hooks/message";
    import { useI18n } from "vue-i18n";
    import {onLoadDicUrl, onLoaded} from "/@/flow/components/convert-name/convert";
    import other, {deepClone} from '/@/utils/other';
    import {parseWithFunctions} from "/@/flow";
    import {utils} from "/@/flow/designer/utils/common";
    import {useUserInfo} from "/@/stores/userInfo";
    import {handleCustomForm, vueKey} from "/@/api/order/order-key-vue";
    import * as jsonflow from "/@/flow/designer/api/jsonflow";
    import * as defFlow from "/@/api/jsonflow/def-flow";
    import {validateNull} from "/@/utils/validate";

    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('/@/flow/components/onebtn-design/form.vue'));
    const FlowFormDesign = defineAsyncComponent(() => import('/@/flow/components/onebtn-design/design.vue'));
    const FormRender = defineAsyncComponent(() => import('/@/flow/components/form-create/render.vue'));
    const FlowPhoto = defineAsyncComponent(() => import('/@/views/jsonflow/flow-design/view.vue'));
    const CustomForm = defineAsyncComponent(() => import('/@/flow/components/custom-form/handle.vue'));
    const TinymceEditor = defineAsyncComponent(() => import('/@/flow/components/tinymce/TinymceEditor.vue'));

    const userInfo = useUserInfo();
    const { t } = useI18n()
    // 定义查询字典

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

    // 定义字典
    const dicData = reactive({});
    // const onLoad = onLoadDicUrl({key: "permission"});
    onMounted(() => {
        // onLoad(dicData);
    });

    const state: BasicTableProps = reactive<BasicTableProps>({
        queryForm: {
            isQueryForm: '1'
        },
        pageList: fetchList,
        // onLoaded: onLoaded({key: "createUser"}),
        descs: ["create_time"]
    })

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

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

    // 导出excel
    const exportExcel = () => {
        downBlobFile('/order/flow-application/export', state.queryForm, 'flow-application.xlsx')
    }

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

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

        let delIdList = []
        let delList = state.dataList.filter(f => ids.includes(f.id));
        for (const each of delList) {
            delIdList.push(each.defFlowId)
            let exists = await jsonflow.listRunFlowsByDefFlowId(each.defFlowId, each.version)
            if (!validateNull(exists.data)) {
                useMessage().error('当前删除的模型版本已存在流程实例! 请勿删除');
                return
            }
        }

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

    const data = reactive({
        showViewOrder: false,
        showDesignFlow: false,
        showFlowPic: false,
        currFlowForm: {},
        showTinymceEditor: false,
        tinymceTitle: '',
        showHandleForm: false,
    })

    function openPreview(defFlowId) {
        data.currFlowForm = {defFlowId: defFlowId}
        data.showFlowPic = true
    }

    function handlePrintTemplate(row) {
        data.currFlowForm = {id: row.id, formType: row.type, formId: row.id, formName: row.formName, path: row.path, isForm: true}
        data.currFlowForm.formInfo = row.formInfo
        data.tinymceTitle = "打印模板设计器（自定义《" + row.formName + "》打印格式）"
        data.showTinymceEditor = true
    }

    function handleDesignFlow(bool, row?: any) {
        data.showDesignFlow = bool
        if (bool === false) {
            getDataList()
            return
        }
        if (row) {
            data.currFlowForm = other.deepClone(row)
            data.currFlowForm.formInfo = parseWithFunctions(row.formInfo, true)
            data.currFlowForm.active = "formSetting";
        } else {
            data.currFlowForm = {
                id:  utils.getId(),
                active: 'formSetting',
                icon: 'iconfont icon-shuxingtu',
                formName: '未命名',
                type: '0',
                isActive: '1',
                isAutoAudit: '0',
                status: '-1',
                version: 1,
                isNew: true,
                sort: 1
            }
        }
    }

    function handleViewOrder(row) {
        data.currFlowForm = deepClone(row)
        // 判断是否自定义首页
        if (row.path !== vueKey.RunApplicationForm) {
            handleCustomForm(data, row)
            data.currFlowForm.operType = 'view'
            data.showHandleForm = true
        } else {
            data.showViewOrder = true
        }
    }

    function onHandleForm(type) {
        data.showHandleForm = false
    }
</script>

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