<template>
	<div class="business-order-container layout-pd">
    <el-card shadow="never">
        <el-tabs v-model="state.activeName" @tab-change="handleClick">
          <el-tab-pane :name="item.value" v-for="item in state.tabPaneList" :key="item.value" :label="item.label">
          </el-tab-pane>
        </el-tabs>
        <el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent class="mt15" label-width="100px">
          <el-row :gutter="10">
            <el-col :span="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 :span="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 :span="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.key" :key="item.key" :label="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </transition>
            <transition name="el-zoom-in-top">
              <el-col :span="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.key" :key="item.key" :label="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </transition>
            <transition name="el-zoom-in-top">
              <el-col :span="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 :span="8" v-show="!searchCol">
                <el-form-item label="部门" prop="OrgCode">
                  <el-cascader
                      :options="state.orgOptions"
                      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"
                  >
                    <template #default="{ node, data }">
                      <span>{{ data.orgName }}</span>
                      <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                    </template>
                  </el-cascader>
                </el-form-item>
              </el-col>
            </transition>
            <transition name="el-zoom-in-top">
              <el-col :span="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 :span="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 :span="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 :span="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 :span="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 :span="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 :span="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 :span="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 :span="8">
              <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"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
                <el-button link type="primary" @click="closeSearch">
                  {{ searchCol ? '展开' : '收起' }}
                  <SvgIcon :class="{ 'is-reverse': searchCol }" name="ele-ArrowUp" class="mr5 arrow" size="18px" />
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
    </el-card>
    <el-card shadow="never">
      <!-- 功能按钮 -->
      <div class="flex-center-between mb20 mt20">
        <p class="table-title">信息列表</p>
        <div>
          <el-button type="primary" @click="onAddWorkOrder" v-auth="'business:order:add'">
            <SvgIcon name="ele-Plus" class="mr5" />新建工单
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
        <el-table :data="state.tableList" v-loading="state.loading" row-key="id" @sort-change="sortChange">
          <el-table-column type="index" width="60" label="序号" />
          <!--  sortable="custom" 工单编码排序 -->
          <el-table-column label="工单编码" prop="no" show-overflow-tooltip width="150">
            <template #default="{row}">
              <span>{{ row.no }}</span>
            </template>
          </el-table-column>
          <el-table-column label="标题" show-overflow-tooltip width="400">
            <template #default="{row}">
              <span style="color: var(--el-color-primary)">{{ row.title }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工单状态" show-overflow-tooltip width="100">
            <template #default="{row}">
              <!-- 草稿 -->
              <span style="color: var(--el-color-info)" v-if="row.status === 0">{{ row.statusText }}</span>
              <!-- 待签收 -->
              <span style="color: var(--el-color-success)" v-if="row.status === 10">{{ row.statusText }}</span>
              <!-- 办理中 -->
              <span style="color: var(--el-color-primary)" v-if="row.status === 20">{{ row.statusText }}</span>
              <!-- 会签中 -->
              <span style="color: var(--el-color-primary)" v-if="row.status === 30">{{ row.statusText }}</span>
              <!-- 退回 -->
              <span style="color: var(--el-color-danger)" v-if="row.status === 40">{{ row.statusText }}</span>
              <!-- 办理完成 -->
              <span style="color: var(--el-color-success)" v-if="row.status === 50">{{ row.statusText }}</span>
              <!-- 已归档 -->
              <span style="color: var(--el-color-info)" v-if="row.status === 60">{{ row.statusText }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="currentStepName" label="当前环节" show-overflow-tooltip width="150"></el-table-column>
          <el-table-column prop="acceptTypeText" label="受理类型" show-overflow-tooltip width="150"></el-table-column>
          <el-table-column prop="hotspotName" label="热点分类" show-overflow-tooltip width="200"></el-table-column>
          <!--  sortable="custom" 紧急程度排序 -->
          <el-table-column label="紧急程度" show-overflow-tooltip prop="emergencyLevelText" width="100">
            <template #default="{row}">
						<span v-if="row.emergencyLevel === 2 || row.emergencyLevel === 3" style="color: var(--el-color-danger)">{{
                row.emergencyLevelText
              }}</span>
              <span v-else style="color: var(--el-color-primary)">{{ row.emergencyLevelText }}</span>
            </template>
          </el-table-column>
          <!--  sortable="custom" 办理期限排序 -->
          <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 prop="employeeName" label="受理坐席" show-overflow-tooltip width="170">
            <template #default="{row}">
              <span>{{ row.employeeName + '[' + row.employeeStaffNo + ']' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <!-- 草稿0 status 可以删除 -->
            <template #default="{ row }">
              <el-button link type="primary" @click="onOrderEdit(row)" title="编辑工单" v-if="row.status === 0" 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>
              <!-- <el-button link type="success" v-if="row.status === 0" @click="onReleaseTemp(row)" title="发布">
                  发布
                </el-button>
                <el-button link type="warning" v-if="row.status === 2" @click="tempEnable(row)" title="启用">
                  启用
                </el-button>-->

              <el-button link v-if="row.status === 0" type="danger" @click="onDeleteOrder(row)" title="删除工单" v-auth="'business:order:delete'">
                删除
              </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" />
	</div>
</template>
<script setup lang="ts" name="order">
import {defineAsyncComponent, ref, reactive, onMounted, onActivated} from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { throttle,shortcuts } from '/@/utils/tools';
import { auth } from '/@/utils/authFunction';
import other from '/@/utils/other';
import { useRouter,useRoute } from 'vue-router';
import { formatDate } from '/@/utils/formatTime';
import { listBaseData, orderList, hotSpotType, orderDelete } from '/@/api/business/order';

// 引入组件
const OrderDetail = defineAsyncComponent(() => import('/@/views/business/order/components/Order-detail.vue'));

// 定义变量内容
const ruleFormRef = ref<RefType>();
const searchCol = ref(true);
const route = useRoute();
const router = useRouter();
const OrderDetailRef = ref<RefType>();
const state = reactive(<any>{
	activeName: '0',
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 10,
		Keyword: '', // 关键字
		Content: '', // 工单内容
		AcceptType: '', // 受理类型
		Channel: '', // 渠道
		HotspotId: [], // 热点
		OrgCode: [], // 机构
		NameOrNo: '', // 受理坐席
		crTime: [], // 创建时间
		CreationTimeStart: '', // 创建时间 开始
		CreationTimeEnd: '', // 创建时间 结束
		TransferPhone: '',// 转派人
		EmergencyLevel: [], // 紧急程度
		exTime: [], // 办理期限
		ExpiredTimeStart: '', //办理期限 开始
		ExpiredTimeEnd: '', //办理期限 结束
		PhoneNo: '', // 手机号
		Status: [], // 状态
		pushTypeOptions: '',//
    PushTypeCode:'' , //推送类型
	},
	tableList: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	tabPaneList: [ //
		{
			label: '全部工单',
			value: '0',
		},
		{
			label: '即将超期',
			value: '1',
		},
		{
			label: '超期件',
			value: '2',
		},
		{
			label: '会签件',
			value: '3',
		},
		{
			label: '督办件',
			value: '4',
		},
		{
			label: '撤销件',
			value: '5',
		},
	],
	acceptTypeOptions: [], //受理类型
	channelOptions: [], // 来源频道
	emergencyLevelOptions: [], // 紧急程度
	orderStatusOptions: [], // 工单状态
	orgOptions: [], // 部门
	pushTypeOptions: [], //推送分类
	orgData: [], // 机构数据
});
const cascadeRef = ref<RefType>();
// 热点分类远程搜索
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 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',
    orgOptions: 'orgOptions',
    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'); // 删除无用的参数
		switch (state.activeName) {
			case '0':
				state.loading = true;
				orderList(request)
					.then((response: any) => {
						state.tableList = response?.result.items ?? [];
						state.total = response?.result.total;
						state.loading = false;
					})
					.catch(() => {
						state.loading = false;
					});
				break;
			case '1':
				// workflowPaged(state.queryParams)
				// 	.then((response: any) => {
				// 		state.tableList = response.result?.items ?? [];
				// 		state.total = response.result?.total ?? 0;
				// 		state.total = 1;
				setTimeout(() => {
					state.loading = false;
				}, 300);
				// 	})
				// 	.catch(() => {
				// 		state.loading = false;
				// 	});
				break;
			case '2':
				// workflowPaged(state.queryParams)
				// 	.then((response: any) => {
				// 		state.tableList = response.result?.items ?? [];
				// 		state.total = response.result?.total ?? 0;
				// 		state.total = 1;
				setTimeout(() => {
					state.loading = false;
				}, 300);
				// 	})
				// 	.catch(() => {
				// 		state.loading = false;
				// 	});
				break;
			case '3':
				// workflowPaged(state.queryParams)
				// 	.then((response: any) => {
				// 		state.tableList = response.result?.items ?? [];
				// 		state.total = response.result?.total ?? 0;
				// 		state.total = 1;
				setTimeout(() => {
					state.loading = false;
				}, 300);
				// 	})
				// 	.catch(() => {
				// 		state.loading = false;
				// 	});
				break;
			case '4':
				// workflowPaged(state.queryParams)
				// 	.then((response: any) => {
				// 		state.tableList = response.result?.items ?? [];
				// 		state.total = response.result?.total ?? 0;
				// 		state.total = 1;
				setTimeout(() => {
					state.loading = false;
				}, 300);
				// 	})
				// 	.catch(() => {
				// 		state.loading = false;
				// 	});
				break;
			case '5':
				// workflowPaged(state.queryParams)
				// 	.then((response: any) => {
				// 		state.tableList = response.result?.items ?? [];
				// 		state.total = response.result?.total ?? 0;
				// 		state.total = 1;
				setTimeout(() => {
					state.loading = false;
				}, 300);
				// 	})
				// 	.catch(() => {
				// 		state.loading = false;
				// 	});
				break;
			default:
				break;
		}
	}
};
// 表格排序
const sortChange = (column: any) => {
	console.log(column);
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.CreationTimeStart = '';
	state.queryParams.CreationTimeEnd = '';
	state.queryParams.ExpiredTimeStart = '';
	state.queryParams.ExpiredTimeStart = '';
	queryList();
}, 500);
// 切换tab 查询列表
const handleClick = () => {
	queryList();
};
// 新增工单
const onAddWorkOrder = () => {
	// 跳转到录入工单页面
	router.push('/business/order/accept');
};
// 查看详情
const onOrderDetail = (row: any) => {
	OrderDetailRef.value.openDialog(row);
};
// 编辑工单
const onOrderEdit = (row: any) => {
	router.push({
		name: 'orderEdit',
		params: {
			id: row.id,
			tagsViewName: '工单受理-' + row.no,
		},
	});
};
// 删除工单
const onDeleteOrder = (row: any) => {
	ElMessageBox.confirm(`确认删除【${row.no}】?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			orderDelete(row.id).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
onMounted(async () => {
	await getBaseData();
	queryList();
  if(route.query.tabIndex){
    state.activeName = route.query.tabIndex as string;
  }
});
onActivated(() => {
  if(route.query.tabIndex){
    state.activeName = route.query.tabIndex as string;
  }
});
</script>
<style scoped lang="scss">
.business-order-container {
	.arrow {
		transition: transform var(--el-transition-duration);
		cursor: pointer;
	}
	.arrow.is-reverse {
		transform: rotateZ(-180deg);
	}
}
</style>
