<template>
    <div>
        <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.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" :key="index" :label="item.label"
                                       :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('handoverNodeRecord.status')" prop="status">
                        <el-select v-model="state.queryForm.status"
                                   :placeholder="t('handoverNodeRecord.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>
            </el-row>
            <el-row>
                <div class="mb8" style="width: 100%">
                    <el-button icon="edit-pen" type="primary" class="ml10" @click="methods.handleUpdateFlow"
                               :loading="state.loading" v-if="state.queryForm.retStatus === '1'"
                               v-auth="'order_handovernoderecord_edit'">
                        {{ $t('jfI18n.updateFlow') }}
                    </el-button>
                    <el-button icon="RefreshLeft" type="primary" class="ml10" @click="methods.handleCheckToReject"
                               :loading="state.loading" v-if="data.isCheckToReject"
                               v-auth="'order_handovernoderecord_edit'">
                        {{ $t('jfI18n.rejectBtn') }}
                    </el-button>
                    <el-button icon="CircleCheck" type="primary" class="ml10" @click="methods.handleConfirmReceive"
                               :loading="state.loading" v-if="data.isConfirmReceive"
                               v-auth="'order_handovernoderecord_edit'">
                        {{ $t('jfI18n.receiveBtn') }}
                    </el-button>
                </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" v-if="data.selection"/>
                <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" v-if="data.menu">
                    <template #default="scope">
                        <el-button text type="primary" icon="view" v-if="!scope.row.$cellEdit"
                                   @click="formDialogRef.openDialog('view', scope.row.id)"
                                   v-auth="'order_handovernoderecord_view'">
                            {{ $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"
                                   @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="HandoverNodeRecordFlow">
    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 {onFormLoadedUrl, onLoadDicUrl, onLoaded, remoteMethodByKey} from "/@/flow/components/convert-name/convert";
    import {validateNull} from "/@/utils/validate";
    import * as handoverFlow from '/@/api/order/handover-flow'
    import * as orderVue from "/@/api/order/order-key-vue";
    import {PROP_CONST} from '/@/flow/support/prop-const'
    import {useUserInfo} from "/@/stores/userInfo";
    import {setCrudQueryForm} from "/@/flow/support/common";

    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    const {t} = useI18n()
    const userInfo = useUserInfo();
    // 定义查询字典
    const dicData = reactive({});
    const onLoad = onLoadDicUrl();
    const onFormLoaded = onFormLoadedUrl({key: "receiveDept"}, {key: "receiveUser"});
    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 onTableLoaded = async (state) => {
        let onLoadedInit = onLoaded({key: "createUser"}, {key: "initiatorId"}, {key: "flowInstId"}, {key: "runJobId"});
        await onLoadedInit(state)
        await onFormLoaded(dicData, state.queryForm)
    }

    const validate = async () => {
        // 防止被手动修改
        methods.setCrudQueryForm()
        if (!state.queryForm.status || !state.queryForm.type) {
            useMessage().info('请选择交接条件')
            return false
        }
        // 被驳回时查询
        state.queryForm.createUser = props.currJob.createUser
        return true
    }

    const state: BasicTableProps = reactive<BasicTableProps>({
        queryForm: {},
        pageList: handoverNodeRecord.fetchFlowList,
        validate: validate,
        onLoaded: onTableLoaded,
        descs: ["create_time"],
        createdIsNeed: false
    })

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

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

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

    // 删除操作
    const handleDelete = async (id: string, index) => {
        if (validateNull(id)) {
            useMessage().info('还未保存')
            return
        }
        try {
            await useMessageBox().confirm(t('common.delConfirmText'));
        } catch {
            return;
        }
        try {
            await handoverNodeRecord.delObjs(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 props = defineProps({
        currJob: {
            type: Object,
            default: null,
        },
        currElTab: {
            type: Object,
            default: {},
        },
    });
    const data = reactive({
        selections: [],
        isCheckToReject: false,
        isConfirmReceive: false,
        menu: false,
        selection: false
    })

    const methods = {
        initJobData() {
            state.loading = false
            data.menu = false;
            data.selection = false;
            data.isConfirmReceive = false
            data.isCheckToReject = false
            methods.initSelections()
        },
        async resolveMethod() {
            let index = state.dataList.findIndex(f => f.retStatus === '1') + 1
            if (index !== 0) {
                useMessage().info('第 ' + index + ' 行交接项未修改，请先修改并保存')
                return false
            }
            orderVue.currElTabIsSave(props.currJob, props.currElTab.id, true)
            return true
        },
        async initSelections() {
            let hiJob = props.currJob.hiJob
            // 判断是否仅查看
            await orderVue.currElTabIsView(null, props.currJob, props.currElTab.id)
            let find = orderVue.currElTabIsExist(props.currJob, props.currElTab.id)
            if (find.isFormEdit === '0') hiJob = true
            let userKey = props.currJob.userKey
            let currJob = PROP_CONST.HANDOVER_FLOW.userKey
            if (userKey === currJob.create_user) {
                // 判断修改工单
                if (!hiJob) {// 为0后带入参数查询不出1的数据
                    state.queryForm.retStatus = '1'
                    data.menu = true;
                } else data.menu = false;
                // 被驳回需全部保存
                props.currJob.resolveMethods.push(methods.resolveMethod)
            } else if (userKey === currJob.receive_user || userKey === currJob.curr_dept_manager) {
                data.menu = false;
                state.queryForm.retStatus = '0'
                // 判断驳回工单
                if (!hiJob) {
                    data.isCheckToReject = true
                    data.selection = true;
                    if (userKey === currJob.curr_dept_manager) orderVue.currElTabIsSave(props.currJob, props.currElTab.id, true)
                }
                // 判断接收工单
                if (userKey === currJob.receive_user && !hiJob) {
                    props.currJob.resolveSaves.push(methods.handleConfirmReceive)
                    data.isConfirmReceive = true
                }
            } else {
                // 其他节点自动完成
                orderVue.currElTabIsSave(props.currJob, props.currElTab.id, true)
            }
            // 初始化
            getDataList()
        },
        async handleUpdate(row, index) {
            try {
                state.loading = true;
                // 防止被手动修改
                methods.setCrudQueryForm()
                // 驳回后修改为正常状态
                if (state.queryForm.retStatus === '1') row.retStatus = '0'
                let resp = await handoverNodeRecord.putObj(Object.assign({}, state.queryForm, row));
                // 延迟赋值
                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;
            }
        },
        handleUpdateFlow() {
            // 可手动修改的交接参数
            // common.setPropsDataValue(order, state.queryForm, 'handoverReason', 'receiveDept')
            if (!state.queryForm.status || !state.queryForm.type || !state.queryForm.handoverReason || !state.queryForm.receiveDept) {
                useMessage().info('请选择交接条件：交接状态、交接类型、交接原因、接受部门')
                return
            }
            methods.timeoutLoading(3)
            let queryForm = {
                id: props.currJob.orderId,
                code: props.currJob.code,
                flowKey: props.currJob.flowKey,
                flowInstId: props.currJob.flowInstId,
                runJobId: props.currJob.id
            }
            // 修改工单信息时，任务交接不允许修改类型、状态
            let order = props.currJob.order
            let assign = Object.assign({}, state.queryForm, queryForm, {type: order.type, status: order.status});
            handoverFlow.putObj(assign).then(data => {
                orderVue.currElTabIsSave(props.currJob, props.currElTab.id, true)
                useMessage().success('修改成功')
            })
        },
        // 防止被手动修改
        setCrudQueryForm() {
            let order = props.currJob.order
            setCrudQueryForm(state, {prop: 'receiveDept', value: order.receiveDept}, {prop: 'type', value: order.type}
                , {prop: 'status', value: order.status}, {prop: 'receiveUser', value: order.receiveUser},
                {prop: 'handoverReason', value: order.handoverReason},{prop: 'orderId', value: props.currJob.orderId} )
        },
        handleCheckToReject() {
            // 防止被手动修改
            methods.setCrudQueryForm()
            // 驳回
            if (validateNull(data.selections)) {
                useMessage().info('请选择需驳回的交接项')
                return
            }
            methods.timeoutLoading(3)
            state.queryForm.id = data.selections[0].orderId
            state.queryForm.rejectIds = data.selections.map(m => m.id)
            handoverFlow.checkToReject(state.queryForm).then(data => {
                state.queryForm.id = null
                getDataList()
                useMessage().success('驳回成功')
            })
        },
        async handleConfirmReceive() {
            // 防止被手动修改
            methods.setCrudQueryForm()
            // 接收
            if (validateNull(state.dataList)) {
                useMessage().info('请选择交接项')
                return
            }
            methods.timeoutLoading(3)
            state.queryForm.id = state.dataList[0].orderId
            await handoverFlow.confirmReceive(state.queryForm)
            orderVue.currElTabIsSave(props.currJob, props.currElTab.id, true, null)
            useMessage().success('接收成功')
        },
        timeoutLoading(t) {
            state.loading = true
            setTimeout(() => {// 防重复提交
                state.loading = false
            }, t * 1000)
        },
        handleEdit(row, index, bool) {
            row.$cellEdit = bool
        }
    }

    // 监听双向绑定
    watch(
        () => props.currJob.id,
        () => {
            methods.initJobData();
        }
    );

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