<template>
	<div class="textarea w100">
		<el-input
			v-model="value"
			type="textarea"
			show-word-limit
			:autosize="{ minRows: props.minRows, maxRows: props.maxRows }"
			:placeholder="props.placeholder"
			:maxlength="props.maxlength"
			:disabled="props.disabled"
      class="textarea-content"
		>
		</el-input>
		<span class="buttons">
			<el-button @click="showAdvice" class="default-button"  :disabled="props.disabled">常用意见</el-button>
			<el-button type="primary" @click="onAddAdvice" :disabled="props.disabled">添加到常用意见</el-button>
		</span>
		<el-drawer v-model="state.showDrawer" :size="props.drawerWidth" :show-close="false" :modal="props.modal">
			<template #header="{ close }">
				<div class="comments-header">
					<div>
						<el-button link @click="state.active = 'default'" :class="{ active: state.active === 'default' }"> 常用意见 </el-button>
						<el-button link @click="state.active = 'add'" :class="{ active: state.active === 'add' }"> 新增个人意见 </el-button>
						<span></span>
					</div>
				</div>
				<div class="flex-center-align">
					<el-button
						link
						@click="state.manage = true"
						v-if="!state.manage && state.active === 'default' && state.adviceList.length && activeName === 'personal'"
						>管理个人常用意见</el-button
					>
					<el-button
						link
						@click="state.manage = false"
						type="primary"
						v-if="state.manage && state.active === 'default' && state.adviceList.length && activeName === 'personal'"
						>返回</el-button
					>
					<el-button link @click="close">
						<SvgIcon name="ele-Close" class="mr5" @click="close" size="16px" />
					</el-button>
				</div>
			</template>
			<div class="comments-container" v-loading="state.loading">
				<el-tabs v-model="activeName" @tab-change="handleClick" v-if="state.active === 'default'">
					<el-tab-pane label="个人常用意见" name="personal"></el-tab-pane>
					<el-tab-pane label="公共常用意见" name="public"></el-tab-pane>
				</el-tabs>
				<template v-if="state.adviceList.length">
					<!-- 默认状态 -->
					<template v-if="state.active === 'default' && !state.manage">
						<ul class="comments-box">
							<li class="comments-item" v-for="(item, index) in state.adviceList" :key="index" @click="chooseAdvice(item)">
								<p class="text-ellipsis2" :title="item.content">{{ item.content }}</p>
							</li>
						</ul>
					</template>
					<!-- 管理 -->
					<template v-if="state.active === 'default' && state.manage">
						<ul class="comments-box">
							<li
								class="comments-item"
								v-for="(item, index) in state.adviceList"
								:class="[item.ischeck === true ? 'chose' : '']"
								:key="index"
								@click="handleAdvice(item, <number>index)"
							>
								<p class="text-ellipsis2" :title="item.content">{{ item.content }}</p>
								<el-checkbox v-model="item.ischeck" class="check-icon" label="" v-if="item.ischeck" size="large" />
							</li>
						</ul>
					</template>
				</template>
				<template v-if="!state.adviceList.length && state.active !== 'add'">
					<Empty description="暂无常用语" />
				</template>
				<!-- 新增意见 -->
				<template v-if="state.active === 'add'">
					<div>
						<el-form :model="state.adviceForm" ref="adviceFormRef">
							<el-form-item label="" prop="content" :rules="[{ required: true, message: '请填写常用意见内容', trigger: 'blur' }]">
								<el-input
									v-model="state.adviceForm.content"
									type="textarea"
									:autosize="{ minRows: 10, maxRows: 10 }"
									placeholder="请填写常用意见内容"
                  show-word-limit
                  maxlength="200"
								>
								</el-input>
							</el-form-item>
						</el-form>
					</div>
				</template>
			</div>
			<template #footer v-if="state.active === 'add' || state.manage">
				<div style="flex: auto">
					<el-button
						@click="deleteAdvice"
						class="default-button"
						:disabled="!state.chooseAdvice.length"
						v-if="state.active === 'default' && state.manage"
						>删 除</el-button
					>
					<el-button type="primary" @click="adviceSave(adviceFormRef)" v-if="state.active === 'add'">保 存</el-button>
				</div>
			</template>
		</el-drawer>
	</div>
</template>

<script setup lang="ts" name="commonAdvice">
import { reactive, ref, computed } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { commonList, addCommon, deleteCommon } from '/@/api/system/commonAdvice';
import { commonEnum } from '/@/utils/constants';
const emit = defineEmits(['chooseAdvice', 'update:modelValue']);
const props = defineProps({
	modal: {
		type: Boolean,
		default:false,
	},
	modelValue: {
		type: String,
		default: '',
	},
	disabled: {
		type: Boolean,
		default: false,
	},
	placeholder: {
		type: String,
		default: '请填写内容',
	},
	loading: {
		type: Boolean,
		default: false,
	},
	commonEnum: {
		type: [String, Number],
		default: commonEnum['Seat'],
	},
	minRows: {
		type: [Number, String, undefined],
		default: 6,
	},
	maxRows: {
		type: [Number, String, undefined],
		default: 20,
	},
	maxlength: {
		type: [Number, String, undefined],
		default: 2000,
	},
	drawerWidth: {
		type: [Number, String],
		default: '35%',
	},
} as any);
const activeName = ref('personal'); // 默认选中tab
const value = computed({
	get() {
		return props.modelValue;
	},
	set(value) {
		emit('update:modelValue', value);
	},
});
// 定义变量内容
const state = reactive<any>({
	showDrawer: false, // 是否显示弹窗
	adviceList: [], // 常用意见列表
	adviceForm: {
		// 新增常用意见
		content: '',
	},
	chooseAdvice: [], // 选中的常用意见
	active: 'default', // 当前状态
	manage: false, // 是否是管理状态
	loading: false, // 是否显示loading
	commonType: '', // 类型
});

