<template>
	<div class="business-order-container layout-pd">
		<el-card shadow="never">
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent class="mt15" label-width="100px">
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
						<el-form-item label="关键字" prop="Keyword">
							<el-input v-model="state.queryParams.Keyword" placeholder="工单编码/标题" clearable @keyup.enter="queryList" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
						<el-form-item label="诉求详情" prop="Content">
							<el-input v-model="state.queryParams.Content" placeholder="诉求详情" clearable @keyup.enter="queryList" />
						</el-form-item>
					</el-col>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="受理类型" prop="AcceptType">
								<el-select v-model="state.queryParams.AcceptType" placeholder="请选择受理类型" multiple clearable class="w100">
									<el-option v-for="item in state.acceptTypeOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
								</el-select>
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="来源渠道" prop="Channel">
								<el-select v-model="state.queryParams.Channel" placeholder="请选择来源渠道" multiple clearable class="w100">
									<el-option v-for="item in state.channelOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
								</el-select>
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="热点分类" prop="HotspotId">
								<el-tree-select
									class="w100"
									v-model="state.queryParams.HotspotId"
									filterable
									clearable
									multiple
									:render-after-expand="false"
									show-checkbox
									placeholder="请选择热点分类"
									:props="HotspotProps"
									lazy
									:load="load"
									node-key="id"
									check-strictly
								/>
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="部门" prop="OrgCode">
								<el-cascader
									:options="state.orgsOptions"
									filterable
									:show-all-levels="false"
									:props="{ checkStrictly: true, value: 'id', label: 'orgName', emitPath: false, multiple: true }"
									placeholder="请选择所属部门"
									clearable
									class="w100"
									v-model="state.queryParams.OrgCode"
									ref="cascadeRef"
									@change="getKnowledgeList"
								>
								</el-cascader>
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="受理坐席" prop="NameOrNo">
								<el-input v-model="state.queryParams.NameOrNo" placeholder="坐席姓名/坐席工号" clearable @keyup.enter="queryList" />
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="受理时间" prop="crTime">
								<el-date-picker
									v-model="state.queryParams.crTime"
									type="datetimerange"
									unlink-panels
									range-separator="至"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									:shortcuts="shortcuts"
									@change="timeStartChangeCr"
									value-format="YYYY-MM-DD[T]HH:mm:ss"
								/>
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="转接来源" prop="TransferPhone">
								<el-input v-model="state.queryParams.TransferPhone" placeholder="请填写转接来源" clearable @keyup.enter="queryList" />
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="紧急程度" prop="EmergencyLevel">
								<el-select v-model="state.queryParams.EmergencyLevel" placeholder="请选择受理类型" multiple clearable class="w100">
									<el-option v-for="item in state.emergencyLevelOptions" :value="item.key" :key="item.key" :label="item.value" />
								</el-select>
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="办理期限" prop="exTime">
								<el-date-picker
									v-model="state.queryParams.exTime"
									type="datetimerange"
									unlink-panels
									range-separator="至"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									:shortcuts="shortcuts"
									@change="timeStartChangeEx"
									value-format="YYYY-MM-DD[T]HH:mm:ss"
								/>
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="电话号码" prop="PhoneNo">
								<el-input v-model="state.queryParams.PhoneNo" placeholder="来电号码/联系电话" clearable @keyup.enter="queryList" />
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="推送分类" prop="PushTypeCode">
								<el-select v-model="state.queryParams.PushTypeCode" placeholder="请选择推送分类" clearable class="w100">
									<el-option v-for="item in state.pushTypeOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
								</el-select>
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-show="!searchCol">
							<el-form-item label="工单状态" prop="Status">
								<el-select v-model="state.queryParams.Status" placeholder="请选择工单状态" multiple clearable class="w100">
									<el-option v-for="item in state.orderStatusOptions" :value="item.key" :key="item.key" :label="item.value" />
								</el-select>
							</el-form-item>
						</el-col>
					</transition>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
						<el-form-item label=" ">
							<div class="flex-end w100">
								<el-button type="primary" @click="queryList" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
								<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button" :loading="state.loading">
									<SvgIcon name="ele-Refresh" class="mr5" />重置
								</el-button>
								<el-button link type="primary" @click="closeSearch" :loading="state.loading">
									{{ searchCol ? '展开' : '收起' }}
									<SvgIcon :class="{ 'is-reverse': searchCol }" name="ele-ArrowUp" class="mr5 arrow" size="18px" />
								</el-button>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<el-card shadow="never">
			<!-- 功能按钮 -->
			<div class="mb20">
				<el-button type="primary" @click="onAddWorkOrder" v-auth="'business:order:add'"> <SvgIcon name="ele-Plus" class="mr5" />新建工单 </el-button>
				<el-button type="primary" @click="onCreateRepeatEvent" v-auth="'business:repeatEvent:add'">
					<SvgIcon name="ele-Plus" class="mr5" /> 创建重复性事件
				</el-button>
				<el-button type="primary" @click="onExport" v-auth="'business:order:export'" :disabled="!multipleSelection.length">
					<SvgIcon name="iconfont icon-daochu" class="mr5" />导出
				</el-button>
        <el-button type="primary" @click="onObserve" v-auth="'business:order:observe'" :disabled="!multipleSelection.length">
          <SvgIcon name="ele-View" class="mr5" />设置观察件
        </el-button>
        <el-button type="primary" @click="onEnd" v-auth="'business:order:end'" :disabled="!multipleSelection.length">
          <SvgIcon name="ele-Stopwatch" class="mr5" />设置终结件
        </el-button>
			</div>
			<!-- 表格 -->
			<el-table
				:data="state.tableData"
				v-loading="state.loading"
				row-key="id"
				@sort-change="sortChange"
				ref="multipleTableRef"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="55" />
				<el-table-column prop="no" label="工单编码" show-overflow-tooltip width="150"></el-table-column>
				<el-table-column width="100" label="省/市工单" prop="isProvince">
					<template #default="{ row }">
						<span>{{ row.isProvince ? '省工单' : '市工单' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="currentStepName" label="办理节点" show-overflow-tooltip width="150"></el-table-column>
				<el-table-column label="工单状态" show-overflow-tooltip width="100" prop="statusText"></el-table-column>
				<el-table-column label="标题" show-overflow-tooltip width="300">
					<template #default="{ row }">
						<span class="color-primary">{{ row.title }}</span>
					</template>
				</el-table-column>
				<el-table-column label="受理时间" show-overflow-tooltip width="170">
					<template #default="{ row }">
						<span>{{ formatDate(row.startTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="actualHandlerName" label="延期申请" show-overflow-tooltip width="150"></el-table-column>
				<el-table-column prop="actualHandlerName" label="重办" show-overflow-tooltip width="150"></el-table-column>
				<el-table-column prop="actualHandlerName" label="甄别状态" show-overflow-tooltip width="150"></el-table-column>
				<el-table-column prop="expiredTime" label="工单期满时间" show-overflow-tooltip width="170">
					<template #default="{ row }">
						<span>{{ formatDate(row.expiredTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="办结时间" show-overflow-tooltip width="170">
					<template #default="{ row }">
						<span>{{ formatDate(row.filedTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="orgLevelOneName" label="一级部门" show-overflow-tooltip width="170"></el-table-column>
				<el-table-column prop="actualHandleOrgName" label="接办部门" show-overflow-tooltip width="170"></el-table-column>
				<el-table-column prop="acceptType" label="受理类型" show-overflow-tooltip width="150"></el-table-column>
				<el-table-column prop="counterSignTypeText" label="中心会签" show-overflow-tooltip width="100"></el-table-column>
				<el-table-column prop="hotspotName" label="热点分类" show-overflow-tooltip width="200"></el-table-column>
				<el-table-column prop="tagNames" label="工单标签" show-overflow-tooltip width="200"></el-table-column>
				<el-table-column prop="employeeName" label="受理人" show-overflow-tooltip width="120">
					<template #default="{ row }">
						<span
							>{{ row.acceptorName }} <span v-if="row.acceptorStaffNo">[{{ row.acceptorStaffNo }}]</span>
						</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="80" fixed="right" align="center">
					<template #default="{ row }">
						<el-button
							link
							type="success"
							@click="onOrderEdit(row)"
							title="编辑工单"
							v-if="[0, 1].includes(row.status)"
							v-auth="'business:order:edit'"
						>
							修改
						</el-button>
						<el-button link type="primary" @click="onOrderDetail(row)" title="查看工单详情" v-auth="'business:order:detail'" v-else> 详情 </el-button>
					</template>
				</el-table-column>
				<template #empty>
					<Empty />
				</template>
			</el-table>
			<!-- 分页 -->
			<pagination
				:total="state.total"
				v-model:page="state.queryParams.PageIndex"
				v-model:limit="state.queryParams.PageSize"
				@pagination="queryList"
			/>
		</el-card>
		<!-- 工单详情 -->
		<order-detail ref="orderDetailRef" @updateList="queryList" />
    <!-- 编辑重复性事件 -->
    <repeat-event-edit ref="repeatEventEditRef" @updateList="queryList" />
	</div>
</template>
<script setup lang="ts" name="order">
import {defineAsyncComponent, onMounted, reactive, ref} from 'vue';
import type {FormInstance} from 'element-plus';
import {ElButton, ElMessage, ElMessageBox} from 'element-plus';
import {throttle} from '/@/utils/tools';
import {shortcuts} from '/@/utils/constants';
import {auth} from '/@/utils/authFunction';
import other from '/@/utils/other';
import {useRoute, useRouter} from 'vue-router';
import {formatDate} from '/@/utils/formatTime';
import {hotSpotType, listBaseData, orderList} from '/@/api/business/order';
import {addObserve} from "/@/api/query/observe";
import {addEnd} from "/@/api/query/end";

// 引入组件
const OrderDetail = defineAsyncComponent(() => import('/@/views/business/order/components/Order-detail.vue')); // 工单详情
const RepeatEventEdit = defineAsyncComponent(() => import('/@/views/business/repeatEvent/components/Repeat-event-edit.vue')); // 编辑重复性事件

// 定义变量内容
const state = reactive(<any>{
	queryParams: {
		// 查询条件
		PageIndex: 1, // 当前页
		PageSize: 10, // 每页条数
		Keyword: null, // 关键字
		Content: null, // 工单内容
		AcceptType: null, // 受理类型
		Channel: null, // 渠道
		HotspotId: [], // 热点
		OrgCode: [], // 机构
		NameOrNo: null, // 受理坐席
		crTime: [], // 创建时间
		CreationTimeStart: null, // 创建时间 开始
		CreationTimeEnd: null, // 创建时间 结束
		TransferPhone: null, // 转派人
		EmergencyLevel: [], // 紧急程度
		exTime: [], // 办理期限
		ExpiredTimeStart: null, //办理期限 开始
		ExpiredTimeEnd: null, //办理期限 结束
		PhoneNo: null, // 手机号
		Status: [], // 状态
		pushTypeOptions: null, //
		PushTypeCode: null, //推送类型
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	acceptTypeOptions: [], //受理类型
	channelOptions: [], // 来源频道
	emergencyLevelOptions: [], // 紧急程度
	orderStatusOptions: [], // 工单状态
	orgsOptions: [], // 部门
	pushTypeOptions: [], //推送分类
	orgData: [], // 机构数据
});
const ruleFormRef = ref<RefType>(); // 表单ref
const searchCol = ref(true); // 展开/收起
const route = useRoute(); // 路由
const router = useRouter(); // 路由
// 热点分类远程搜索
const HotspotProps = {
	label: 'hotSpotName',
	children: 'children',
	isLeaf: 'isLeaf',
};
// 热点分类远程搜索
const load = async (node: any, resolve: any) => {
	if (node.isLeaf) return resolve([]);
	let res: any = await hotSpotType({ id: node.data.id ? node.data.id : '' });
	resolve(res.result);
};
// 获取选择组织name值
const cascadeRef = ref<RefType>();
const getKnowledgeList = () => {
	let currentNode = cascadeRef.value.getCheckedNodes();
	state.queryParams.orgCode = currentNode[0]?.data.orgCode ?? '';
};
// 展开/收起
const closeSearch = () => {
	searchCol.value = !searchCol.value;
};
const handleTimeChange = (val: string[], startKey: string, endKey: string) => {
	if (val) {
		state.queryParams[startKey] = val[0];
		state.queryParams[endKey] = val[1];
	} else {
		state.queryParams[startKey] = '';
		state.queryParams[endKey] = '';
	}
};
// 受理时间
const timeStartChangeCr = (val: string[]) => {
	handleTimeChange(val, 'CreationTimeStart', 'CreationTimeEnd');
};
// 过期时间
const timeStartChangeEx = (val: string[]) => {
	handleTimeChange(val, 'ExpiredTimeStart', 'ExpiredTimeEnd');
};
// 获取查询条件基础信息
const getBaseData = async () => {
	const res: any = await listBaseData();
	const mappings: any = {
		acceptTypeOptions: 'acceptTypeOptions',
		channelOptions: 'channelOptions',
		emergencyLevelOptions: 'emergencyLevelOptions',
		orgsOptions: 'orgsOptions',
		pushTypeOptions: 'pushTypeOptions',
		orderStatusOptions: 'orderStatusOptions',
	};
	for (const key in mappings) {
		state[key] = res.result?.[mappings[key]] ?? [];
	}
};
/** 获取列表 */
const queryList = () => {
	if (!auth('business:order:query')) ElMessage.error('抱歉，您没有权限查看工单列表！');
	else {
		let request = other.deepClone(state.queryParams);
		Reflect.deleteProperty(request, 'crTime'); // 删除无用的参数
		Reflect.deleteProperty(request, 'exTime'); // 删除无用的参数
		state.loading = true;
		orderList(request)
			.then((response: any) => {
				state.tableData = response?.result.items ?? [];
				state.total = response?.result.total;
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	}
};
// 表格排序
const sortChange = (column: any) => {
	console.log(column);
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.CreationTimeStart = null;
	state.queryParams.CreationTimeEnd = null;
	state.queryParams.ExpiredTimeStart = null;
	state.queryParams.ExpiredTimeStart = null;
	queryList();
}, 300);
// 表格多选
const multipleTableRef = ref<RefType>();
const multipleSelection = ref<any>([]);
const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};
// 导出
const onExport = () => {
	console.log('导出');
};
// 设置终结件
const onObserve = ()=>{
  const titles = multipleSelection.value.map((item: any) => item.title).join(',');
  const ids = multipleSelection.value.map((item: any) => {
    return {
      orderId: item.id,
    }
  })
  ElMessageBox.confirm(`确定要将【${titles}】设置观察件吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
    autofocus: false,
  }).then(() => {
    addObserve({orderIds:ids}).then(() => {
      ElMessage.success('操作成功');
      queryList()
    })
  }).catch(() => {

  });
}
// 设置终结件
const onEnd = ()=>{
  const titles = multipleSelection.value.map((item: any) => item.title).join(',');
  const ids = multipleSelection.value.map((item: any) => {
    return {
      orderId: item.id,
    }
  })
  ElMessageBox.confirm(`确定要将【${titles}】设置终结件吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
    autofocus: false,
  }).then(() => {
    addEnd({orderIds:ids}).then(() => {
      ElMessage.success('操作成功');
      queryList()
    })
  }).catch(() => {

  });
}
// 查看详情
const orderDetailRef = ref<RefType>();
const onOrderDetail = (row: any) => {
  orderDetailRef.value.openDialog(row);
};
// 新增工单
const onAddWorkOrder = () => {
  // 跳转到录入工单页面
  router.push({
    name: 'orderAccept',
    params: {
      tagsViewName: '工单受理',
    },
  });
};
// 创建重复性事件
const repeatEventEditRef = ref<RefType>();
const onCreateRepeatEvent = ()=>{
  repeatEventEditRef.value.openDialog();
}
// 编辑工单
const onOrderEdit = (row: any) => {
	router.push({
		name: 'orderAccept',
		params: {
			tagsViewName: '工单受理-' + row.no,
			id: row.id,
			callId: '0',
		},
	});
};
onMounted(async () => {
	await getBaseData();
	queryList();
});
</script>
<style scoped lang="scss">
.business-order-container {
	.arrow {
		transition: transform var(--el-transition-duration);
		cursor: pointer;
	}
	.arrow.is-reverse {
		transform: rotateZ(-180deg);
	}
}
</style>
