<template>
	<div>
		<!-- 顶部 start -->
		<div class="top">
			<el-page-header @back="goBack"> </el-page-header>

			<div class="step">
				<div class="step_item" @click="stepChange(0)">
					<text class="step_num">1</text>
					<text class="step_title">基本信息编辑</text>
					<div class="line" :style="{ backgroundColor: tabIndex == 0 ? '#1890FF' : '#fff' }"></div>
				</div>
				<el-icon size="24" color="rgba(0,0,0,0.25)"><ArrowRight /></el-icon>
				<div class="step_item" @click="stepChange(1)">
					<text class="step_num">2</text>
					<text class="step_title">正文编辑</text>
					<div class="line" :style="{ backgroundColor: tabIndex == 1 ? '#1890FF' : '#fff' }"></div>
				</div>
				<el-icon size="24" color="rgba(0,0,0,0.25)"><ArrowRight /></el-icon>
				<div class="step_item" @click="stepChange(2)">
					<text class="step_num">3</text>
					<text class="step_title">标签与栏目配置</text>
					<div class="line" :style="{ backgroundColor: tabIndex == 2 ? '#1890FF' : '#fff' }"></div>
				</div>
			</div>

			<!-- <el-steps class="mb-4" :space="200" :active="1" simple style="width: 800px">
				<el-step title="基本信息编辑">
					<template #icon>
						<div class="step_num">1</div>
					</template>
				</el-step>
				<el-step title="正文编辑" :icon="UploadFilled" />
				<el-step title="标签与栏目配置" :icon="Picture" />
			</el-steps> -->
			<!--#e4e7ed-->
			<div>
				<el-button
					type="primary"
					@click="submit(0)"
					:style="{ backgroundColor: canSubmit ? '' : 'rgb(159.5,206.5,255)', border: canSubmit ? '' : '1px solid rgb(159.5,206.5,255)' }"
					>发布</el-button
				>
				<el-button @click="submit(1)" :style="{ backgroundColor: canSubmit ? '' : '#e4e7ed', border: canSubmit ? '' : '1px solid #e4e7ed' }"
					>保存</el-button
				>
			</div>
		</div>
		<!-- 顶部 end -->
		<el-form class="form" :rules="rules" ref="ruleFormRef" :model="form" label-width="95">
			<div class="center">
				<!-- step1 start -->
				<div class="step_bk" v-show="tabIndex == 0">
					<div class="page_title">标题与封面</div>

					<el-form-item label="文章标题" style="margin-top: 20px" prop="title">
						<div style="display: flex; width: 800px">
							<el-input placeholder="输入文章标题" v-model="form.title" :max="titleTextMax" :maxlength="titleTextMax" @input="inputChange"></el-input>
							<text style="margin-left: 10px; color: #b3b3b3"> {{ titleTextNum }}/{{ titleTextMax }}</text>
						</div>
					</el-form-item>

					<el-form-item label="文章封面">
						<div class="r_upload">
							<uploadImage v-model:file-list="pictureTemp" :limit="1" :fileSize="20 * 1024"> </uploadImage>
							<text>请上传jpg，png格式的图片，大小不超过20M</text>
						</div>
					</el-form-item>

					<el-form-item prop="summary">
						<div class="page_title">输入摘要</div>
						<el-input
							v-model="form.summary"
							show-word-limit
							maxlength="300"
							style="margin-top: 10px"
							:rows="10"
							type="textarea"
							placeholder="请输入摘要内容"
							max="300"
						/>
					</el-form-item>
				</div>
				<!-- step1 end -->

				<!-- step2 start -->
				<div class="step_bk" v-show="tabIndex == 1">
					<editorBox :ueditorData="form.content" @changeMsg="changeMsg"></editorBox>
				</div>
				<!-- step2 end -->

				<!-- step3 start -->
				<div v-show="tabIndex == 2">
					<div class="step_bk">
						<div class="page_title">标签配置</div>

						<!-- <el-form-item label="付费类型：" style="margin-top: 20px">
							<el-radio-group v-model="form.type">
								<el-radio :value="0" size="large">免费</el-radio>
								<el-radio :value="1" size="large">VIP</el-radio>
							</el-radio-group>
						</el-form-item> -->

						<el-form-item label="来源标签：" prop="tagSourceSelect" style="margin-top: 20px">
							<el-select v-model="form.tagSourceSelect" filterable placeholder="选择所属来源" size="large" style="width: 240px">
								<el-option v-for="item in tagSourceList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>

						<el-form-item label="频道标签：" prop="tagDiySelect">
							<el-select v-model="form.tagDiySelect" filterable multiple placeholder="选择所属标签" size="large" style="width: 240px">
								<el-option v-for="item in tagDiyList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</div>
					<div class="step_bk">
						<div style="display: flex; justify-content: space-between">
							<div class="page_title">栏目配置</div>
							<!-- <el-button @click="addColumnNum">添加栏目</el-button> -->
						</div>

						<div style="margin-top: 20px">
							<text class="page_title">VIP栏目</text>
							<el-form-item label="选择栏目：" style="margin-top: 15px" prop="columnsVip">
								<el-select v-model="form.columnsVip" filterable placeholder="选择所属栏目" size="large" style="width: 240px" @change="vipChange">
									<el-option v-for="item in columnListVIp" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>

							<el-form-item label="" style="margin-top: 15px" v-if="isShowVipChild">
								<el-select v-model="form.columnsVipChild" filterable placeholder="选择所属栏目" size="large" style="width: 240px">
									<el-option v-for="item in vipChildList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>

							<el-form-item label="展示方式：">
								<el-select v-model="form.showTypeVip" placeholder="无特殊样式" size="large" style="width: 240px">
									<el-option label="无特殊样式" :value="null" />
									<el-option label="封面banner" :value="0" />
									<el-option label="标题banner" :value="1" />
								</el-select>
							</el-form-item>
						</div>

						<div style="margin-top: 20px">
							<text class="page_title">首页-早知道</text>
							<el-form-item label="是否展示：" style="margin-top: 20px">
								<el-radio-group v-model="form.column.earlyKnow.show">
									<el-radio :value="true" size="large">是</el-radio>
									<el-radio :value="false" size="large">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</div>

						<div style="margin-top: 20px">
							<text class="page_title">首页-天下事</text>
							<el-form-item label="是否展示：" style="margin-top: 20px">
								<el-radio-group v-model="form.column.showEverything">
									<el-radio :value="true" size="large">是</el-radio>
									<el-radio :value="false" size="large">否</el-radio>
								</el-radio-group>
							</el-form-item>

							<el-form-item label="展示方式：">
								<el-select v-model="form.column.everything.type" placeholder="无特殊样式" size="large" style="width: 240px">
									<el-option v-for="item in showTypeList" :key="item.value" :label="item.name" :value="item.value" />
								</el-select>
							</el-form-item>
						</div>

						<!-- <div v-for="(item, index) in columnNumList" :key="index" style="margin-top: 20px">
							<div class="columns_title">
								<text class="page_title">栏目{{ index + 1 }}</text>
								<div class="column_del" v-if="index > 0" @click="delColunmNum(index)">删除此栏目</div>
							</div>

							<el-form-item label="选择栏目：" style="margin-top: 15px" v-if="index == 0">
								<el-select v-model="item.columns" placeholder="选择所属栏目" size="large" style="width: 240px">
									<el-option v-for="item in columnList1" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>

							<el-form-item label="选择栏目：" style="margin-top: 15px" v-if="index == 1">
								<el-select v-model="item.columns" placeholder="选择所属栏目" size="large" style="width: 240px">
									<el-option v-for="item in columnList2" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>

							<el-form-item label="展示方式：">
								<el-select v-model="form.showType" placeholder="选择展示方式" size="large" style="width: 240px">
									<el-option v-for="item in showTypeList" :key="item.name" :label="item.name" :value="item.name" />
								</el-select>
							</el-form-item>
						</div> -->
					</div>
				</div>
				<!-- step3 end -->
			</div>
		</el-form>
	</div>
