<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <el-row>
                <div class="mb8" style="width: 100%">
                    <el-button icon="Promotion" type="primary" class="ml10" @click="methods.handleInitiate"
                               :loading="state.loading" v-if="!validateNull(props.selections)"
                               v-auth="'order_handovernoderecord_add'">
                        {{ $t('jfI18n.initialBtn') }}
                    </el-button>
                    <el-button icon="Check" type="primary" class="ml10" @click="methods.batchSaveOrUpdate"
                               :loading="state.loading" v-if="!validateNull(props.selections)"
                               v-auth="'order_handovernoderecord_add'">
                        {{ $t('jfI18n.batchBtn') }}
                    </el-button>
                </div>
            </el-row>
            <el-table :data="state.dataList" v-loading="state.loading" style="width: 100%"
                      @sort-change="sortChangeHandle">
                <el-table-column type="index" :label="t('handoverNodeRecord.index')" width="40"/>
                <el-table-column prop="flowKey" :label="t('handoverNodeRecord.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="initiatorId" :label="t('handoverNodeRecord.initiatorId')" show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.initiatorId" :value="scope.row.initiatorId"
                                      :valueKey="'userId'" :showKey="'name'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="runJobId" :label="t('handoverNodeRecord.runJobId')" show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.runJobId" :value="scope.row.runJobId"
                                      :valueKey="'id'" :showKey="'jobName'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="startTime" :label="t('handoverNodeRecord.startTime')" show-overflow-tooltip/>
                <el-table-column prop="todoList" :label="t('handoverNodeRecord.todoList')" show-overflow-tooltip>
                    <template #default="scope">
                        <el-input :disabled="!scope.row.$cellEdit" v-model="scope.row.todoList" type="textarea" :placeholder="t('handoverNodeRecord.inputTodoListTip')"/>
                    </template>
                </el-table-column>
                <el-table-column prop="status" :label="t('handoverNodeRecord.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('handoverNodeRecord.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('handoverNodeRecord.createTime')" show-overflow-tooltip/>
                <el-table-column :label="$t('common.action')" width="200">
                    <template #default="scope">
                        <el-button text type="primary" icon="view" v-if="!scope.row.$cellEdit && scope.row.id"
                                   @click="formDialogRef.openDialog('view', scope.row.id)" v-auth="'order_handovernoderecord_edit'">
                            {{ $t('common.viewBtn') }}
                        </el-button>
                        <el-button icon="edit-pen" text type="primary" v-auth="'order_handovernoderecord_edit'" v-if="!scope.row.$cellEdit"
                                   @click="methods.handleEdit(scope.row, scope.$index, true)">{{ $t('common.editBtn') }}
                        </el-button>
                        <el-button icon="Check" text type="primary" v-auth="'order_handovernoderecord_add'" v-if="scope.row.$cellEdit"
                                   @click="methods.handleUpdate(scope.row, scope.$index)">{{ $t('jfI18n.saveBtn') }}
                        </el-button>
                        <el-button icon="Close" text type="primary" v-auth="'order_handovernoderecord_edit'" v-if="scope.row.$cellEdit && scope.row.id"
                                   @click="methods.handleEdit(scope.row, scope.$index, false)">{{ $t('jfI18n.cancelBtn') }}
                        </el-button>
                        <el-button icon="delete" text type="primary" v-auth="'order_handovernoderecord_del'"
                                   @click="handleDelete(scope.row.id, scope.$index)">{{
                                $t('common.delBtn')
                            }}
                        </el-button>
                    </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="HandoverNodeRecordInitiate">
    import {BasicTableProps, useTable} from "/@/hooks/table";
    import * as handoverNodeRecord from '/@/api/order/handover-node-record'
    import {useMessage, useMessageBox} from "/@/hooks/message";

    import {useI18n} from "vue-i18n";
    import {onLoaded} from "/@/flow/components/convert-name/convert";
    import {validateNull} from "/@/utils/validate";
    import * as handoverFlow from '/@/api/order/handover-flow'
    import {deepClone} from "/@/utils/other";
    import {paramsFilter} from "/@/flow";

    const $emit = defineEmits(['onHandoverFlow']);
    const props = defineProps({
        selections: {
            type: Object,
            default: null,
        },
        handoverForm: {
            type: Object,
            default: null,
        }
    });

    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    const {t} = useI18n()

    // 定义变量内容
    const formDialogRef = ref()

    const state: BasicTableProps = reactive<BasicTableProps>({
        createdIsNeed: false,
        isPage: false
    })

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

    // 删除操作
    const handleDelete = async (id: string, index) => {
        if (validateNull(id)) {
            useMessage().info('还未保存')
            return
        }
        try {
            await useMessageBox().confirm(t('common.delConfirmText'));
        } catch {
            return;
        }
        try {
            await handoverNodeRecord.delObj(id);
            state.dataList.splice(index, 1)
            state.pagination!.total = state.dataList.length
            useMessage().success(t('common.delSuccessText'));
        } catch (err: any) {
            useMessage().error(err.msg);
        }
    };

    const initLoaded = onLoaded({key: "flowInstId"}, {key: "runJobId"}, {key: "createUser"}, {key: "initiatorId"})

    const methods = {
        async initSelections() {
            state.loading = true
            // 搜索条件
            state.queryForm = paramsFilter(Object.assign(state.queryForm, props.handoverForm))
            // 任务交接交接数据一定不能为空
            if (validateNull(props.selections)) {
                useMessage().info('请选择交接项')
                state.loading = false
                return
            }
            let selections = deepClone(props.selections)
            for (let i = 0; i < selections.length; i++) {
                selections[i].$cellEdit = true
                selections[i].id = null// 防止复用
            }
            Object.assign(state.dataList, selections)
            await initLoaded(state);
            state.pagination!.total = state.dataList.length
            state.loading = false
        },
        async handleUpdate(row, index) {
            try {
                state.loading = true;
                let resp = await handoverNodeRecord.putObj(Object.assign(row, state.queryForm));
                // 延迟赋值
                setTimeout(() => {
                    state.dataList[index].id = resp.data.id
                    state.dataList[index].$cellEdit = false
                }, 0)
                useMessage().success('操作成功')
            } catch (err: any) {
                useMessage().error(err.msg);
            } finally {
                state.loading = false;
            }
        },
        handleInitiate() {
            // 发起
            if (validateNull(state.dataList)) {
                useMessage().info('请选择交接项')
                return
            }
            let index = state.dataList.findIndex(f => !f.id) + 1
            if (index !== 0) {
                useMessage().info('第 ' + index + ' 行交接项未保存，请先保存')
                return
            }
            methods.timeoutLoading()
            // 防止再次发起复用
            let assign = Object.assign({}, state.queryForm, {id: state.dataList[0].orderId});
            handoverFlow.addObj(assign).then(data => {
                useMessage().success('发起成功')
                $emit('onHandoverFlow', state.queryForm.type)
            })
        },
        batchSaveOrUpdate() {
            state.loading = true
            state.dataList[0] = Object.assign({}, state.queryForm, state.dataList[0]);
            handoverNodeRecord.batchSaveOrUpdate(state.dataList).then(resp => {
                // 延迟赋值
                setTimeout(() => {
                    resp.data.forEach(data => {
                        let find = state.dataList.find(f => f.flowInstId === data.flowInstId && f.runJobId === data.runJobId)
                        find.id = data.id
                        find.type = state.queryForm.type
                        find.$cellEdit = false
                    })
                    useMessage().success('保存成功')
                    state.loading = false
                }, 0)
            }).catch((e) => {
                state.loading= false
            })
        },
        timeoutLoading() {
            state.loading = true
            setTimeout(() => {// 防重复提交
                state.loading = false
            }, 3 * 1000)
        },
        handleEdit(row, index, bool) {
            row.$cellEdit = bool
        }
    }

    // 监听双向绑定
    watch(
        () => props.selections.length,
        () => {
            methods.initSelections();
        },
        {deep: true}
    );

    onMounted(() => {
        methods.initSelections()
    });
</script>
