<template>
	<el-dialog v-model="state.dialogVisible" width="50%" draggable title="新增行业" destroy-on-close append-to-body @close="close">
		<template #header>
			<el-tabs v-model="state.activeName">
				<el-tab-pane :name="item.name" v-for="item in state.tabPaneList" :key="item.name" :label="item.label"></el-tab-pane>
			</el-tabs>
		</template>
		<el-form :model="state.ruleForm" label-width="110px" ref="ruleFormRef">
			<el-row :gutter="10" v-show="state.activeName === '0'">
				<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="citizenReadPackAmount" :rules="[{ required: true, message: '请填写市民红包', trigger: 'blur' }]">
						<el-input-number v-model="state.ruleForm.citizenReadPackAmount" :min="0" :precision="2" class="w100" placeholder="请填写市民红包" />
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="网格员红包" prop="guiderReadPackAmount" :rules="[{ required: true, message: '请填写网格员红包', trigger: 'blur' }]">
						<el-input-number v-model="state.ruleForm.guiderReadPackAmount" :min="0" :precision="2" class="w100" placeholder="请填写网格员红包" />
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item
						label="阶段性回复间隔时间"
						prop="intervalTime"
						label-width="150px"
						:rules="[{ required: false, message: '请填写阶段性回复间隔时间', trigger: 'blur' }]"
					>
						<el-input type="number" v-model.number="state.ruleForm.intervalTime" placeholder="请填写阶段性回复间隔时间">
							<template #suffix> 小时 </template>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="审批部门" prop="approveOrgId" :rules="[{ required: false, message: '请选择审批部门', trigger: 'change' }]">
						<el-select v-model="state.ruleForm.approveOrgId" placeholder="请选择审批部门" class="w100" clearable @change="selectDepartment" filterable>
							<el-option v-for="item in department" :key="item.dicDataValue" :label="item.dicDataName" :value="item.dicDataValue" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item
						label="关联宣传学习"
						prop="bulletinTypePublicityId"
						:rules="[{ required: false, message: '请选择关联宣传学习', trigger: 'change' }]"
					>
						<el-select v-model="state.ruleForm.bulletinTypePublicityId" placeholder="请选择关联宣传学习" class="w100" clearable @change="selectxc" filterable>
							<el-option v-for="item in bulletinType" :key="item.dicDataValue" :label="item.dicDataName" :value="item.dicDataValue"/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item
						label="关联操作指引"
						prop="bulletinTypeGuideId"
						:rules="[{ required: false, message: '请选择关联操作指引', trigger: 'change' }]"
					>
						<el-select v-model="state.ruleForm.bulletinTypeGuideId" placeholder="请选择关联操作指引" class="w100" clearable @change="selectzy" filterable>
							<el-option v-for="item in bulletinType" :key="item.dicDataValue" :label="item.dicDataName" :value="item.dicDataValue" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="关联受理类型" prop="acceptTypeCode" :rules="[{ required: false, message: '请选择关联受理类型', trigger: 'change' }]">
						<el-select v-model="state.ruleForm.acceptTypeCode" placeholder="请选择关联受理类型" class="w100" clearable @change="selectAcceptType" filterable>
							<el-option v-for="item in acceptType" :key="item.dicDataValue" :label="item.dicDataName" :value="item.dicDataValue" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="标题追加信息" prop="titleSuffix" :rules="[{ required: false, message: '请填写标题追加信息', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.titleSuffix" 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="isEnable">
						<el-switch v-model="state.ruleForm.isEnable" inline-prompt active-text="启用" inactive-text="禁用" />
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="小程序状态" prop="isAppEnable">
						<el-switch v-model="state.ruleForm.isAppEnable" inline-prompt active-text="启用" inactive-text="禁用" />
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="排序" prop="displayOrder" :rules="[{ required: false, message: '请填写排序', trigger: 'blur' }]">
						<el-input-number v-model="state.ruleForm.displayOrder" :min="1" :precision="0" class="w100" />
					</el-form-item>
				</el-col>
				<el-col>
					<el-form-item label="页面Url" prop="pageUrl" :rules="[{ required: false, message: '请填写页面Url', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.pageUrl" placeholder="请填写页面Url" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col>
					<el-form-item label="关怀页面Ur" prop="pageCareUrl" :rules="[{ false: true, message: '请填写关怀页面Ur', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.pageCareUrl" placeholder="请填写关怀页面Ur" 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="txtHelpRemarks" :rules="[{ required: false, message: '请填写帮助引导用语', trigger: 'blur' }]">
						<el-input
							type="textarea"
							:autosize="{ minRows: 6, maxRows: 10 }"
							v-model="state.ruleForm.txtHelpRemarks"
							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="txtRemarks" :rules="[{ required: false, message: '请填写宫格说明文本', trigger: 'blur' }]">
						<el-input
							type="textarea"
							:autosize="{ minRows: 6, maxRows: 10 }"
							v-model="state.ruleForm.txtRemarks"
							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="txtCareRemarks" :rules="[{ required: false, message: '请填写关怀说明', trigger: 'blur' }]">
						<el-input
							type="textarea"
							:autosize="{ minRows: 6, maxRows: 10 }"
							v-model="state.ruleForm.txtCareRemarks"
							placeholder="请填写关怀说明"
							clearable
						></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row v-show="state.activeName === '1'">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="背景图片">
						<el-upload
							class="avatar-uploader"
							:action="action"
							:show-file-list="false"
							:on-success="updateSuccessBg"
							ref="uploadListRefBg"
							name="fileData"
							:on-error="onUploadError"
						>
							<img v-if="bgUrl" :src="bgUrl" class="avatar" alt="" />
							<SvgIcon v-else class="avatar-uploader-icon" name="ele-Plus" size="28px" />
						</el-upload>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="banner设置">
						<el-upload
							class="avatar-uploader"
							:action="action"
							:show-file-list="false"
							:on-success="updateSuccessBanner"
							ref="uploadListRefBanner"
							name="fileData"
							:on-error="onUploadError"
						>
							<img v-if="bannerUrl" :src="bannerUrl" class="avatar" alt="" />
							<SvgIcon v-else class="avatar-uploader-icon" name="ele-Plus" size="28px" />
						</el-upload>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="宫格图">
						<el-upload
							class="avatar-uploader"
							:action="action"
							:show-file-list="false"
							:on-success="updateSuccessCell"
							ref="uploadListRefCell"
							name="fileData"
							:on-error="onUploadError"
						>
							<img v-if="cellImgUrl" :src="cellImgUrl" class="avatar" alt="" />
							<SvgIcon v-else class="avatar-uploader-icon" name="ele-Plus" size="28px" />
						</el-upload>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="关怀宫格图">
						<el-upload
							class="avatar-uploader"
							:action="action"
							:show-file-list="false"
							:on-success="updateSuccessCareCell"
							ref="uploadListRefCareCell"
							name="fileData"
							:on-error="onUploadError"
						>
							<img v-if="careCellImgUrl" :src="careCellImgUrl" class="avatar" alt="" />
							<SvgIcon v-else class="avatar-uploader-icon" name="ele-Plus" size="28px" />
						</el-upload>
					</el-form-item>
				</el-col>
				<el-col>
					<el-form-item label="附件">
						<annex-list classify="行业管理上传" v-model="state.ruleForm.files" v-model:format="filesFormat" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row v-show="state.activeName === '2'"> </el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, FormInstance, UploadFile, UploadFiles } from 'element-plus';