</template>

<script setup lang="ts" name="loginIndex">
import { onMounted, reactive, ref, watch } from 'vue';
import { NextLoading } from '/@/utils/loading';
import { ElMessage, ElStep } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import editorBox from '/@/components/editorBox.vue';
import uploadImage from '/@/components/upload/image.vue';
import { getTagSource, getTagDiy, getColumn, doNewsSave, doNewsCreatePublish, getNewsDetail, getColumnVIP } from '/@/api/api';

const route = useRoute();
const router = useRouter();

const rules = reactive<FormRules<RuleForm>>({
	title: [{ required: true, message: '请填写文章标题', trigger: 'blur' }],
	tagSourceSelect: [{ required: true, message: '请选择来源标签', trigger: 'blur' }],
	columnsVip: [{ required: true, message: '请选择VIP栏目', trigger: 'blur' }],
	// tagDiySelect: [{ required: true, message: '请选择标签类型', trigger: 'blur' }],
});
const ruleFormRef = ref();
const form = ref({
	type: 0,
	column: {
		earlyKnow: {
			show: true,
		},
		showEverything: true,
		everything: {
			type: null,
		},
	},

	showEverything: true,
});
/********************step1 start *************************/
// 文章标题已经输入的字数
const titleTextNum = ref(0);
// 文章标题最大字数限制
const titleTextMax = ref(50);

function inputChange(text) {
	titleTextNum.value = text.length;
}
/********************step1 end *************************/

/********************step2 start *************************/
function changeMsg(value) {
	form.value.content = value.html;
	form.value.contentText = value.text;
}
/********************step2 end *************************/

