<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-tooltip content="离职 或 转岗 会默认交接全部任务。故可随意选择1条任务发起即可" placement="top">
							<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-tooltip>
					</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"
							@change="typeChange"
						>
							<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>
						<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-button icon="Promotion" type="primary" class="ml10" @click="handleInitiate" :loading="state.loading" v-auth="'order_handoverflow_add'">
						{{ $t('jfI18n.initHandover') }}
					</el-button>
					<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="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="type" :label="t('handoverFlow.type')" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="DIC_PROP.HANDOVER_TYPE" :value="scope.row.type ? scope.row.type : state.queryForm.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>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<el-dialog v-if="data.showNodeHandover" append-to-body v-model="data.showNodeHandover" top="20px" width="80%" :title="data.handoverTitle">
			<handover-node-record
				ref="node"
				:selections="data.selections"
				:handover-form="data.handoverForm"
				@onHandoverFlow="onHandoverFlow"
			></handover-node-record>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemHandoverFlow">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';
import { onLoadDicUrl, onLoaded, remoteMethodByKey } from '/@/flow/components/convert-name/convert';
import { validateNull } from '/@/utils/validate';
import { DIC_PROP } from '/@/flow/support/dict-prop';
import * as handoverFlow from '/@/api/order/handover-flow';
import * as runJob from '/@/api/jsonflow/run-job';

// 引入组件
const HandoverNodeRecord = defineAsyncComponent(() => import('/@/views/order/handover-node-record/initiate.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 queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		type: DIC_PROP.HANDOVER_TYPE[0].value,
		status: DIC_PROP.HANDOVER_STATUS[1].value,
	},
	pageList: runJob.fetchNodeHandover,
	onLoaded: onLoaded({ key: 'createUser' }, { key: 'flowInstId' }, { key: 'runJobId' }),
	descs: ['create_time'],
});

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

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

// 导出excel
const exportExcel = () => {
	downBlobFile('/order/handover-flow/export', state.queryForm, 'handover-flow.xlsx');
};

// 多选事件
const handleSelectionChange = (objs: any) => {
	data.selections = objs;
	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 handoverFlow.delObjs(ids);
		getDataList();
		useMessage().success(t('common.delSuccessText'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

const data = reactive({
	selections: [],
	showNodeHandover: false,
	handoverTitle: null,
	handoverForm: null,
});

function fetchListFun(fetchList, params) {
	if (!params.status || !params.type) {
		useMessage().info('请选择必填交接条件');
		return;
	}
	state.pageList = fetchList;
	getDataList();
}

function typeChange() {
	let type = state.queryForm.type;
	let handoverType = DIC_PROP.HANDOVER_TYPE;
	if (type === handoverType[0].value) {
		// 任务交接
		fetchListFun(runJob.fetchNodeHandover, state.queryForm);
	} else {
		// 公共交接 TODO 需自行扩展自身业务，参考任务交接
		// fetchListFun(company.fetchCommonHandover, state.queryForm)
	}
	handleSelectionChange([]);
}

function handleInitiate() {
	const type = state.queryForm.type;
	if (validateFormInfo(type)) {
		return;
	}
	data.handoverTitle = DIC_PROP.HANDOVER_TYPE.filter((f) => f.value === type)[0].label;
	// 转岗或离职，则全部交接
	if (validateNull(data.selections)) {
		useMessage().info('请选择交接项');
		return;
	}
	data.handoverForm = Object.assign({}, state.queryForm);
	data.handoverForm.code = null;
	data.showNodeHandover = true;
}

function validateFormInfo(type) {
	const handoverReason = state.queryForm.handoverReason;
	if (!handoverReason) {
		useMessage().info('请选择交接原因');
		return true;
	}
	if (!type) {
		useMessage().info('请选择交接类型');
		return true;
	}
	if (!state.queryForm.status) {
		useMessage().info('请选择交接状态');
		return true;
	}
	if (!state.queryForm.receiveDept) {
		useMessage().info('请选择接收部门');
		return true;
	}
	if (!state.queryForm.receiveUser) {
		useMessage().info('请选择接收人');
		return true;
	}
	return false;
}

function onHandoverFlow(type) {
	getDataList();
	data.showNodeHandover = false;
}

onMounted(() => {
	state.loading = false;
});
</script>
