<template>
	<div class="device-ivrList-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<div class="mb20">
				<el-button type="primary" @click="onAddIvr" v-waves v-auth="'device:ivrList:query'">
					<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="ivr编号" show-overflow-tooltip></el-table-column>
				<el-table-column prop="name" label="ivr名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="ivrTypeText" label="ivr类型" show-overflow-tooltip></el-table-column>
				<el-table-column prop="repeat" label="语音播放次数" show-overflow-tooltip></el-table-column>
				<el-table-column prop="infoLength" label="按键长度" show-overflow-tooltip></el-table-column>
				<el-table-column prop="exit" label="按键结束符" show-overflow-tooltip></el-table-column>
				<el-table-column label="操作" width="270" fixed="right" align="center">
					<template #default="{row}">
						<el-button link type="primary" @click="configure(row)" v-auth="'device:ivrList:edit'" title="基础配置"> 基础配置 </el-button>
						<el-button link type="success" @click="ivrConfigure(row)" v-auth="'device:ivrList:config'" title="策略配置"> 策略配置 </el-button>
						<el-button link type="danger" @click="resetIvrConfigure(row)" v-auth="'device:ivrList:reset'" 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="120px" ref="ruleFormRef">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="ivr编号" 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="ivr名称" prop="name" :rules="[{ required: true, message: '请输入ivr名称', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.name" placeholder="请输入ivr名称" 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="repeat" :rules="[{ required: true, message: '请输入语音播放次数', trigger: 'blur' }]">
							<el-input-number v-model="state.ruleForm.repeat" :min="1" :max="50" :precision="0" placeholder="请输入语音播放次数" class="w100" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="按键检测长度" prop="infoLength" :rules="[{ required: true, message: '请输入按键检测长度', trigger: 'blur' }]">
							<el-input-number v-model="state.ruleForm.infoLength" :min="1" :precision="0" placeholder="请输入按键检测长度" class="w100" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item
							label="按键结束字符"
							prop="exit"
							:rules="[
								{ required: false, message: '请输入按键结束字符', trigger: 'blur' },
								{ pattern: /[a-z]|[A-Z]|[1-9]#|[*]+/, message: '结束符格式错误，请输入1-9，A-D，*,#' },
							]"
						>
							<el-input v-model="state.ruleForm.exit" placeholder="请输入1-9，A-D，*,#" clearable maxlength="1"> </el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="ivr类型" prop="ivrType" :rules="[{ required: true, message: '请选择ivr类型', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.ivrType" placeholder="请选择ivr类型" class="w100">
								<el-option v-for="item in state.ivrTypes" :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="ivrCategoryId" :rules="[{ required: true, message: '请选择ivr所属分类', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.ivrCategoryId" placeholder="请选择ivr所属分类" class="w100">
								<el-option v-for="item in state.categoryList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</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: true, message: '选择语音文件', trigger: 'change' }]">
							<el-transfer
								v-model="state.ruleForm.voiceList"
								:titles="['选择语音文件', '按照选择顺序播放']"
								target-order="push"
								:data="state.voiceList"
								:filterable="true"
							>
								<template #default="{ option }">
									<span>{{ option.label }}</span>
								</template>
							</el-transfer>
						</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="onSave(ruleFormRef)" :loading="state.loading">保 存</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 策略配置 -->
		<el-dialog v-model="state.ivrKeyConfig" draggable title="策略配置">
			<el-tabs tab-position="left" class="demo-tabs" v-model="state.ivrAnswerType">
				<el-tab-pane :label="item.value" v-for="(item, index) in state.ivrStrategeTypes" :key="index" :name="item.key"></el-tab-pane>
				<!-- 语音播放完成 -->
				<el-form :model="state.voiceFinishedForm" ref="voiceFinishedFormRef" label-width="100px" v-show="state.ivrAnswerType === 0">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="响应类型" prop="ivrAnswerType">
								<el-select v-model="state.voiceFinishedForm.ivrAnswerType" placeholder="请选择响应类型" class="w100">
									<el-option v-for="item in state.ivrAnswerTypes" :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" v-if="state.voiceFinishedForm.ivrAnswerType === 1">
							<!-- 转语音选择ivr -->
							<el-form-item label="ivr">
								<el-select v-model="state.voiceFinishedForm.content" placeholder="请选择ivr" class="w100">
									<el-option v-for="item in state.ivrList" :key="item.id" :label="item.name" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.voiceFinishedForm.ivrAnswerType === 2">
							<!-- 转分机选择分机-->
							<el-form-item label="分机" prop="content">
								<el-select v-model="state.voiceFinishedForm.content" placeholder="请选择分机" class="w100">
									<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.voiceFinishedForm.ivrAnswerType === 3">
							<!-- 转分机组 -->
							<el-form-item label="分机组" prop="telsGroup">
								<el-transfer
									v-model="state.voiceFinishedForm.telsGroup"
									:titles="['选择语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.telsGroup"
									:props="{
										key: 'no',
										label: 'name',
									}"
									:filterable="true"
								>
									<template #default="{ option }">
										<span>{{ option.name }}</span>
									</template>
								</el-transfer>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.voiceFinishedForm.ivrAnswerType === 4">
							<!-- 转外部电话 -->
							<el-form-item label="外部电话" prop="content">
								<el-input v-model="state.voiceFinishedForm.content" placeholder="请输入外部电话" clearable> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<el-form-item label="插播语音" prop="voiceList">
								<el-transfer
									v-model="state.voiceFinishedForm.voiceList"
									:titles="['语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.voiceList"
									:filterable="true"
								>
									<template #default="{ option }">
										<span>{{ option.label }}</span>
									</template>
								</el-transfer>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>

				<!-- 普通按键 -->
				<el-form label-width="100px" ref="commonKeysFormRef" v-show="state.ivrAnswerType === 1">
					<div class="mb20">
						<el-button type="primary" @click="addFruitConfig"> <SvgIcon name="ele-Plus" class="mr5" />新增按键 </el-button>
					</div>
					<!-- <template v-if="keysArray.length"> -->
					<el-row :gutter="35" v-for="(itemForm, indexForm) in state.keysArray" :key="indexForm">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="按键输入" prop="input" :rules="[{ required: false, message: '请输入按键输入', trigger: 'blur' }]">
								<el-input v-model="itemForm.input" placeholder="请输入按键输入" class="w100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="响应类型" prop="ivrAnswerType">
								<el-select v-model="itemForm.ivrAnswerType" placeholder="请选择响应类型" class="w100">
									<el-option v-for="item in state.ivrAnswerTypes" :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" v-if="itemForm.ivrAnswerType === 1">
							<!-- 转语音选择ivr -->
							<el-form-item label="ivr">
								<el-select v-model="itemForm.content" placeholder="请选择ivr" class="w100">
									<el-option v-for="item in state.ivrList" :key="item.id" :label="item.name" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="itemForm.ivrAnswerType === 2">
							<!-- 转分机选择分机-->
							<el-form-item label="分机">
								<el-select v-model="itemForm.content" placeholder="请选择分机" class="w100">
									<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="itemForm.ivrAnswerType === 3">
							<!-- 转分机组 -->
							<el-form-item label="分机组" prop="telsGroup">
								<el-transfer
									v-model="itemForm.telsGroup"
									:titles="['选择语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.telsGroup"
									:props="{
										key: 'no',
										label: 'name',
									}"
									:filterable="true"
								>
									<template #default="{ option }">
										<span>{{ option.name }}</span>
									</template>
								</el-transfer>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="itemForm.ivrAnswerType === 4">
							<!-- 转外部电话 -->
							<el-form-item label="外部电话">
								<el-input v-model="itemForm.content" placeholder="请输入外部电话" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<el-form-item label="插播语音" prop="voiceList">
								<el-transfer
									v-model="itemForm.voiceList"
									:titles="['语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.voiceList"
									: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-button @click.prevent="removeFruitConfig(itemForm)" type="danger"> <SvgIcon name="ele-Delete" class="mr5" />删除按键 </el-button>
						</el-col>
						<el-divider />
					</el-row>
					<!-- </template>
                    <template v-else>
                        <Empty description="暂无按键" />
                    </template> -->
				</el-form>

				<!-- 异常按键 -->
				<el-form :model="state.abnormalKeysForm" ref="abnormalKeysFormRef" label-width="100px" v-show="state.ivrAnswerType === 2">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="响应类型" prop="ivrAnswerType">
								<el-select v-model="state.abnormalKeysForm.ivrAnswerType" placeholder="请选择响应类型" class="w100">
									<el-option v-for="item in state.ivrAnswerTypes" :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" v-if="state.abnormalKeysForm.ivrAnswerType === 1">
							<!-- 转语音选择ivr -->
							<el-form-item label="ivr" prop="content">
								<el-select v-model="state.abnormalKeysForm.content" placeholder="请选择ivr" class="w100">
									<el-option v-for="item in state.ivrList" :key="item.id" :label="item.name" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.abnormalKeysForm.ivrAnswerType === 2">
							<!-- 转分机选择分机-->
							<el-form-item label="分机" prop="content">
								<el-select v-model="state.abnormalKeysForm.content" placeholder="请选择分机" class="w100">
									<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.abnormalKeysForm.ivrAnswerType === 3">
							<!-- 转分机组 -->
							<el-form-item label="分机组" prop="telsGroup">
								<el-transfer
									v-model="state.abnormalKeysForm.telsGroup"
									:titles="['选择语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.telsGroup"
									:props="{
										key: 'no',
										label: 'name',
									}"
									:filterable="true"
								>
									<template #default="{ option }">
										<span>{{ option.name }}</span>
									</template>
								</el-transfer>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.abnormalKeysForm.ivrAnswerType === 4">
							<!-- 转外部电话 -->
							<el-form-item label="外部电话" prop="content">
								<el-input v-model="state.abnormalKeysForm.content" placeholder="请输入外部电话" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<el-form-item label="插播语音" prop="voiceList">
								<el-transfer
									v-model="state.abnormalKeysForm.voiceList"
									:titles="['语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.voiceList"
									:filterable="true"
								>
									<template #default="{ option }">
										<span>{{ option.label }}</span>
									</template>
								</el-transfer>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>

				<!-- 返回上一级 -->
				<el-form :model="state.returnPreviousForm" ref="returnPreviousFormRef" label-width="100px" v-show="state.ivrAnswerType === 3">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="响应类型" prop="ivrAnswerType">
								<el-select v-model="state.returnPreviousForm.ivrAnswerType" placeholder="请选择响应类型" class="w100">
									<el-option v-for="item in state.ivrAnswerTypes" :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" v-if="state.returnPreviousForm.ivrAnswerType === 1">
							<!-- 转语音选择ivr -->
							<el-form-item label="ivr" prop="content">
								<el-select v-model="state.returnPreviousForm.content" placeholder="请选择ivr" class="w100">
									<el-option v-for="item in state.ivrList" :key="item.id" :label="item.name" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.returnPreviousForm.ivrAnswerType === 2">
							<!-- 转分机选择分机-->
							<el-form-item label="分机" prop="content">
								<el-select v-model="state.returnPreviousForm.content" placeholder="请选择分机" class="w100">
									<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.returnPreviousForm.ivrAnswerType === 3">
							<!-- 转分机组 -->
							<el-form-item label="分机组" prop="telsGroup">
								<el-transfer
									v-model="state.returnPreviousForm.telsGroup"
									:titles="['选择语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.telsGroup"
									:props="{
										key: 'no',
										label: 'name',
									}"
									:filterable="true"
								>
									<template #default="{ option }">
										<span>{{ option.name }}</span>
									</template>
								</el-transfer>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.returnPreviousForm.ivrAnswerType === 4">
							<!-- 转外部电话 -->
							<el-form-item label="外部电话" prop="content">
								<el-input v-model="state.returnPreviousForm.content" placeholder="请输入外部电话" clearable> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<el-form-item label="插播语音" prop="voiceList">
								<el-transfer
									v-model="state.returnPreviousForm.voiceList"
									:titles="['语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.voiceList"
									:filterable="true"
								>
									<template #default="{ option }">
										<span>{{ option.label }}</span>
									</template>
								</el-transfer>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>

				<!-- 按键超时 -->
				<el-form :model="state.keyTimeoutForm" ref="keyTimeoutFormRef" label-width="100px" v-show="state.ivrAnswerType === 4">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="响应类型" prop="ivrAnswerType">
								<el-select v-model="state.keyTimeoutForm.ivrAnswerType" placeholder="请选择响应类型" class="w100">
									<el-option v-for="item in state.ivrAnswerTypes" :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" v-if="state.keyTimeoutForm.ivrAnswerType === 1">
							<!-- 转语音选择ivr -->
							<el-form-item label="ivr" prop="content">
								<el-select v-model="state.keyTimeoutForm.content" placeholder="请选择ivr" class="w100">
									<el-option v-for="item in state.ivrList" :key="item.id" :label="item.name" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.keyTimeoutForm.ivrAnswerType === 2">
							<!-- 转分机选择分机-->
							<el-form-item label="分机" prop="content">
								<el-select v-model="state.keyTimeoutForm.content" placeholder="请选择分机" class="w100">
									<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.keyTimeoutForm.ivrAnswerType === 3">
							<!-- 转分机组 -->
							<el-form-item label="分机组" prop="telsGroup">
								<el-transfer
									v-model="state.keyTimeoutForm.telsGroup"
									:titles="['选择语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.telsGroup"
									:props="{
										key: 'no',
										label: 'name',
									}"
									:filterable="true"
								>
									<template #default="{ option }">
										<span>{{ option.name }}</span>
									</template>
								</el-transfer>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.keyTimeoutForm.ivrAnswerType === 4">
							<!-- 转外部电话 -->
							<el-form-item label="外部电话" prop="content">
								<el-input v-model="state.keyTimeoutForm.content" placeholder="请输入外部电话" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<el-form-item label="插播语音" prop="voiceList">
								<el-transfer
									v-model="state.keyTimeoutForm.voiceList"
									:titles="['语音文件', '按照选择顺序播放']"
									target-order="push"
									:data="state.voiceList"
									:filterable="true"
								>
									<template #default="{ option }">
										<span>{{ option.label }}</span>
									</template>
								</el-transfer>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-tabs>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.ivrKeyConfig = false" class="default-button">取 消</el-button>
					<el-button type="primary" @click="saveIvrConfig" :loading="state.loading">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" name="ivrList" setup>