/********************step3 start *************************/
// 用户选择的栏目列表
// 栏目选择框数组
// const columnNumList = ref([{}, {}]);
// function addColumnNum() {
// 	columnNumList.value.push({});
// }
// // 删除新添加的栏目
// function delColunmNum(index: number) {
// 	columnNumList.value.splice(index, 1);
// }

// 栏目列表（接口获取的待选择列表）
// const columnList1 = ref([]);
// const columnList2 = ref([]);
const columnListVIp = ref([]);

// 获取VIP栏目
async function getColumnVIPFn() {
	let { code, data } = await getColumnVIP({
		page: 1,
		size: 100000,
	});
	if (code == 200) {
		columnListVIp.value = data;
	}
}

// // 获取栏目
// async function getColumnFn(type) {
// 	let { code, data } = await getColumn({
// 		page: 1,
// 		size: 100000,
// 		type,
// 	});
// 	if (code == 200) {
// 		if (type == 0) {
// 			columnList1.value = data;
// 		} else {
// 			columnList2.value = data;
// 		}
// 	}
// }
// 用户选择的来源标签（单选）
// const tagSourceSelect = ref();
// 用户选择的标签类型（多选）
// const tagDiySelect = ref([]);

// 自定义标签列表
const tagDiyList = ref([]);
async function getTagDiyFn() {
	let { code, data } = await getTagDiy({
		page: 1,
		size: 100000,
		parent: 6,
	});
	if (code == 200) {
		tagDiyList.value = data;
	}
}

// 来源标签列表
const tagSourceList = ref([]);
async function getTagSourceFn() {
	let { code, data } = await getTagSource({
		page: 1,
		size: 100000,
	});
	if (code == 200) {
		tagSourceList.value = data;
	}
}
//展示方式列表
const showTypeList = ref([
	{
		name: '无特殊样式',
		value: null,
	},
	{
		name: '封面banner',
		value: 0,
	},
	{
		name: '标题banner',
		value: 1,
	},
]);
/********************step3 end *************************/

const canSubmit = ref(false);
watch(
	() => form.value,
	(val) => {
		// console.log('🚀 ~ val:', val);
		if (form.value.title && form.value.tagSourceSelect && form.value.columnsVip) {
			canSubmit.value = true;
		}
	},
	{
		immediate: true,
		deep: true,
	}
);

const pictureTemp = ref([]);
/**
 * 提交创建
 * @param type  0：发布 1：保存
 */
async function submit(type) {
	form.value.picture = pictureTemp.value[0]?.url;

	if (!form.value.title) {
		ElMessage.error('请输入标题');
		tabIndex.value = 0;
		await ruleFormRef.value.validate();
		return;
	}

	if (!form.value.tagSourceSelect) {
		ElMessage.error('请选择来源标签');
		tabIndex.value = 2;
		await ruleFormRef.value.validate();
		return;
	}

	if (!form.value.columnsVip) {
		ElMessage.error('请选择VIP栏目');
		tabIndex.value = 2;
		await ruleFormRef.value.validate();
		return;
	}

	if (form.value.column.earlyKnow.show && !form.value.summary) {
		ElMessage.success('选择展示在早知道栏目需要填写摘要');
		return;
	}

	console.log('🚀 ~ submit ~ form.value:', form.value);
	var tags = [];
	if (form.value.tagSourceSelect) {
		tagSourceList.value.forEach((item, index) => {
			if (item.id == form.value.tagSourceSelect) {
				tags.push(item);
			}
		});
	}
	if (form.value.tagDiySelect) {
		form.value.tagDiySelect.forEach((item, index) => {
			tagDiyList.value.forEach((childItem, childIndex) => {
				if (item == childItem.id) {
					tags.push(childItem);
				}
			});
		});
	}
	let vip = {
		id: form.value.columnsVipChild ? form.value.columnsVipChild : form.value.columnsVip,
		type: form.value.showTypeVip,
	};

	// if (form.value.showTypeVip == -1) {
	// 	form.value.showTypeVip = null;
	// }

	// if (form.value.column?.everything?.type == -1) {
	// 	form.value.column.everything.type = null;
	// }

	let par = {
		...form.value,
		column: {
			vip: vip, // vip栏目
			earlyKnow: {
				show: form.value.column.earlyKnow.show,
				type: form.value.column.earlyKnow.type,
			},
			showEverything: form.value.column.showEverything,
			everything: {
				type: form.value.column.everything.type,
			},
		},

		tag: {
			source: form.value.tagSourceSelect,
			// field: form.value.tagDiySelect && form.value.tagDiySelect.length > 0 ? form.value.tagDiySelect[0] : null,
			fieldArr: form.value.tagDiySelect,
		},
	};
	if (type == 0) {
		// 发布
		let { code, data } = await doNewsCreatePublish(par);
		if (code == 200) {
			ElMessage.success('操作成功');
			goBack();
		}
	} else if (type == 1) {
		// 保存
		let { code, data } = await doNewsSave(par);
		if (code == 200) {
			ElMessage.success('操作成功');
			goBack();
		}
	}
}

