<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from "vue";
import { useRouter } from "vue-router";
import { getProjListData} from "@/api/mock.js";
import { useTableList } from "@/composables/useTableList.js";

const { proxy } = getCurrentInstance();
const user = JSON.parse(proxy.$vtk.storage.get("_mis_acis_users"));
const router = useRouter();
const dict = proxy.$vtk.filters.dict;
const date = proxy.$vtk.filters.date;
const breadcrumbBack = () => {
	router.back();
};

const breadcrumbItems = [
	{ title: "首页", to: "" },
	{ title: "评价回访", to: "" },
	{ title: "事项配置" },
];

const type = ref("A");
const cataList = [
	{ state: "A", bizName: "全部" },
	{ state: "0", bizName: "未启用" },
	{ state: "1", bizName: "已启用" },
];

const editDialog = reactive({ visible: false });
const entity = ref({
	id: "",
	projName: "",
	rateType: "",
	rateText: "",
	rateTime: "",
	rateNote: "",
	projId: "",
	rateTypeArr: [],
});
const valid = ref(true);
const entityRef = ref(null);
const rateTextArea = ref(null);

const rateTimeOptions = "全天 09点至19点:全天 09点至19点/工作日 09点至19点:工作日 09点至19点/休息日 09点至19点:休息日 09点至19点";
const suggestionWords = [
	{ label: "对象姓名", value: "${objsName}" },
	{ label: "事项名称", value: "${projName}" },
	{ label: "申请时间", value: "${servTime}" },
	{ label: "办理途径", value: "${servFrom}" },
];

const {
	loading,
	desserts,
	queryParam,
	pageData,
	headers,
	loadPage,
	handlePageChange,
	handleSearch,
} = useTableList({
	fetchApi: getProjListData,
	defaultQuery: {
		state: type.value,
		areaCode: user?.areacode,
		condition: "",
	},
	headers: [
		{ title: "序", key: "first_col", width: 40, sortable: false },
		{ title: "事项", key: "projName", sortable: false },
		{ title: "配置信息", key: "rateInfo", sortable: false },
		{ title: "是否启用", key: "state", sortable: false, width: 120 },
		{ title: "操作", key: "actions", sortable: false, width: 120 },
	]
});

const searchQuery = () => {
	handleSearch();
};

const addSuggestionWord = (word) => {
	const textarea = rateTextArea.value?.$el?.querySelector("textarea");
	if (textarea) {
		const start = textarea.selectionStart;
		const end = textarea.selectionEnd;
		const text = entity.value.rateText || "";
		entity.value.rateText = text.substring(0, start) + word + text.substring(end);
		nextTick(() => {
			textarea.selectionStart = start + word.length;
			textarea.selectionEnd = start + word.length;
			textarea.focus();
		});
	} else {
		entity.value.rateText = (entity.value.rateText || "") + word;
	}
};

const getRateTypeText = (rateType) => {
	if (!rateType) return "";
	const rateTypeMap = { "1": "短信", "2": "电话" };
	if (rateType.includes(",")) {
		return rateType.split(",").map((type) => rateTypeMap[type.trim()] || "").join("、");
	}
	return rateTypeMap[rateType] || "";
};

const toggleStateHandler = (item) => {
	toggleRateState(proxy, { id: item.id }).then((res) => {
		if (res.meta.success) {
			proxy.$vtk.message.toast("状态切换成功", { color: "success" });
			searchQuery();
		} else {
			proxy.$vtk.message.toast("状态切换失败", { color: "red" });
		}
	});
};

const change = (item) => {
	type.value = item.state;
	queryParam.value.state = item.state;
	searchQuery();
};

const openManageDialog = (item) => {
	entityRef.value?.reset();
	entity.value = JSON.parse(JSON.stringify(item));
	if (entity.value.rateType) {
		entity.value.rateTypeArr = entity.value.rateType.split(",");
	}
	if (!entity.value.rateText) {
		entity.value.rateText = "您好，${objsName}，您在${servTime}通过${servFrom}办理了${projName}，请您用1~5分对我们的服务进行评价打分！";
	}
	editDialog.visible = true;
};