import { throttle } from '@/utils/tools';
import { addIndustry, baseIndustry } from '@/api/snapshot/config';

const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue')); // 附件列表

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		name: null, // 行业名称
		citizenReadPackAmount: null, // 市民红包
		guiderReadPackAmount: null, // 网格员红包
		intervalTime: 0, // 阶段性回复间隔时间
		approveOrgId: null, // 审批机构id
		approveOrgName: null,
		bulletinTypePublicityId: null, // 关联宣传学习ID
		bulletinTypePublicityName: null, // 关联宣传学习名称
		bulletinTypeGuideId: null, // 关联操作指引ID
		bulletinTypeGuideName: null, // 关联操作指引名称
		acceptTypeCode: null, // 关联受理类型ID
		acceptType: null, // 关联受理类型名称
		titleSuffix: null, // 标题追加信息
		isEnable: true, // 系统状态
		isAppEnable:true, // 小程序状态
		displayOrder: 1, // 排序
		pageUrl: null, // 页面Url
		pageCareUrl: null, //Care页面Url
		txtHelpRemarks: null, // 帮助引导用语
		txtRemarks: null, // 宫格说明文本
		txtCareRemarks: null, //Care说明
		backgroundImgUrl: null, // 背景图片
		bannerImgUrl: null, // banner图片
		cellImgUrl: null, // 宫格图片
		careCellImgUrl: null, //Care宫格图片
	},
	activeName: '0',
	tabPaneList: [
		{
			label: '参数配置',
			name: '0',
		},
		{
			label: '图片配置',
			name: '1',
		},
	/*	{
			label: '操作权限',
			name: '3',
		},*/
	],
});