import { ref, reactive, onMounted } from 'vue';
import {ElMessage, ElMessageBox, FormInstance} from 'element-plus';
import other from '/@/utils/other';
import { authAll } from '/@/utils/authFunction';
import { getIvrCategories, baseInfo, addIvr, updateIvr, getIvrById, addEditIvr, getIvrList, voiceQueryList, resetConfig } from '/@/api/device/ivr';
import { getTelsGroupList } from '/@/api/device/phoneGroup';
import { getTelsList } from '/@/api/device/phone';

// 定义接口来定义对象的类型
interface IvrListState {
	ruleForm: {
		no: string; // ivr编号
		name: string; // ivr名称
		repeat: number; // 语音播放次数
		infoLength: number; // 按键长度
		exit: string; // 按键结束符
		ivrCategoryId: string; // 分类id
		voiceList: Array<any>; //语音列表
		voice: string; //格式化之后的语音列表
		ivrType: string; //vir类型
	};
  ivrStrategeTypes: Array<any>; //策略配置的类型数组
	ivrAnswerTypes: Array<any>; //应答类型数组
	ivrList: Array<any>; //vir列表
	telsList: Array<any>; //分机列表
	telsGroup: Array<any>; //分机组列表
	voiceList: Array<any>; //所有语音
	keysArray: Array<any>; //按键列表
	categoryList: Array<any>; //分类列表
	loading: boolean;
	tableData: Array<any>; //列表数据
	dialogVisible: boolean; // 新增编辑弹窗
  ivrKeyConfig: boolean; // 策略配置弹窗
	ivrAnswerType: number; // 选择的策略配置
	ivrTypes: Array<any>; //ivr类型列表
	voiceFinishedForm: {
		// 语音播放完
		ivr: any;
		ivrStrategeType: any;
		ivrAnswerType: any;
		content: any;
		telsGroup: Array<any>;
		voiceList: Array<any>;
	};
	abnormalKeysForm: {
		// 异常按键
		ivr: any;
		ivrStrategeType: any;
		ivrAnswerType: any;
		content: any;
		telsGroup: Array<any>;
		voiceList: Array<any>;
	};
	returnPreviousForm: {
		// 返回上一级
		ivr: any;
		ivrStrategeType: any;
		ivrAnswerType: any;
		content: any;
		telsGroup: Array<any>;
		voiceList: Array<any>;
	};
	keyTimeoutForm: {
		// 按键超时
		ivr: any;
		ivrStrategeType: any;
		ivrAnswerType: any;
		content: any;
		telsGroup: Array<any>;
		voiceList: Array<any>;
	};
}