// 打开常用意见管理
const showAdvice = () => {
	openDialog();
};
// 添加到常用意见
const onAddAdvice = async () => {
	if (!props.modelValue) {
		ElMessage.warning(props.placeholder);
		return;
	}
	ElMessageBox.confirm(`确认要添加到常用意见?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(async () => {
			await addCommon({
				commonType: props.commonEnum,
				isOpen: false, // 个人意见
				content: props.modelValue,
			});
			ElMessage.success('操作成功');
			closeDialog();
		})
		.catch(() => {});
};
// 打开弹窗
const adviceFormRef = ref<RefType>();
const openDialog = async () => {
	state.commonType = props.commonEnum;
	state.active = 'default';
	adviceFormRef.value?.resetFields();
	state.manage = false;
	await getList();
	state.showDrawer = true;
};
const isOpen = ref<boolean>(false);
const getList = async () => {
	try {
		state.loading = true;
		const res: any = await commonList({ commonType: props.commonEnum, isOpen: isOpen.value });
		state.adviceList = res.result;
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};

// 切换tab查询意见
const handleClick = (val: string) => {
	isOpen.value = val === 'public';
  if(isOpen.value) state.manage = false;
	getList();
};
// 选中常用意见（管理）
const handleAdvice = (item: any, index: number) => {
	const repeatData = [...state.adviceList];
	const repeatSolar = [...state.chooseAdvice];
	if (!repeatData[index].ischeck) {
		repeatData[index].ischeck = true;
		repeatSolar.push(item);
	} else {
		repeatData[index].ischeck = false;
		if (!repeatSolar || repeatSolar.length == 0) {
			return '';
		}
		repeatSolar.splice(index, 1);
	}
	state.chooseAdvice = repeatSolar.filter((item: any) => item.ischeck);
};
// 重置状态
const resetState = () => {
	state.active = 'default';
	state.manage = false;
	state.chooseAdvice = [];
	state.adviceForm.content = '';
	getList();
};
// 删除常用意见
const deleteAdvice = () => {
	if (!state.chooseAdvice.length) {
		ElMessage.warning('请选择要删除的常用意见');
		return;
	}
	ElMessageBox.confirm(`确定要删除选中的常用意见，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		draggable: true,
		cancelButtonClass: 'default-button',
		type: 'warning',
	})
		.then(() => {
      const ids = state.chooseAdvice.map((item: any) => item.id);
			deleteCommon({ ids }).then(() => {
				ElMessage.success('操作成功');
				resetState();
				state.loading = false;
			});
		})
		.catch(() => {});
};
// 添加常用意见 保存
const adviceSave = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		addCommon({
			commonType: state.commonType,
			content: state.adviceForm.content,
		}).then(() => {
			ElMessage.success('操作成功');
			resetState();
			state.loading = false;
		});
	});
};
// 选择常用意见 填入填写框
const chooseAdvice = (item: any) => {
	emit('chooseAdvice', item);
	closeDialog();
};
// 关闭弹窗
const closeDialog = () => {
	state.showDrawer = false;
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style lang="scss" scoped>
.textarea {
  .textarea-content{
    position: relative;
    :deep(.el-input__count) {
      font-size: 16px;
      bottom: 18px;
      right: 250px;
    }
  }
	.buttons {
		position: absolute;
		right: 10px;
		bottom: 10px;
	}
	:deep(.el-textarea__inner) {
		padding-bottom: 40px;
	}
}
.comments-container {
	.comments-box {
		.comments-item {
			border: var(--el-border);
			border-radius: var(--el-border-radius-base);
			margin-bottom: 10px;
			padding: 8px 15px;
			cursor: pointer;
			position: relative;
			line-height: 18px;
			&:hover {
				box-shadow: 0 0 0 1px var(--el-color-primary) inset;
				background-color: var(--hotline-bg-main-color);
			}
			.check-icon {
				position: absolute;
				right: 0;
				top: -13px;
			}
		}
		.chose {
			box-shadow: 0 0 0 1px var(--el-color-primary) inset;
		}
	}
}
.comments-header {
	.active {
		color: var(--el-color-primary);
		//font-size: var(--el-font-size-medium);
	}
}
:deep(.el-drawer__footer) {
	box-shadow: 0px -4px 10px 0px rgb(0 0 0 / 10%);
	border-radius: 0 0 8px 0;
	padding: 10px 20px;
}
</style>
