<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('runApplication.code')" prop="code" >
                        <el-input :placeholder="t('runApplication.inputCodeTip')" v-model="state.queryForm.code" clearable
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('runApplication.flowKey')" prop="flowKey" >
                        <el-input :placeholder="t('runApplication.inputFlowKeyTip')" v-model="state.queryForm.flowKey" clearable
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('runApplication.formName')" prop="formName" >
                        <el-input :placeholder="t('runApplication.inputFormNameTip')" v-model="state.queryForm.formName" clearable
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('runApplication.status')" prop="status" >
                        <el-select v-model="state.queryForm.status" :placeholder="t('runApplication.inputStatusTip')" clearable style="max-width: 180px">
                            <el-option v-for="(item, index) in DIC_PROP.ORDER_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('common.delBtn') }}
                        </template>
                        <el-button plain :disabled="multiple" icon="Delete" type="primary" class="ml10"
                                   v-auth="'order_runapplication_del'" @click="handleDelete(selectObjs)">
                        </el-button>
                    </el-tooltip>

                    <right-toolbar v-model:showSearch="showSearch" 	:export="'order_runapplication_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('runApplication.index')" width="40"/>
                <el-table-column prop="code" :label="t('runApplication.code')" show-overflow-tooltip/>
                <el-table-column prop="flowKey" :label="t('runApplication.flowKey')" show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="dicData.flowKey" :value="scope.row.flowKey"
                                      :valueKey="'flowKey'" :showKey="'flowName'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="icon" :label="t('runApplication.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('runApplication.formName')" show-overflow-tooltip/>
                <el-table-column prop="groupName" :label="t('runApplication.groupName')" show-overflow-tooltip/>
                <el-table-column prop="finishTime" :label="t('runApplication.finishTime')" show-overflow-tooltip/>
                <el-table-column prop="status" :label="t('runApplication.status')" show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.ORDER_STATUS" :value="scope.row.status"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" :label="t('runApplication.remark')" width="200" show-overflow-tooltip/>
                <el-table-column prop="version" :label="t('runApplication.version')"  show-overflow-tooltip/>
<!--                <el-table-column prop="createUser" :label="t('runApplication.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('runApplication.createTime')"  show-overflow-tooltip/>-->
                <el-table-column :label="$t('common.action')" width="170">
                    <template #default="scope">

                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.viewBtn') }}
                            </template>
                            <el-button text type="primary" icon="view" @click="handleViewOrder(scope.row)">
                            </el-button>
                        </el-tooltip>

                        <el-tooltip placement="top">
                            <template #content>
                                打印表单
                            </template>
                            <el-button icon="Document" text type="primary" @click="handleViewOrder(scope.row)">
                            </el-button>
                        </el-tooltip>

                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.copyBtn') }}
                            </template>
                            <el-button icon="DocumentCopy" text type="primary" @click="handleInitiateOrder(scope.row,'copy')">
                            </el-button>
                        </el-tooltip>

                        <el-tooltip placement="top" v-if="scope.row.status===DIC_PROP.ORDER_STATUS[2].value">
                            <template #content>
                                {{ $t('jfI18n.recallBtn') }}
                            </template>
                            <el-button icon="RefreshLeft" text type="primary" @click="handleRecallReset(scope.row)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip placement="top" v-if="scope.row.status===DIC_PROP.ORDER_STATUS[0].value">
                            <template #content>
                                {{ $t('jfI18n.resetBtn') }}
                            </template>
                            <el-button icon="RefreshRight" text type="primary" @click="handleRecallReset(scope.row)">
                            </el-button>
                        </el-tooltip>

                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('jfI18n.viewFlow') }}
                            </template>
                            <el-button icon="Share" text type="primary" @click="openPreview(scope.row)">
                            </el-button>
                        </el-tooltip>

                        <el-tooltip placement="top" v-if="scope.row.status===DIC_PROP.ORDER_STATUS[1].value || scope.row.status===DIC_PROP.ORDER_STATUS[0].value">
                            <template #content>
                                {{ $t('common.editBtn') }}
                            </template>
                            <el-button icon="edit-pen" text type="primary" @click="handleInitiateOrder(scope.row,'edit')">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip placement="top" v-if="scope.row.status===DIC_PROP.ORDER_STATUS[1].value">
                            <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>

        <json-flow-predict ref="predict" :proxy="proxy" @handleInitiateOrder="handleInitiateOrder">
            <template v-slot="slotProps" v-if="data.showInitiateOrder">
                <run-initiate ref="form" v-show="slotProps.currActive === 'form'" :curr-flow-form="data.currFlowForm"
                               @handleInitiateOrder="handleInitiateOrder"></run-initiate>
            </template>
            <template v-slot="slotProps" v-if="data.showHandleForm">
                <custom-form ref="form" v-show="slotProps.currActive === 'form'" :curr-job="data.currFlowForm"
                             @onHandleForm="handleInitiateOrder"></custom-form>
            </template>
        </json-flow-predict>

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

        <!-- 查看工单 -->
        <el-dialog
                v-model="data.showViewOrder"
                top="20px"
                width="90%"
                title="查看工单"
                append-to-body>
            <run-view v-if="data.showViewOrder" :curr-flow-form="data.currFlowForm"></run-view>
        </el-dialog>

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