// 定义变量内容
const currentIvr = ref<any>(undefined); //当前ivr
const dialogTitle = ref('新增ivr');
const ruleFormRef = ref<RefType>();
const state = reactive<IvrListState>({
	ruleForm: {
		no: '', // ivr编号
		name: '', // ivr名称
		repeat: 1,
		infoLength: 1,
		exit: '',
		ivrCategoryId: '',
		voiceList: [],
		voice: '',
		ivrType: '',
	},
	ivrStrategeTypes: [],
	ivrAnswerTypes: [],
	ivrAnswerType: 0,
	ivrList: [],
	telsList: [],
	telsGroup: [],
	voiceList: [],
	keysArray: [],
  categoryList: [],
	ivrTypes: [],
	tableData: [],
	dialogVisible: false,
  ivrKeyConfig: false,
	loading: false,
	voiceFinishedForm: {
		ivr: null,
		ivrStrategeType: null,
		ivrAnswerType: null,
		content: '',
		telsGroup: [],
		voiceList: [],
	},
	abnormalKeysForm: {
		//异常按键
		ivr: null,
		ivrStrategeType: null,
		ivrAnswerType: null,
		content: '',
		telsGroup: [],
		voiceList: [],
	},
	returnPreviousForm: {
		ivr: null,
		ivrStrategeType: null,
		ivrAnswerType: null,
		content: '',
		telsGroup: [],
		voiceList: [],
	},
	keyTimeoutForm: {
		ivr: null,
		ivrStrategeType: null,
		ivrAnswerType: null,
		content: '',
		telsGroup: [],
		voiceList: [],
	},
});

