<template>
	<div class="device-phoneGroup-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<div class="mb20">
				<el-button type="primary" @click="onAddTelsGroup" v-waves v-auth="'device:phoneGroup:add'">
					<SvgIcon name="ele-Plus" class="mr5" />新增
				</el-button>
			</div>
			<el-table :data="state.tableData" v-loading="state.loading" row-key="id">
				<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="{ row }">
						{{ 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="{ row }">
						<span>{{ formatDate(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="{ row }">
						<el-button link type="primary" @click="configure(row)" v-auth="'device:phoneGroup:edit'" title="配置分机组"> 配置 </el-button>
					</template>
				</el-table-column>
				<template #empty>
					<Empty />
				</template>
			</el-table>
		</div>
		<!-- 配置分机组 -->
		<el-dialog v-model="state.dialogVisible" draggable :title="dialogTitle">
			<el-form :model="state.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="state.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="state.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="state.ruleForm.distribution" placeholder="请选择呼叫分配方式" class="w100">
								<el-option v-for="item in state.distributionOptions" :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="state.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="state.ruleForm.telNos"
								:titles="['所有分机', '已选分机']"
								:props="{ key: 'no' }"
								:data="state.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="state.ruleForm.voiceList"
								:titles="['选择语音文件', '按照选择顺序播放']"
								target-order="push"
								:data="state.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="state.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="state.dialogVisible = false" class="default-button">取 消</el-button>
					<el-button type="primary" @click="save(ruleFormRef)" :loading="state.loading">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" name="phoneGroup" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { authAll } from '/@/utils/authFunction';
import other from '/@/utils/other';
import { getTelsGroupList, addTelsGroup, updateTelsGroup, baseInfoTelsGroup } from '/@/api/device/phoneGroup';
import { getTelsList } from '/@/api/device/phone';
import { voiceQueryList } from '/@/api/device/ivr';

// 定义变量内容
const dialogTitle = ref('配置分机组');
const ruleFormRef = ref<RefType>();
const state = reactive<any>({
	ruleForm: {
		no: '', // 分机组编号
		name: '', // 分机组名称
		remark: '', // 分机组备注
		telNos: [],
		voiceList: [],
		voice: '',
		distribution: '',
		isDefault: false,
	},
	distributionOptions: [],
	loading: false,
	tableData: [],
	voiceData: [],
	dialogVisible: false,
	telsList: [],
});
/** 获取分机组列表 语音文件 基础信息 分机列表 */
const queryList = async () => {
	if (!authAll(['device:phoneGroup:query', 'public:voice:query', 'device:phoneGroup:baseData', 'device:phone:query']))
		ElMessage.error('抱歉，您没有权限获取分机组列表！');
	else {
		state.loading = true;
		try {
			const res: any = await Promise.all([getTelsGroupList(), voiceQueryList(), baseInfoTelsGroup(), getTelsList()]);
			// 分机组
			state.tableData = res[0].result ?? [];
			state.tableData = state.tableData.map((v: any) => {
				return {
					...v,
					voiceList: v.voice ? v.voice.split('+') : [],
					telNos: v.tels,
				};
			});
			// 语音文件
			state.voiceData = res[1].result.map((item: any) => {
				return {
					key: item,
					label: item,
				};
			});
			// 获取页面基础信息
			state.distributionOptions = res[2].result?.distributions ?? [];
			// 分机列表
			state.telsList = res[3].result ?? [];
			state.loading = false;
		} catch (error) {
			state.loading = false;
		}
	}
};
//配置分机组
const configure = (row: any) => {
	state.ruleForm = other.deepClone(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 = <EmptyArrayType>[];
	}
	state.dialogVisible = 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.dialogVisible = true;
};
// 保存分机组配置
const save = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		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(() => {
						queryList();
					}, 1000);
					state.dialogVisible = false;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		} else if (dialogTitle.value == '配置分机组') {
			updateTelsGroup(state.ruleForm)
				.then(() => {
					ElMessage.success('操作成功');
					setTimeout(() => {
						queryList();
					}, 1000);
					state.dialogVisible = false;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		}
	});
};
// 页面加载时
onMounted(() => {
	queryList();
});
</script>

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