<template>
	<div class="business-visit-todo-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline label-width="100px">
				<el-form-item label="数据范围" prop="QuerySelf" v-auth="'business:visit:todo:querySelf'">
					<el-segmented
						:options="[
							{ label: '我的', value: 'true' },
							{ label: '全部', value: 'false' },
						]"
						v-model="state.queryParams.QuerySelf"
						@change="handleQuery"
						:disabled="state.loading"
					/>
				</el-form-item>
				<el-form-item label="工单类型" prop="IsProvince" v-auth="'business:visit:todo:orderType'">
					<el-segmented
						:options="[
							{
								value: 'all',
								label: '全部',
							},
							{
								value: 'city',
								label: '市工单',
							},
							{
								value: 'province',
								label: '省工单',
							},
						]"
						v-model="fastSearch"
						@change="fastSearchChange"
						:disabled="state.loading"
					/>
				</el-form-item>
				<el-form-item label="回访状态" prop="VisitStateQuery" v-if="['ZiGong'].includes(themeConfig.appScope)">
					<el-segmented
						:options="[
							{ label: '待回访', value: 2 },
							{ label: '短信回访中', value: 21 },
							{ label: '短信不满意待回访', value: 41 },
							{ label: '未接通', value: 51 },
						]"
						v-model="state.queryParams.VisitStateQuery"
						@change="handleQuery"
						:disabled="state.loading"
					/>
				</el-form-item>
				<el-form-item label="工单标题" prop="Keyword">
					<el-input v-model.trim="state.queryParams.Keyword" placeholder="工单标题" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="工单编码" prop="No">
					<el-input v-model.trim="state.queryParams.No" placeholder="工单编码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="drawer = true" class="default-button"> <SvgIcon name="ele-Search" class="mr5" />更多查询</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button
						type="primary"
						@click="messageVisit"
						:disabled="isChecked"
						v-auth="'business:visit:todo:message'"
						v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope)"
					>
						<SvgIcon name="ele-Message" class="mr5" />短信回访</el-button
					>
					<el-button
						type="primary"
						@click="batchVisit"
						:disabled="isChecked"
						v-auth="'business:visit:todo:batch'"
						v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope)"
					>
						<SvgIcon name="ele-DocumentCopy" class="mr5" />批量回访</el-button
					>
					<!--					<el-button type="primary" @click="multiplePeople" :disabled="isChecked" v-auth="'business:visit:todo:multiplePeople'">
						<SvgIcon name="ele-User" class="mr5" />分配回访人</el-button
					>-->
					<el-button type="primary" @click="onMigration" v-auth="'business:visit:todo:migration'" :disabled="isChecked">
						<SvgIcon name="ele-Rank" class="mr5" />平级移动
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30 }"
					ref="tableRef"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					height="auto"
					auto-resize
					show-overflow
					:print-config="{}"
					:scrollY="{ enabled: true, gt: 0 }"
					id="businessVisitTodo"
					:custom-config="{
						storage: true,
					}"
					showHeaderOverflow
				>
					<vxe-column type="checkbox" width="50" align="center"></vxe-column>
					<vxe-column field="order.expiredStatusText" title="超期状态" width="90" align="center">
						<template #default="{ row }">
							<span :class="'overdue-status-' + row.order?.expiredStatus" :title="row.order?.expiredStatusText"></span>
						</template>
					</vxe-column>
					<vxe-column field="order.no" title="工单编码" width="140"></vxe-column>
					<vxe-column field="order.isProvinceText" title="省/市工单" width="100"></vxe-column>
					<vxe-column field="title" title="工单标题" width="200">
						<template #default="{ row }">
							<order-detail :order="row.order" @updateList="queryList">{{ row.order?.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="order.sourceChannel" title="来源渠道" width="100"></vxe-column>
					<vxe-column field="visitStateText" title="回访状态" width="100"></vxe-column>
					<vxe-column field="visitTypeText" title="回访方式" width="100"></vxe-column>
					<vxe-column field="order.acceptType" title="受理类型" width="110"></vxe-column>
					<vxe-column field="order.hotspotName" title="热点分类" width="150"></vxe-column>
					<vxe-column field="order.acceptorName" title="受理人" width="120"></vxe-column>
					<vxe-column field="order.orgLevelOneName" title="一级部门" width="150"></vxe-column>
					<vxe-column field="order.actualHandleOrgName" title="接办部门" width="150"></vxe-column>
					<vxe-column field="order.startTime" title="受理时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.startTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="order.filedTime" title="办结时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.filedTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="publishTime" title="发布时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.publishTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="creationTime" title="回访任务创建时间" width="170">
						<template #default="{ row }">
							{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="employeeName" title="回访人" width="150"></vxe-column>
					<vxe-column title="操作" fixed="right" width="80" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onManpower(row)" title="工单回访" v-auth="'business:visit:todo:manpower'"> 回访 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
			/>
		</div>
		<!--	更多查询	-->
		<el-drawer v-model="drawer" title="更多查询" size="500px">
			<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="100px">
				<el-form-item label="来电号码" prop="FromPhone">
					<el-input v-model.trim="state.queryParams.FromPhone" placeholder="来电号码" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="联系电话" prop="Contact">
					<el-input v-model.trim="state.queryParams.Contact" placeholder="联系电话" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="回访人" prop="EmployeeName">
					<el-input v-model="state.queryParams.EmployeeName" placeholder="回访人" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="接办部门" prop="ActualHandleOrgName">
					<el-input v-model="state.queryParams.ActualHandleOrgName" placeholder="接办部门" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="归档类型" prop="FiledType">
					<el-select v-model="state.queryParams.FiledType" placeholder="请选择归档类型" @change="handleQuery" clearable>
						<el-option label="中心归档" value="10" />
						<el-option label="部门归档" value="20" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否会签" prop="IsCountersign">
					<el-select v-model="state.queryParams.IsCountersign" placeholder="请选择是否会签" @change="handleQuery" clearable>
						<el-option label="是" value="true" />
						<el-option label="否" value="false" />
					</el-select>
				</el-form-item>
				<el-form-item label="发布时间" prop="fbTime">
					<el-date-picker
						v-model="state.queryParams.fbTime"
						type="datetimerange"
						unlink-panels
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						:shortcuts="shortcuts"
						@change="handleQuery"
						value-format="YYYY-MM-DD[T]HH:mm:ss"
						:default-time="defaultTimeStartEnd"
					/>
				</el-form-item>
				<el-form-item label="回访方式" prop="VisitType">
					<el-select v-model="state.queryParams.VisitType" placeholder="请选择回访方式" @change="handleQuery" clearable>
						<el-option v-for="item in state.visitTypeOptions" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="来源渠道" prop="Channel">
					<el-select v-model="state.queryParams.Channel" placeholder="请选择来源渠道" clearable @change="handleQuery">
						<el-option v-for="item in channelOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否超期" prop="IsOverTime">
					<el-select v-model="state.queryParams.IsOverTime" placeholder="请选择是否超期" class="w100" clearable @change="handleQuery">
						<el-option label="是" :value="true" />
						<el-option label="否" :value="false" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(drawerRuleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
			</template>
		</el-drawer>
		<!-- 回访 -->
		<visit-detail ref="visitDetailRef" @updateList="queryList" />
		<!--  分配回访人  -->
		<assign-return-visitors ref="assignReturnVisitorsRef" @updateList="queryList" />
		<!-- 工单平移 -->
		<order-migration ref="orderMigrationRef" @updateList="queryList" />
		<!-- 批量回访 -->
		<visit-batch ref="visitBatchRef" @updateList="queryList" />
	</div>
</template>

<script setup lang="tsx" name="businessVisitTodo">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessageBox, FormInstance, ElMessage } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { visitList } from '@/api/todo/visit';
import { visitSearchBaseData, visitSendSms } from '@/api/business/visit';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';
// 引入组件
const VisitDetail = defineAsyncComponent(() => import('/src/views/business/visit/components/Visit-detail.vue')); // 回访
const AssignReturnVisitors = defineAsyncComponent(() => import('@/views/business/visit/components/Assign-return-visitors.vue')); // 分配回访人
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const OrderMigration = defineAsyncComponent(() => import('@/views/todo/center/Order-migration.vue')); // 工单平移
const VisitBatch = defineAsyncComponent(() => import('@/views/business/visit/components/Visit-batch.vue')); // 批量回访
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const fastSearch = ref('all'); // tab位置
const fastSearchChange = (val: string) => {
	fastSearch.value = val;
	switch (val) {
		case 'all':
			state.queryParams.IsProvince = null;
			break;
		case 'city':
			state.queryParams.IsProvince = false;
			break;
		case 'province':
			state.queryParams.IsProvince = true;
			break;
	}
	handleQuery();
};
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 20,
		Keyword: null, // 关键字
		FiledType: null, // 归档类型
		IsCountersign: null, // 是否会签
		VisitStateQuery: 2, // 回访状态  2待回访
		VisitType: null, // 回访方式
		No: null,
		QuerySelf: 'true', // 是否只查询自己的待回访工单
		EmployeeName: null, // 回访人
		IsProvince: null, // 是否省工单
		FromPhone: null, //来电号码
		Contact: null, //联系电话
		ActualHandleOrgName: null, // 接办部门
		fbTime: [], // 发布时间
		StartPublishTime: null,
		EndPublishTime: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	visitTypeOptions: [],
});
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const channelOptions = ref<EmptyArrayType>([]);
// 获取基础数据
const getBaseData = () => {
	visitSearchBaseData().then((res: any) => {
		state.visitTypeOptions = res.result?.visitType ?? [];
		channelOptions.value = res.result?.sourceChannel ?? [];
	});
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	return new Promise((resolve, reject) => {
		state.loading = true;
		requestParams.value = Other.deepClone(state.queryParams);
		requestParams.value.StartPublishTime = state.queryParams.fbTime === null ? null : state.queryParams.fbTime[0];
		requestParams.value.EndPublishTime = state.queryParams.fbTime === null ? null : state.queryParams.fbTime[1];
		Reflect.deleteProperty(requestParams.value, 'fbTime');
		visitList(requestParams.value)
			.then((res: any) => {
				state.tableData = res.result?.items ?? [];
				state.total = res.result?.total ?? 0;
				state.loading = false;
				resolve(res);
			})
			.catch(() => {
				state.loading = false;
				reject();
			});
	});
};

/** 重置按钮操作 */
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(); // 表单ref
const drawer = ref(false);
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.QuerySelf = 'true';
	state.queryParams.IsProvince = null;
	fastSearch.value = 'all';
	ruleFormRef.value?.resetFields();
	queryList();
};
// 批量分配
const assignReturnVisitorsRef = ref<RefType>();
const multiplePeople = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	assignReturnVisitorsRef.value.openDialog(ids);
};
// 回访
const visitDetailRef = ref<RefType>();
const onManpower = (row: any) => {
	visitDetailRef.value.openDialog(row);
};
// 平移功能
const orderMigrationRef = ref<RefType>();
const onMigration = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	orderMigrationRef.value.openDialog('visitTodo', ids);
};
// 短信回访
const messageVisit = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定要选中的工单进行短信回访?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		autofocus: false,
	})
		.then(() => {
			visitSendSms({ ids })
				.then((res: any) => {
					ElMessage.success('操作成功');
					queryList();
				})
				.catch((e) => {
					console.log(e);
				});
		})
		.catch(() => {});
};
// 批量回访
const visitBatchRef = ref<RefType>();
const batchVisit = () => {
	const visit = checkTable.value.map((item: any) => {
		return {
			orderId: item.order?.id,
			visitId: item.id,
			no: item.order?.no,
		};
	});
	visitBatchRef.value.openDialog(visit);
};
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList().then(() => {
		getBaseData();
	});
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
