<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('handoverFlow.code')" prop="code" >
                        <el-input :placeholder="t('handoverFlow.inputCodeTip')" v-model="state.queryForm.code" clearable
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('handoverFlow.handoverReason')" prop="handoverReason" >
                        <el-select v-model="state.queryForm.handoverReason" :placeholder="t('handoverFlow.inputHandoverReasonTip')" clearable filterable style="max-width: 180px">
                            <el-option v-for="(item, index) in DIC_PROP.HANDOVER_REASON" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('handoverFlow.receiveDept')" prop="receiveDept" >
                        <el-tooltip content="请输入部门名称进行模糊搜索" placement="top">
                            <el-select v-model="state.queryForm.receiveDept" :placeholder="t('handoverFlow.inputReceiveDeptTip')" clearable filterable
                                       remote :remote-method="remoteMethodDept" :reserve-keyword="false"
                                       style="max-width: 180px">
                                <el-option v-for="(item, index) in dicData.receiveDept" :key="index" :label="item.name" :value="item.deptId"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item :label="$t('handoverFlow.receiveUser')" prop="receiveUser" >
                        <el-tooltip content="请输入用户名称进行模糊搜索" placement="top">
                            <el-select v-model="state.queryForm.receiveUser" :placeholder="t('handoverFlow.inputReceiveUserTip')" clearable filterable
                                       remote :remote-method="remoteMethodUser" :reserve-keyword="false"
                                       style="max-width: 180px">
                                <el-option v-for="(item, index) in dicData.receiveUser" :key="index" :label="item.name" :value="item.userId"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item :label="$t('handoverFlow.type')" prop="type" >
                        <el-select v-model="state.queryForm.type" :placeholder="t('handoverFlow.inputTypeTip')" clearable filterable style="max-width: 180px">
                            <el-option v-for="(item, index) in DIC_PROP.HANDOVER_TYPE" :disabled="DIC_PROP.HANDOVER_TYPE[1].value === item.value"
                                       :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('handoverFlow.status')" prop="status" >
                        <el-select v-model="state.queryForm.status" :placeholder="t('handoverFlow.inputStatusTip')" clearable filterable style="max-width: 180px">
                            <el-option v-for="(item, index) in DIC_PROP.HANDOVER_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_handoverflow_del'" @click="handleDelete(selectObjs)">
                        </el-button>
                    </el-tooltip>

                    <right-toolbar v-model:showSearch="showSearch" 	:export="'order_handoverflow_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('handoverFlow.index')" width="40" />
                <el-table-column prop="code" :label="t('handoverFlow.code')"  show-overflow-tooltip/>
                <el-table-column prop="flowKey" :label="t('handoverFlow.flowKey')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.flowInstId" :value="scope.row.flowKey"
                                      :valueKey="'flowKey'" :showKey="'flowName'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="receiveDept" :label="t('handoverFlow.receiveDept')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.receiveDept" :value="scope.row.receiveDept"
                                      :valueKey="'deptId'" :showKey="'name'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="receiveUser" :label="t('handoverFlow.receiveUser')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.receiveUser" :value="scope.row.receiveUser"
                                      :valueKey="'userId'" :showKey="'name'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="type" :label="t('handoverFlow.type')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.HANDOVER_TYPE" :value="scope.row.type"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" :label="t('handoverFlow.status')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.HANDOVER_STATUS" :value="scope.row.status"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createUser" :label="t('handoverFlow.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('handoverFlow.createTime')"  show-overflow-tooltip/>
                <el-table-column :label="$t('common.action')" width="120">
                    <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" 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.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="formDialogRef.openDialog('edit', scope.row.id)">
                            </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>

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

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

    import { useI18n } from "vue-i18n";
    import {onLoadDicUrl, onLoaded, remoteMethodByKey} from "/@/flow/components/convert-name/convert";
    import {recallReset} from "/@/api/jsonflow/run-flow";
    import {DIC_PROP} from "/@/flow/support/dict-prop";

    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    const { t } = useI18n()
    // 定义查询字典
    const dicData = reactive({});
    const onLoad = onLoadDicUrl();
    onMounted(() => {
        // onLoad(dicData);
    });

    function remoteMethodDept(query: string) {
        remoteMethodByKey(query, onLoad, dicData, 'deptName', "receiveDept")
    }

    function remoteMethodUser(query: string) {
        remoteMethodByKey(query, onLoad, dicData, 'userName', "receiveUser")
    }

    // 定义变量内容
    const formDialogRef = 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: "receiveUser"}, {key: "flowInstId"}, {key: "receiveDept"}),
        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/handover-flow/export', state.queryForm, 'handover-flow.xlsx')
    }

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

    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 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);
        }
    };
</script>