<script setup lang="ts" name="systemRunApplication">
    import { BasicTableProps, useTable } from "/@/hooks/table";
    import * as runApplication from '/@/api/order/run-application'
    import { useMessage, useMessageBox } from "/@/hooks/message";

    import {useI18n} from "vue-i18n";
    import {onLoadDicUrl, onLoaded} from "/@/flow/components/convert-name/convert";
    import * as common from '/@/flow/support/common'
    import other, {deepClone} from "/@/utils/other";
    import {recallReset} from "/@/api/jsonflow/run-flow";
    import {DIC_PROP} from "/@/flow/support/dict-prop";
    import {openFlowPreview} from "/@/flow/support/extend";
    import {handleCustomForm, vueKey} from "/@/api/order/order-key-vue";

    // 引入组件
    const FlowPhoto = defineAsyncComponent(() => import('/@/views/jsonflow/flow-design/view.vue'));
    const RunInitiate = defineAsyncComponent(() => import('./initiate.vue'));
    const RunView = defineAsyncComponent(() => import('./view.vue'));
    const CustomForm = defineAsyncComponent(() => import('/@/flow/components/custom-form/handle.vue'));
    const JsonFlowPredict = defineAsyncComponent(() => import('/@/views/jsonflow/flow-design/predict.vue'));

    const { t } = useI18n()
    const {proxy} = getCurrentInstance();

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

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

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

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

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

    // 导出excel
    const exportExcel = () => {
        downBlobFile('/order/run-application/export', state.queryForm, 'run-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;
        }

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

    const data = reactive({
        showViewOrder: false,
        showInitiateOrder: false,
        showFlowPic: false,
        currFlowForm: {},
        showHandleFormView: false,
        showHandleForm: false,
    })

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

    function handleInitiateOrder(row, operType) {
        if (row === false) {
            getDataList();
            openPredict({}, false)
            data.showInitiateOrder = false
            data.showHandleForm = false
            return
        }
        data.currFlowForm = deepClone(row)
        data.currFlowForm.operType = operType
        let clone = {operType: data.currFlowForm.operType};
        common.handleClone(clone, data.currFlowForm)
        // 判断是否自定义首页
        if (row.path !== vueKey.RunApplicationForm) {
            handleCustomForm(data, row)
            data.showHandleForm = true
        } else {
            data.showInitiateOrder = true
        }
        openPredict(row, true)
    }

    function openPredict(row, bool) {
        proxy.$refs.predict.open(row, bool)
    }

    const $router = useRouter();
    function openPreview(row) {
        if (row.status === DIC_PROP.ORDER_STATUS[1].value) {
            data.currFlowForm = {defFlowId: row.defFlowId}
            data.showFlowPic = true
        } else {
            openFlowPreview($router, {flowInstId: row.flowInstId}, '1')
        }
    }

    function handleRecallReset(row) {
        let params = {id: row.flowInstId, flowKey: row.flowKey, status: row.status}
        if (row.status === DIC_PROP.ORDER_STATUS[0].value) {
            recallReset(params).then(() => {
                useMessage().success('重发成功');
                getDataList();
            })
            return
        }
        useMessageBox().confirm('是否确认要撤回该工单?')
            .then(() => {
                return recallReset(params)
            }).then(() => {
            useMessage().success('撤回成功')
            getDataList();
        })
    }

</script>

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