const tabIndex = ref(0);

function stepChange(index: number) {
	tabIndex.value = index;
}

function goBack() {
	router.back();
}

const infoData = ref({});
// 获取新闻详情
async function getInfo() {
	console.log('🚀 ~ getInfo ~ route:', route);

	let { code, data } = await getNewsDetail({ id: route.query.id });
	if (code == 200) {
		infoData.value = data;
		form.value = data;

		// 如果返回的栏目为空，填上默认字段
		if (!form.value.column) {
			form.value.column = {
				vip: null,
				everything: null,
			};
		}
		// 如果返回的栏目为空（早知道），填上默认字段
		if (!form.value.column?.earlyKnow) {
			form.value.column.earlyKnow = {
				show: false,
			};
		}
		form.value.columnsVip = data.column?.vip?.id;
		form.value.tagSourceSelect = data.tag.source?.id;
		// 付费类型，目前这个字段灭用
		form.value.type = 0;
		// 初始化上传的封面
		if (form.value.picture) {
			pictureTemp.value = [
				{
					url: form.value.picture,
				},
			];
		}
		// 初始化标题字数
		titleTextNum.value = form.value.title.length;
		// VIP展示方式
		form.value.showTypeVip = data.column.vip?.type;
		// 初始化频道标签（多选）
		form.value.tagDiySelect = [];
		data.tag?.fieldArr?.forEach((item) => {
			form.value.tagDiySelect.push(item.id);
		});
		// 如果频道标签有子标签
		if (data.column?.vip?.child) {
			vipChange(data.column.vip.id);
			form.value.columnsVipChild = data.column.vip.child.id;
		}
		// 初始化天下事字段
		if (!form.value.column.everything) {
			form.value.column.everything = {
				type: null,
			};
		}

		// if (form.value.showTypeVip == null) {
		// 	form.value.showTypeVip = -1;
		// }

		// if (form.value.column?.everything?.type == null) {
		// 	form.value.column.everything.type = -1;
		// }
	}
}

const isShowVipChild = ref(false);
const vipChildList = ref([]);
function vipChange(val) {
	let selectItem = {};
	columnListVIp.value.forEach((item, index) => {
		if (item.id == val) {
			selectItem = item;
		}
	});

	// 如果有二级栏目
	if (selectItem.children && selectItem.children.length > 0) {
		isShowVipChild.value = true;
		vipChildList.value = selectItem.children;

		form.value.columnsVipChild = vipChildList.value[0].id;
	} else {
		isShowVipChild.value = false;
		form.value.columnsVipChild = null;
	}
}

// 页面加载时
onMounted(async () => {
	console.log('🚀 ~ file: index.vue:13 ~ onMounted ~ onMounted:');
	NextLoading.done();
	await getColumnVIPFn();

	//如果是编辑进来
	if (route.query.type == 1) {
		getInfo();
	}
	// 自定义标签列表
	getTagDiyFn();
	// 来源标签列表
	getTagSourceFn();
	// 栏目列表
	// getColumnFn();
});
</script>

<style scoped lang="scss">
.top {
	width: 100%;
	height: 80px;
	background-color: white;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-left: 20px;
	padding-right: 20px;

	:deep(.el-steps--simple) {
		background-color: transparent;
	}
}

.step {
	display: flex;
	align-items: center;
	// gap: 50px;
	height: 100%;

	.step_item {
		display: flex;
		align-items: center;
		width: 227px;
		height: 100%;
		justify-content: center;
		position: relative;
		cursor: pointer;
	}

	.step_num {
		color: #fff;
		background-color: #1890ff;
		width: 24px;
		height: 24px;
		display: flex;
		text-align: center;
		justify-content: center;
		align-items: center;
		border-radius: 100px;
		margin-left: -10px;
	}

	.step_title {
		font-size: 14px;
		margin-left: 10px;
	}

	.line {
		position: absolute;
		bottom: 0;
		width: 100%;
		height: 3px;
	}
}

.step_bk {
	margin: 20px;
	padding: 20px;
	background-color: white;
	border-radius: 10px;
}

.form {
	margin-top: 30px;
}

.r_upload {
	display: flex;
	align-items: center;

	text {
		margin-left: 10px;
		color: #b3b3b3;
		font-size: 12px;
	}
}

.columns_title {
	display: flex;
}
.column_del {
	margin-left: 40px;
	color: #ff4d4f;
	border: 1px solid #ff4d4f;
	padding: 3px 5px;
	border-radius: 3px;
	cursor: pointer;
}
</style>