const closeEditDialog = () => {
	editDialog.visible = false;
	entity.value = {
		id: "",
		projName: "",
		rateType: "",
		rateText: "",
		rateTime: "",
		rateNote: "",
		projId: "",
		rateTypeArr: [],
	};
};

const saveConfigHandler = () => {
	if (entityRef.value.validate()) {
		entity.value.rateCron = "无";
		entity.value.state = "1";
		entity.value.operator = user.value.username;
		entity.value.rateType = entity.value.rateTypeArr.join(",");

		saveRateConfig(proxy, entity.value).then((res) => {
			if (res.meta.success) {
				proxy.$vtk.message.toast("保存成功", { color: "success" });
				closeEditDialog();
				searchQuery();
			} else {
				proxy.$vtk.message.toast("保存失败", { color: "red" });
			}
		});
	}
};

const del = (item) => {
	proxy.$vtk.message.confirm({
		title: "确认删除",
		text: "确认删除该配置么？",
		onConfirm: () => {
			deleteRateConfig(proxy, { id: item.id }).then((res) => {
				if (res.meta.success) {
					proxy.$vtk.message.toast("删除成功", { color: "success" });
					searchQuery();
				} else {
					proxy.$vtk.message.toast(res.meta.message, { color: "error" });
				}
			});
		},
	});
};

const detail = (item) => {
	// router.push({ path: "/fwzx/sets-view", query: { id: item.id, projId: item.projId } });
};

onMounted(() => {
	loadPage();
});
</script>