/** 获取ivr列表 */
const queryList = async () => {
	if (
		!authAll([
			'device:ivrList:query',
			'public:voice:query',
			'device:ivrCategory:query',
			'device:phone:query',
			'device:phoneGroup:query',
			'device:ivrList:baseData',
		])
	)
		ElMessage.error('抱歉，您没有权限获取获取ivr列表！');
	else {
		state.loading = true;
		try {
			const res: any = await Promise.all([getIvrList(), voiceQueryList(), getIvrCategories(), getTelsList(), getTelsGroupList(), baseInfo()]);
			// 列表
			state.tableData = res[0].result ?? [];
			// 语音文件
			state.voiceList = res[1].result.map((item: any) => {
				return {
					key: item,
					label: item,
				};
			});
			// vir分类
			state.categoryList = res[2].result ?? [];
			// 分机列表
			state.telsList = res[3].result ?? [];
			// 分机组
			state.telsGroup = res[4].result ?? [];
			// 基础数据
			state.ivrTypes = res[5].result?.ivrTypes ?? [];
			state.ivrAnswerTypes = res[5].result?.ivrAnswerTypes ?? [];
			state.ivrStrategeTypes = res[5].result?.ivrStrategeTypes ?? [];
			state.loading = false;
		} catch (error) {
			state.loading = false;
		}
	}
};
// 新增Ivr
const onAddIvr = () => {
	dialogTitle.value = '新增ivr';
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	if (state.tableData.length) {
		state.ruleForm = {
			no: String(Number(state.tableData.length + 1)), // ivr编号
			name: '', // ivr名称
			repeat: 1,
			infoLength: 1,
			exit: '',
			ivrCategoryId: '',
			voiceList: [],
			voice: '',
			ivrType: '',
		};
	} else {
		state.ruleForm.no = '1';
	}
	state.dialogVisible = true;
};
//修改 配置ivr
const configure = (row: any) => {
	dialogTitle.value = '基础配置';
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	state.ruleForm = other.deepClone(row);
	if (row.voice) {
		//处理成穿梭框需要的数据格式
		state.ruleForm.voiceList = row.voice.split('+');
	}
	state.dialogVisible = true;
};
// 新增修改基础配置保存
const onSave = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid: boolean) => {
    if (!valid) return;
    if (state.tableData.length && Number(state.tableData[state.tableData.length - 1].no) >= 50) {
      ElMessage.warning('ivr最多配置50条');
      return;
    }
    state.ruleForm.voice = state.ruleForm.voiceList.join('+');
    if (dialogTitle.value == '新增ivr') {
      addIvr(state.ruleForm)
          .then(() => {
            ElMessage.success('新增成功');
            queryList();
            state.dialogVisible = false;
          })
          .catch(() => {});
    } else if (dialogTitle.value == '基础配置') {
      updateIvr(state.ruleForm)
          .then(() => {
            ElMessage.success('配置成功');
            queryList();
            state.dialogVisible = false;
          })
          .catch(() => {});
    }
  })
};
// 新增按键ivr
const addFruitConfig = () => {
	state.keysArray.unshift({
		ivr: null,
		ivrStrategeType: null,
		ivrAnswerType: null,
		content: '',
		input: '',
		telsGroup: [],
		voiceList: [],
		ivrId: Math.random(),
	});
};
// 删除按键ivr
const removeFruitConfig = (val: any) => {
	ElMessageBox.confirm(`确定要删除当前按键ivr，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		beforeClose: (action, instance, done) => {
			if (action === 'confirm') {
				instance.confirmButtonLoading = true;
				instance.confirmButtonText = '删除中';
				setTimeout(() => {
					done();
					setTimeout(() => {
						instance.confirmButtonLoading = false;
					}, 300);
				}, 700);
			} else {
				done();
			}
		},
	})
		.then(() => {
			state.keysArray = state.keysArray.filter((item: any) => item.ivrId != val.ivrId);
		})
		.catch(() => {});
};
const voiceFinishedFormRef = ref<RefType>();
const commonKeysFormRef = ref<RefType>();
const abnormalKeysFormRef = ref<RefType>();
const returnPreviousFormRef = ref<RefType>();
const keyTimeoutFormRef = ref<RefType>();
// 配置策略
const ivrConfigure = (row: any) => {
	currentIvr.value = other.deepClone(row);
	state.keysArray = [];
	state.ivrAnswerType = 0;
	getIvrById(row.ivrCategoryId).then((res: any) => {
		// 根据分类ID查出分类下所有的ivr  排除根节点
		state.ivrList = res?.result.ivrs.filter((item: any) => item.id != row.ivrCategoryId) ?? [];
	});
	if (voiceFinishedFormRef.value) voiceFinishedFormRef.value.resetFields();
	// if (commonKeysFormRef.value && state.keysArray.length) commonKeysFormRef.value.resetFields();
	if (abnormalKeysFormRef.value) abnormalKeysFormRef.value.resetFields();
	if (returnPreviousFormRef.value) returnPreviousFormRef.value.resetFields();
	if (keyTimeoutFormRef.value) keyTimeoutFormRef.value.resetFields();
	for (let i of row.ivrStrategies) {
		switch (i.ivrStrategeType) {
			case 0: // 语音播放完
				let arr0 = <EmptyArrayType>[];
				state.voiceFinishedForm.ivrAnswerType = i.answer.ivrAnswerType;
				state.voiceFinishedForm.content = i.answer.content;
				state.voiceFinishedForm.voiceList = i.answer.preVoice.split('+');
				for (let j of i.groupSorts) {
					arr0.push(j.groupNo);
				}
				state.voiceFinishedForm.telsGroup = arr0;
				break;
			case 1: // 普通按键
				let arr1 = <EmptyArrayType>[];
				let obj: any = {};
				obj.ivrAnswerType = i.answer.ivrAnswerType;
				obj.content = i.answer.content;
				obj.input = i.input;
				obj.voiceList = i.answer.preVoice.split('+');
				for (let j of i.groupSorts) {
					arr1.push(j.groupNo);
				}
				obj.telsGroup = arr1;
				obj.ivrId = Math.random();
				state.keysArray.push(obj);
				break;
			case 2: // 异常按键
				let arr2 = <EmptyArrayType>[];
				state.abnormalKeysForm.ivrAnswerType = i.answer.ivrAnswerType;
				state.abnormalKeysForm.content = i.answer.content;
				state.abnormalKeysForm.voiceList = i.answer.preVoice.split('+');
				for (let j of i.groupSorts) {
					arr2.push(j.groupNo);
				}
				state.abnormalKeysForm.telsGroup = arr2;
				break;
			case 3: // 返回上一级
				let arr3 = <EmptyArrayType>[];
				state.returnPreviousForm.ivrAnswerType = i.answer.ivrAnswerType;
				state.returnPreviousForm.content = i.answer.content;
				state.returnPreviousForm.voiceList = i.answer.preVoice.split('+');
				for (let j of i.groupSorts) {
					arr3.push(j.groupNo);
				}
				state.returnPreviousForm.telsGroup = arr3;
				break;
			case 4: // 按键超时
				let arr4 = <EmptyArrayType>[];
				state.keyTimeoutForm.ivrAnswerType = i.answer.ivrAnswerType;
				state.keyTimeoutForm.content = i.answer.content;
				state.keyTimeoutForm.voiceList = i.answer.preVoice.split('+');
				for (let j of i.groupSorts) {
					arr4.push(j.groupNo);
				}
				state.keyTimeoutForm.telsGroup = arr4;
				break;
			default:
				break;
		}
	}
	state.ivrKeyConfig = true;
};
// 保存ivr配置
const saveIvrConfig = () => {
	let arr1: any = [];
	let arr3: any = [];
	let arr4: any = [];
	let arr5: any = [];
	for (let i in state.voiceFinishedForm.telsGroup) {
		arr1.push({
			sort: Number(i),
			groupNo: state.voiceFinishedForm.telsGroup[i],
		});
	}
	for (let i in state.abnormalKeysForm.telsGroup) {
		arr3.push({
			sort: Number(i),
			groupNo: state.abnormalKeysForm.telsGroup[i],
		});
	}
	for (let i in state.returnPreviousForm.telsGroup) {
		arr4.push({
			sort: Number(i),
			groupNo: state.returnPreviousForm.telsGroup[i],
		});
	}
	for (let i in state.keyTimeoutForm.telsGroup) {
		arr5.push({
			sort: Number(i),
			groupNo: state.keyTimeoutForm.telsGroup[i],
		});
	}
	let request = {
		id: currentIvr.value.id,
		prevIvrNo: '',
		ivrStrategies: <EmptyArrayType>[],
	};
	if (state.voiceFinishedForm.ivrAnswerType) {
		// 语音播放完成
		request.ivrStrategies.push({
			ivrStrategeType: 0,
			answer: {
				ivrAnswerType: state.voiceFinishedForm.ivrAnswerType,
				content: state.voiceFinishedForm.content,
				preVoice: state.voiceFinishedForm.voiceList ? state.voiceFinishedForm.voiceList.join('+') : '',
			},
			groupSorts: arr1,
		});
	}
	if (state.abnormalKeysForm.ivrAnswerType) {
		// 异常按键
		request.ivrStrategies.push({
			ivrStrategeType: 2,
			answer: {
				ivrAnswerType: state.abnormalKeysForm.ivrAnswerType,
				content: state.abnormalKeysForm.content,
				preVoice: state.abnormalKeysForm.voiceList ? state.abnormalKeysForm.voiceList.join('+') : '',
			},
			groupSorts: arr3,
		});
	}
	if (state.returnPreviousForm.ivrAnswerType) {
		// 返回上一级
		request.ivrStrategies.push({
			ivrStrategeType: 3,
			answer: {
				ivrAnswerType: state.returnPreviousForm.ivrAnswerType,
				content: state.returnPreviousForm.content,
				preVoice: state.returnPreviousForm.voiceList ? state.returnPreviousForm.voiceList.join('+') : '',
			},
			groupSorts: arr4,
		});
	}
	if (state.keyTimeoutForm.ivrAnswerType) {
		//  按键超时
		request.ivrStrategies.push({
			ivrStrategeType: 4,
			answer: {
				ivrAnswerType: state.keyTimeoutForm.ivrAnswerType,
				content: state.keyTimeoutForm.content,
				preVoice: state.keyTimeoutForm.voiceList ? state.keyTimeoutForm.voiceList.join('+') : '',
			},
			groupSorts: arr5,
		});
	}
	for (let i of state.keysArray) {
		// 拼入普通按键
		let arr2: any = [];
		for (let j in i.telsGroup) {
			arr2.push({
				sort: Number(j),
				groupNo: i.telsGroup[j],
			});
		}
		request.ivrStrategies.push({
			ivrStrategeType: 1,
			input: i.input,
			answer: {
				ivrAnswerType: i.ivrAnswerType,
				content: i.content,
				preVoice: i.voiceList ? i.voiceList.join('+') : '',
			},
			groupSorts: arr2,
		});
	}

	state.loading = true;
	addEditIvr(request)
		.then(() => {
			ElMessage.success('操作成功');
			queryList();
			state.ivrKeyConfig = false;
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
// 重置策略配置
const resetIvrConfigure = (row: any) => {
	ElMessageBox.confirm(`确定要重置：【${row.name}】策略配置，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			resetConfig(row.id).then(() => {
				ElMessage.success('重置成功');
				queryList();
			});
		})
		.catch(() => {});
};
onMounted(() => {
	queryList();
});
</script>

<style lang="scss" scoped>
.device-ivrList-container {
	:deep(.el-tabs__nav-wrap::after) {
		height: 100% !important;
	}
	.el-table {
		flex: 1;
	}
}
</style>
