<template>
	<div class="device-telsGroup-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<div class="flex-center-between mb20">
				<p class="table-title">信息列表</p>
				<div>
					<el-button type="primary" @click="onAddTelsGroup" v-waves v-auth="'300202'"> <SvgIcon name="ele-Plus" class="mr5" />新增 </el-button>
					<el-button type="primary" v-waves @click="onImportTable" :disabled="!state.multipleSelection.length">
						<SvgIcon name="iconfont icon-daochu" class="mr5" />导出
					</el-button>
				</div>
			</div>
			<el-table :data="tableData" v-loading="loading" row-key="id" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" :reserve-selection="true" />
				<el-table-column prop="no" label="编号" show-overflow-tooltip></el-table-column>
				<el-table-column prop="name" label="分机组名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="distributionText" label="呼叫分配方式" show-overflow-tooltip></el-table-column>
				<el-table-column label="是否默认分组" show-overflow-tooltip>
					<template #default="scope">
						{{ scope.row.isDefault ? '是' : '否' }}
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
				<el-table-column prop="creationTime" label="创建时间" show-overflow-tooltip width="170">
					<template #default="scope">
						<span>{{ formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="100" fixed="right" align="center">
					<template #default="scope">
						<el-button text type="primary" @click="configure(scope.row)" v-auth="'300203'" title="配置分机组">
							<SvgIcon name="ele-EditPen" size="var(--hotline-table-icon-font-size)" />
						</el-button>
					</template>
				</el-table-column>
				<template #empty>
					<Empty />
				</template>
			</el-table>
		</div>
		<!-- 配置分机组 -->
		<el-dialog v-model="isShowDialog" draggable :title="dialogTitle">
			<el-form :model="ruleForm" label-width="110px" ref="ruleFormRef">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="分机编号" prop="no">
							<el-input v-model="ruleForm.no" disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="分机组名称" prop="name" :rules="[{ required: true, message: '请输入分机组名称', trigger: 'blur' }]">
							<el-input v-model="ruleForm.name" placeholder="请输入分机组名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="呼叫分配方式" prop="distribution" :rules="[{ required: true, message: '请选择ivr类型', trigger: 'change' }]">
							<el-select v-model="ruleForm.distribution" placeholder="请选择呼叫分配方式" class="w100">
								<el-option v-for="item in distributions" :key="item.key" :label="item.value" :value="item.key" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="默认分组" prop="isDefault" :rules="[{ required: false, message: '请选择ivr类型', trigger: 'change' }]">
							<el-switch v-model="ruleForm.isDefault" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="选择分机" prop="telNos" :rules="[{ required: true, message: '请选择分机', trigger: 'change' }]">
							<el-transfer v-model="ruleForm.telNos" :titles="['所有分机', '已选分机']" :props="{ key: 'no' }" :data="telsList" :filterable="true">
								<template #default="{ option }">
									<span>分机 - {{ option.no }}</span>
								</template>
							</el-transfer>
						</el-form-item>
					</el-col>
					<!-- 语音文件 -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="语音文件" prop="voiceList" :rules="[{ required: false, message: '选择语音文件', trigger: 'change' }]">
							<el-transfer
								v-model="ruleForm.voiceList"
								:titles="['选择语音文件', '按照选择顺序播放']"
								target-order="push"
								:data="voiceData"
								:filterable="true"
							>
								<template #default="{ option }">
									<span>{{ option.label }}</span>
								</template>
							</el-transfer>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="备注" prop="remark">
							<el-input
								v-model="ruleForm.remark"
								type="textarea"
								:autosize="{ minRows: 4, maxRows: 6 }"
								placeholder="请输入备注"
								clearable
							></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="isShowDialog = false" class="default-button">取 消</el-button>
					<el-button type="primary" @click="save" :loading="loading">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" name="tels" setup>
import { ref, reactive, toRefs, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { formatDate } from '/@/utils/formatTime';
import { useUserInfo } from '/@/stores/userInfo';
import table2excel from 'js-table2excel';
// 引入需要的api
import { getTelsGroupList, addTelsGroup, updateTelsGroup, baseInfoTelsGroup } from '/@/api/device/telsGroup';
import { getTelsList } from '/@/api/device/tels';
import { voicequerylist } from '/@/api/device/ivr';

// 定义接口来定义对象的类型
interface TelsGroupState {
	ruleForm: {
		no: string; // 分机组编号
		name: string; // 分机组名称
		remark: string; // 分机组备注
		telNos: Array<any>; //选择的分机
		voiceList: Array<any>; //语音列表
		voice: string; //格式化之后的语音列表
		distribution: object; //呼叫分配方式
		isDefault: boolean; //是否默认分组
	};
	distributions: Array<any>; //呼叫分配方式列表
	loading: boolean;
	tableData: Array<any>; //列表数据
	voiceData: Array<any>; //音频文件
	isShowDialog: boolean;
	telsList: Array<any>; //分机列表
	multipleSelection: Array<any>; //多选列表
}

// 定义变量内容
const dialogTitle = ref('配置分机组');
const ruleFormRef = ref();
const state = reactive<TelsGroupState>({
	ruleForm: {
		no: '', // 分机组编号
		name: '', // 分机组名称
		remark: '', // 分机组备注
		telNos: [],
		voiceList: [],
		voice: '',
		distribution: {},
		isDefault: false,
	},
	distributions: [],
	loading: false,
	tableData: [],
	voiceData: [],
	isShowDialog: false,
	telsList: [],
	multipleSelection: [],
});
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo);
const { ruleForm, distributions, loading, tableData, voiceData, isShowDialog, telsList } = toRefs(state);
/** 获取所有语音文件列表 */
const getAudioList = () => {
	if (userInfos.value.authBtnList.includes('300201')) {
		// 校验是否有权限 页面基础信息
		voicequerylist()
			.then((response: any) => {
				state.voiceData = response.result.map((item: any) => {
					return {
						key: item,
						label: item,
					};
				});
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
		baseInfoTelsGroup().then((res: any) => {
			// 获取页面基础信息
			state.distributions = res?.result.distributions ?? [];
		});
	} else {
		ElMessage.warning('您没有权限查看页面基础信息');
	}
};
/** 获取分机列表 */
const getList = () => {
	state.loading = true;
	getTelsGroupList()
		.then((response: any) => {
			state.tableData = response?.result ?? [];
			for (let i of state.tableData) {
				i.voiceList = i.voice ? i.voice.split('+') : [];
				i.telNos = i.tels;
			}
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
const configure = (row: any) => {
	//配置分机
	state.ruleForm = JSON.parse(JSON.stringify(row));
	dialogTitle.value = '配置分机组';
	if (row.telNos) {
		//处理成穿梭框需要的数据格式
		let arr: string[] = [];
		for (let i of row.telNos) {
			arr.push(i.no);
		}
		state.ruleForm.telNos = arr;
	} else {
		state.ruleForm.telNos = <any>[];
	}
	state.isShowDialog = true;
};
//新增分机组
const onAddTelsGroup = () => {
	dialogTitle.value = '新增分机组';
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	if (state.tableData.length) {
		state.ruleForm = {
			no: String(Number(state.tableData.length + 1)), // ivr编号
			name: '',
			remark: '',
			telNos: [],
			voiceList: [],
			voice: '',
			distribution: {},
			isDefault: false,
		};
	} else {
		state.ruleForm.no = '1';
	}
	state.isShowDialog = true;
};
/** 获取分机列表 */
const getTelList = () => {
	getTelsList()
		.then((response: any) => {
			state.telsList = response?.result ?? [];
		})
		.catch(() => {});
};
// 保存分机组配置
const save = () => {
	ruleFormRef.value.validate((valid: boolean) => {
		if (valid) {
			if (state.ruleForm.voiceList.length) {
				state.ruleForm.voice = state.ruleForm.voiceList.join('+');
			}
			state.loading = true;
			if (dialogTitle.value == '新增分机组') {
				addTelsGroup(state.ruleForm)
					.then(() => {
						ElMessage.success('操作成功');
						setTimeout(() => {
							getList();
						}, 1000);
						state.isShowDialog = false;
						state.loading = false;
					})
					.catch(() => {
						state.loading = false;
					});
			} else if (dialogTitle.value == '配置分机组') {
				updateTelsGroup(state.ruleForm)
					.then(() => {
						ElMessage.success('操作成功');
						setTimeout(() => {
							getList();
						}, 1000);
						state.isShowDialog = false;
						state.loading = false;
					})
					.catch(() => {
						state.loading = false;
					});
			}
		} else {
			return false;
		}
	});
};
// 表格多选
const handleSelectionChange = (val: any) => {
	state.multipleSelection = val;
};
// 导出表格
const onImportTable = () => {
	const tabeHeader = [
		{ key: 'no', colWidth: '', title: '编号', type: 'text', isCheck: true },
		{ key: 'name', colWidth: '', title: '分机组名称', type: 'text', isCheck: true },
		{ key: 'distributionText', colWidth: '', title: '呼叫分配方式', type: 'text', isCheck: true },
		{ key: 'isDefault', colWidth: '', title: '是否默认分组', type: 'text', isCheck: true },
		{ key: 'remark', colWidth: '', title: '备注', type: 'text', isCheck: true },
		{ key: 'creationTime', colWidth: '', title: '创建时间', type: 'text', isCheck: true },
	];
	table2excel(tabeHeader, state.multipleSelection, `分机组管理 ${formatDate(new Date(), 'YYYY-mm-dd HH-MM')}`);
};
// 页面加载时
onMounted(() => {
	getTelList(); //获取分机列表
	getList();
	getAudioList();
});
</script>

<style lang="scss" scoped>
.device-telsGroup-container {
	.el-table {
		flex: 1;
	}
}
</style>