<template>
	<div >
		<div class="d-flex justify-space-between">
			<VtkBreadcrumb :items="breadcrumbItems" class="pt-0" :show-back="true" @back="breadcrumbBack" />
		</div>
		<v-card elevation="0" >
			<v-card-title class="d-flex pt-3">
				<v-btn-toggle v-model="type" mandatory color="primary" density="compact">
					<v-btn v-for="item in cataList" :key="item.state" :value="item.state" @click="change(item)">{{ item.bizName }}</v-btn>
				</v-btn-toggle>
				<v-spacer />
				<v-text-field style="max-width: 380px" class="vtk-field" v-model="queryParam.condition"
					@click:append="searchQuery" @keyup.enter="searchQuery" placeholder="关键字查询"
					append-inner-icon="mdi-magnify" variant="outlined" clearable density="compact"
					hide-details></v-text-field>
			</v-card-title>
			<v-card-text >
				<v-data-table :headers="headers" :items="desserts" :loading="loading" hide-default-footer
					loading-text="数据加载中..." class="elevation-0">
					<template v-slot:item.first_col="{ index }">
						{{ index + 1 }}
					</template>
					<template v-slot:item.projName="{ item }">
						<div @click="detail(item)" class="py-3 vtk-cursor-pointer">
							<span :title="item.projName" class="vtk-cursor-pointer text-body-1 font-weight-bold">
								<v-chip class="ml-1"
									:class="proxy.$vtk.filters.dict(item.areaLeve, '1:green-lighten-5 text-green/2:blue-lighten-5 text-blue/4:cyan-lighten-5 text-cyan/6:orange-lighten-5 text-orange')"
									size="small" label>
									{{ proxy.$vtk.filters.dict(item.areaLeve, "0:国家/2:省级/4:市级/6:区县") }}
								</v-chip>
								<v-chip class="ml-2"
									:class="proxy.$vtk.filters.dict(item.projType, 'A:green-lighten-5 text-green/B:blue-lighten-5 text-blue/C:cyan-lighten-5 text-cyan')"
									size="small" label>
									{{ proxy.$vtk.filters.dict(item.projType, "A:公共服务/B:政策服务/C:社会服务") }}
								</v-chip>
								{{ item.projName }}
							</span>
							<v-row class="pt-2 pb-0" style="color: #979797c2">
								<v-col>行政区划：{{ item.areaName }}</v-col>
							</v-row>
						</div>
					</template>
					<template v-slot:item.rateInfo="{ item }">
						<div :title="item.name" class="d-block" :style="{ color: item.rateType ? '' : '#979797c2' }">
							回访方式：{{ getRateTypeText(item.rateType) }}
						</div>
						<div :title="item.name" class="d-block" :style="{ color: item.rateTime ? '' : '#979797c2' }">
							回访时段：{{ item.rateTime }}
						</div>
					</template>
					<template v-slot:item.state="{ item }">
						<v-switch color="primary" v-model="item.state" class="mb-3 mt-3" false-value="0" true-value="1" inset
							hide-details density="compact" @update:model-value="toggleStateHandler(item)"
							:disabled="!item.id"></v-switch>
					</template>
					<template v-slot:item.actions="{ item }">
						<span @click="openManageDialog(item)" class="me-4 vtk-cursor-pointer text-success">配置</span>
						<span v-if="item.id" @click="del(item)" class="vtk-cursor-pointer text-red">删除</span>
						<span v-else class="vtk-cursor-pointer text-grey" style="cursor: not-allowed">删除</span>
					</template>
					<template v-slot:no-data>
						<vtk-empty />
					</template>
				</v-data-table>
				<vtk-page :page-data="pageData" :page-sizes="[10, 20, 50]" @page-change="handlePageChange" />
			</v-card-text>
		</v-card>
		<v-dialog v-model="editDialog.visible" persistent max-width="525">
			<v-card>
				<v-card-title>
					回访配置<v-spacer></v-spacer>
				</v-card-title>
				<v-divider />
				<v-card-text class="pb-1">
					<v-list-item class="rounded mt-4 pa-3" style="border: 1px dashed #99999952">
						<template v-slot:prepend>
							<v-avatar class="rounded blue-grey-lighten-5" size="56">
								<v-img src="@/assets/img/avatar-1.png" alt="头像" />
							</v-avatar>
						</template>
						<v-list-item-title class="text-h6 font-weight-regular mb-1">{{ entity.projName || ""
							}}</v-list-item-title>
						<v-list-item-subtitle style="line-height: unset">事项编码：{{ entity.projCode || ""
							}}</v-list-item-subtitle>
					</v-list-item>
					<v-form ref="entityRef" v-model="valid" class="mt-5">
						<vtk-select v-model="entity.rateTypeArr" placeholder="请选择回访方式" list="1:短信/2:电话" multi
							:rules="[(v) => !!v || '回访方式不能为空!']" density="compact" variant="outlined"
							clearable></vtk-select>
						<vtk-select v-model="entity.rateTime" placeholder="请选择回访时段" :list="rateTimeOptions"
							:rules="[(v) => !!v || '回访时段不能为空!']" density="compact" variant="outlined"
							clearable></vtk-select>
						<div class="mb-2" style="margin-top: -8px">
							<v-chip v-for="word in suggestionWords" :key="word.label"
								@click="addSuggestionWord(word.value)" size="small" variant="outlined"
								class="ma-1 vtk-cursor-pointer">
								{{ word.label }}
							</v-chip>
						</div>
						<v-textarea v-model="entity.rateText" :rules="[(v) => !!v || '回访话术不能为空!']" placeholder="请填写回访话术"
							variant="outlined" rows="4" ref="rateTextArea"></v-textarea>
						<v-textarea v-model="entity.rateNote" :rules="[(v) => !!v || '配置说明不能为空!']" placeholder="请输入配置说明"
							variant="outlined" rows="2"></v-textarea>
					</v-form>
					<p class="text-body-2 mt-3"  style="color: #979797c2">
						说明：<br />
						1. 回访方式：听力残疾默认以短信方式；都选时则先短信三天后再电话；<br />
						2. 回访话术：模板中添加的关键字将根据办件内容替换后发送；<br />
						3. 回访时段：避免干扰到残疾人正常作息，实现更加人性化的服务。
					</p>
				</v-card-text>
				<v-divider></v-divider>
				<v-card-actions class="justify-end">
					<v-spacer />
					<v-btn @click="closeEditDialog" variant="text"> 取消 </v-btn>
					<v-btn @click="saveConfigHandler" variant="text" color="primary"> 确定 </v-btn>
				</v-card-actions>
			</v-card>
		</v-dialog>
	</div>
</template>

<style lang="scss" scoped></style>