let loading = ref<boolean>(false); // 加载状态
// 打开弹窗
const ruleFormRef = ref<RefType>();
const openDialog = async () => {
	try {
		state.dialogVisible = true;
	} catch (error) {
		console.log(error);
	}
};
// 审批部门
const selectDepartment = (val: any)=>{
	if(val){
		const item = department.value.find((item:any)=>item.dicDataValue === val);
		state.ruleForm.approveOrgName = item?.dicDataName;
	}else{
		state.ruleForm.approveOrgName = null;
	}
}
// 关联宣传学习
const selectxc = (val:any)=>{
	if(val){
		const item = bulletinType.value.find((item:any)=>item.dicDataValue === val);
		state.ruleForm.bulletinTypePublicityName = item?.dicDataName;
	}else{
		state.ruleForm.bulletinTypePublicityName = null;
	}
}
// 关联操作指引
const selectzy = (val:any)=>{
	if(val){
		const item = bulletinType.value.find((item:any)=>item.dicDataValue === val);
		state.ruleForm.bulletinTypeGuideName = item?.dicDataName;
	}else{
		state.ruleForm.bulletinTypeGuideName = null;
	}
}
// 受理类型
const selectAcceptType = (val:any)=>{
	if(val){
		const item = acceptType.value.find((item:any)=>item.dicDataValue === val);
		state.ruleForm.acceptType = item?.dicDataName;
	}else{
		state.ruleForm.acceptType = null;
	}
}
// 上传地址
const action = computed(() => {
	return import.meta.env.VITE_API_UPLOAD_URL + '/file/upload?source=hotline';
});
const bgUrl = ref(''); // 背景图
const uploadListRefBg = ref<RefType>(); // 上传组件ref
// 上传成功背景图
const updateSuccessBg = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
	if (response.result.path) {
		bgUrl.value = import.meta.env.VITE_API_UPLOAD_URL + response.result.path;
		// bgUrl.value = URL.createObjectURL(uploadFile.raw!);
		state.ruleForm.backgroundImgUrl = response.result.path;
	} else {
		uploadListRefBg.value.handleRemove(uploadFile);
		ElMessage.error('上传失败');
	}
};
// banner图
const bannerUrl = ref('');
const uploadListRefBanner = ref<RefType>();
const updateSuccessBanner = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
	if (response.result.path) {
		bannerUrl.value = import.meta.env.VITE_API_UPLOAD_URL + response.result.path;
		// bannerUrl.value = URL.createObjectURL(uploadFile.raw!);
		state.ruleForm.bannerImgUrl = response.result.path;
	} else {
		uploadListRefBanner.value.handleRemove(uploadFile);
		ElMessage.error('上传失败');
	}
};
// 宫格图
const cellImgUrl = ref('');
const uploadListRefCell = ref<RefType>();
const updateSuccessCell = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
	if (response.result.path) {
		cellImgUrl.value = import.meta.env.VITE_API_UPLOAD_URL + response.result.path;
		// cellImgUrl.value = URL.createObjectURL(uploadFile.raw!);
		state.ruleForm.cellImgUrl = response.result.path;
	} else {
		uploadListRefCell.value.handleRemove(uploadFile);
		ElMessage.error('上传失败');
	}
};
// 关怀宫格图
const careCellImgUrl = ref('');
const uploadListRefCareCell = ref<RefType>();
const updateSuccessCareCell = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
	if (response.result.path) {
		careCellImgUrl.value = import.meta.env.VITE_API_UPLOAD_URL + response.result.path;
		// careCellImgUrl.value = URL.createObjectURL(uploadFile.raw!);
		state.ruleForm.careCellImgUrl = response.result.path;
	} else {
		uploadListRefCareCell.value.handleRemove(uploadFile);
		ElMessage.error('上传失败');
	}
};
// 上传失败
const onUploadError = (error: Error) => {
	try {
		const errMessage = JSON.parse(error.message)?.message ?? '上传失败';
		ElMessage.error(errMessage);
	} catch (e) {
		ElMessage.error('上传失败');
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	state.ruleForm.backgroundImgUrl = null;
	state.ruleForm.bannerImgUrl = null;
	state.ruleForm.cellImgUrl = null;
	state.ruleForm.careCellImgUrl = null;
	bgUrl.value = '';
	bannerUrl.value = '';
	cellImgUrl.value = '';
	careCellImgUrl.value = '';
	state.ruleForm.files = [];
	state.activeName = '0';
};

const filesFormat = ref<EmptyArrayType>([]); // 附件列表格式化
// 新增
const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		loading.value = true;
		const requestData = {
			...state.ruleForm,
			files: filesFormat.value,
		};
		addIndustry(requestData)
			.then(() => {
				ElMessage({
					message: '操作成功',
					type: 'success',
				});
				emit('updateList');
			})
			.catch(() => {})
			.finally(() => {
				loading.value = false;
				closeDialog();
			});
	});
}, 300);
// 获取基础数据
const acceptType = ref<EmptyArrayType>([]); // 受理类型
const bulletinType = ref<EmptyArrayType>([]); // 公告类型
const department = ref<EmptyArrayType>([]); // 审批部门
const getBaseData = async () => {
	try {
		const { result } = await baseIndustry();
		acceptType.value = result.acceptType;
		bulletinType.value = result.bulletinType;
		department.value = result.department;
	} catch (e) {
		console.log(e);
	}
};
onMounted(() => {
	getBaseData();
});
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style scoped lang="scss">
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
