<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('askLeave.code')" prop="code" >
                        <el-input :placeholder="t('askLeave.inputCodeTip')" v-model="state.queryForm.code" clearable
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('askLeave.status')" prop="status">
                        <el-select v-model="state.queryForm.status" :placeholder="t('askLeave.inputStatusTip')" clearable filterable 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.addBtn') }}
                        </template>
                        <el-button icon="Plus" type="primary" class="ml10" @click="openDialog('add')"
                                   v-auth="'order_askleave_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_askleave_del'" @click="handleDelete(selectObjs)">
                        </el-button>
                    </el-tooltip>

                    <right-toolbar v-model:showSearch="showSearch" :export="'order_askleave_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('askLeave.index')" width="40"/>
                <el-table-column prop="code" :label="t('askLeave.code')" show-overflow-tooltip/>
                <el-table-column prop="flowKey" :label="t('askLeave.flowKey')" show-overflow-tooltip/>
                <el-table-column prop="type" :label="t('askLeave.type')" show-overflow-tooltip/>
                <el-table-column prop="startTime" :label="t('askLeave.startTime')" show-overflow-tooltip/>
                <el-table-column prop="endTime" :label="t('askLeave.endTime')" show-overflow-tooltip/>
                <el-table-column prop="days" :label="t('askLeave.days')" show-overflow-tooltip/>
                <el-table-column prop="carbonCopyPerson" :label="t('askLeave.carbonCopyPerson')" show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.carbonCopyPerson" :value="scope.row.carbonCopyPerson"
                                      :valueKey="'userId'" :showKey="'name'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" :label="t('askLeave.remark')" show-overflow-tooltip/>
                <el-table-column prop="status" :label="t('askLeave.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="finishTime" :label="t('askLeave.finishTime')" show-overflow-tooltip/>
                <el-table-column prop="createUser" :label="t('askLeave.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('askLeave.createTime')" show-overflow-tooltip/>
                <el-table-column :label="$t('common.action')" width="150">
                    <template #default="scope">
                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.viewBtn') }}
                            </template>
                            <el-button text type="primary" icon="view" @click="openDialog('view', scope.row.id)">
                            </el-button>
                        </el-tooltip>

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

                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.copyBtn') }}
                            </template>
                            <el-button icon="DocumentCopy" text type="primary" @click="openDialog('copy', scope.row.id, scope.row)">
                            </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" v-if="scope.row.flowInstId">
                            <template #content>
                                {{ $t('jfI18n.viewFlow') }}
                            </template>
                            <el-button text type="primary" icon="Share" @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="openDialog('edit', scope.row.id, scope.row)">
                            </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="refresh">
            <template v-slot="slotProps" v-if="showInitiateOrder">
                <form-dialog ref="form" v-show="slotProps.currActive === 'form'" :formData="formData" @refresh="refresh"/>
            </template>
        </json-flow-predict>

        <!-- 编辑、新增  -->
        <el-dialog title="请假工单" v-model="showFormDialog" width="60%"
                   :close-on-click-modal="false" draggable>
            <form-dialog v-if="showFormDialog" ref="formDialogRef" :formData="formData" @refresh="refresh"/>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="systemAskLeave">
    import {BasicTableProps, useTable} from "/@/hooks/table";
    import {fetchList, delObjs} from "/@/api/order/ask-leave";
    import {useMessage, useMessageBox} from "/@/hooks/message";

    import {useI18n} from "vue-i18n";
    import {onCascadeChange, onLoadDicUrl, onLoaded} from "/@/flow/components/convert-name/convert";
    import {recallReset} from "/@/api/jsonflow/run-flow";
    import {openFlowPreview} from "/@/flow/support/extend";
    import {DIC_PROP} from "/@/flow/support/dict-prop";
    import {orderKeyMap} from "/@/api/order/order-key-vue";

    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    const JsonFlowPredict = defineAsyncComponent(() => import('/@/views/jsonflow/flow-design/predict.vue'));

    const {t} = useI18n()
    const {proxy} = getCurrentInstance();
    // 定义查询字典
    const dicData = reactive({});
    // const onLoad = onLoadDicUrl();
    onMounted(() => {
        // onLoad(dicData);
    });
    // 定义变量内容
    const formDialogRef = ref()
    const showFormDialog = ref(false)
    const showInitiateOrder = ref(false)
    const formData = 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,
        onLoaded: onLoaded({key: "createUser"}, {key: "carbonCopyPerson"}),
        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/ask-leave/export', state.queryForm, 'ask-leave.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 delObjs(ids);
            getDataList();
            useMessage().success(t('common.delSuccessText'));
        } catch (err: any) {
            useMessage().error(err.msg);
        }
    };

    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();
        })
    }

    const $router = useRouter();
    function openPreview(row) {
        openFlowPreview($router, {flowInstId: row.flowInstId}, '1')
    }

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

    // 打开弹窗
    const openDialog = (type?: string, id?: string, row?) => {
        formData.value = {type, id}
        if (type === 'add' || type === 'edit' || type === 'copy') {
            showInitiateOrder.value = true
            if (type === 'add') {
                openPredict({flowKey: orderKeyMap.AskLeave}, true)
            } else {
                openPredict(row, true)
            }
        } else {
            showFormDialog.value = true
        }
    }

    function refresh() {
        getDataList(false)
        openPredict({}, false)
        showInitiateOrder.value = false
        showFormDialog.value = false
    }

</script>
