<template>
	<el-dialog
		class="api-edit"
		v-model="showDialog"
		:title="`${formData.sourceId ? t('message.dateCenter.actions.edit') : t('message.dateCenter.actions.createSource')}`"
		width="800px"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
	>
		<el-form class="inline-form" ref="formRef" :model="formData" :rules="ruleForm" label-width="140px">
			<el-form-item :label="t('message.dateCenter.labels.sourceKey')" prop="key">
				<el-input v-model="formData.key" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.sourceKey')}`" :disabled="formData.sourceId" />
			</el-form-item>
			<el-form-item :label="t('message.dateCenter.labels.sourceName')" prop="name">
				<el-input v-model="formData.name" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.sourceName')}`" />
			</el-form-item>
			<el-form-item :label="t('message.dateCenter.labels.sourceDesc')" prop="desc">
				<el-input v-model="formData.desc" type="textarea" :placeholder="t('message.dateCenter.placeholders.input')"></el-input>
			</el-form-item>

			<el-form-item :label="t('message.dateCenter.labels.sourceFrom')" prop="from" v-if="!formData.sourceId">
				<el-radio-group v-model="formData.from">
					<el-radio :label="1">{{ t('message.dateCenter.options.api') }}</el-radio>
					<el-radio :label="4">{{ t('message.dateCenter.options.device') }}</el-radio>
					<el-radio :label="2">{{ t('message.dateCenter.options.db') }}</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-divider content-position="left">{{ t('message.dateCenter.tabs.sourceConfig') }}</el-divider>

			<div v-if="formData.from == 1">
				<el-form-item :label="t('message.dateCenter.labels.method')" prop="config.method">
					<el-select v-model="formData.config.method" :rules="ruleForm['config.method']" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.method')}`">
						<el-option v-for="item in methodData" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

				<el-form-item :label="t('message.dateCenter.labels.url')" prop="config.url">
					<el-input v-model="formData.config.url" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.url')}`" :rules="ruleForm['config.url']" />
				</el-form-item>

				<el-form-item :label="t('message.dateCenter.labels.interval')" prop="config.cronExpression">
					<div style="display: flex">
						<el-input v-model="formData.config.cronExpression" :placeholder="`${t('message.dateCenter.placeholders.input')} cron`" :rules="ruleForm['config.cronExpression']" />
						<el-button type="success" @click="showCron('config')" style="margin-left: 5px">{{ t('message.dateCenter.actions.edit') }}</el-button>
					</div>
				</el-form-item>

				<div class="box-content">
					<div>
						<div
							v-for="(item, index) in requestParams"
							:key="index"
							style="padding: 10px; border: 1px solid #eee; margin-bottom: 10px; position: relative"
						>
							<div class="conicon" style="width: 100%; text-align: right; position: absolute; right: -8px; top: -8px; color: red">
								<el-icon @click="delParams(index)">
									<CircleClose />
								</el-icon>
							</div>

							<div style="display: flex">
								<el-divider content-position="left">{{ t('message.dateCenter.tabs.reqParams') }}</el-divider>
							</div>
							<div class="content-f" v-for="(aaa, bbb) in item" :key="bbb">
								<el-select v-model="aaa.type" :placeholder="t('message.dateCenter.labels.paramType')" style="width: 320px">
									<el-option v-for="item in paramData" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
								<el-input v-model="aaa.name" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.paramTitle')}`" style="width: 320px" />
								<el-input v-model="aaa.key" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.paramKey')}`" style="width: 320px" />
								<el-input v-model="aaa.value" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.paramValue')}`" style="width: 320px" />
								<div class="conicon">
									<el-icon @click="delParamss(index, bbb)">
										<Delete />
									</el-icon>
								</div>
							</div>
							<el-button type="primary" class="addbutton" @click="addParams(index)">{{ t('message.dateCenter.actions.add') }}</el-button>
							<div style=""></div>
						</div>
					</div>
				</div>
				<el-button type="success" class="addbutton" @click="addParamss">{{ t('message.dateCenter.actions.add') }}</el-button>
			</div>
			<div v-if="formData.from == 4">
				<el-form-item :label="t('message.dateCenter.labels.sourceFrom')">
					<el-radio-group v-model="deviceOrProduct" @change=";(formData.devconfig.productKey = ''), (formData.devconfig.deviceKey = '')">
						<el-radio label="device">{{ t('message.dateCenter.options.device') }}</el-radio>
						<el-radio label="product">{{ t('message.dateCenter.labels.productKey') }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item :label="t('message.dateCenter.labels.deviceKey')" v-if="deviceOrProduct == 'device'" prop="devconfig.deviceKey">
					<el-select
						v-model="formData.devconfig.deviceKey"
						:rules="ruleForm['devconfig.deviceKey']"
						filterable
						:placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.deviceKey')}`"
						@change="formData.devconfig.productKey = ''"
						style="width: 100%"
					>
						<el-option v-for="item in sourceData" :key="item.key" :label="item.name" :value="item.key">
							<span style="float: left">{{ item.name }}</span>
							<span style="float: right; font-size: 13px">{{ item.key }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="t('message.dateCenter.labels.productKey')" v-if="deviceOrProduct == 'product'" prop="devconfig.productKey">
					<el-select
						v-model="formData.devconfig.productKey"
						:rules="ruleForm['devconfig.productKey']"
						filterable
						:placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.productKey')}`"
						@change="formData.devconfig.deviceKey = ''"
						style="width: 100%"
					>
						<el-option v-for="item in producList" :key="item.key" :label="item.name" :value="item.key">
							<span style="float: left">{{ item.name }}</span>
							<span style="float: right; font-size: 13px">{{ item.key }}</span>
						</el-option>
					</el-select>
				</el-form-item>
			</div>

			<div v-if="formData.from == 2">
				<el-form-item :label="t('message.dateCenter.labels.dbType')" prop="tabconfig.type">
					<el-radio-group v-model="formData.tabconfig.type" :rules="ruleForm['tabconfig.type']">
						<el-radio label="mysql">mysql</el-radio>
						<el-radio label="mssql">mssql</el-radio>
					</el-radio-group>
				</el-form-item>

				<div class="inline">
					<el-form-item :label="t('message.dateCenter.labels.host')" prop="tabconfig.host">
						<el-input v-model="formData.tabconfig.host" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.host')}`" :rules="ruleForm['tabconfig.host']" />
					</el-form-item>

					<el-form-item :label="t('message.dateCenter.labels.port')" prop="tabconfig.port">
						<el-input v-model="formData.tabconfig.port" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.port')}`" :rules="ruleForm['tabconfig.port']" />
					</el-form-item>
				</div>
				<div class="inline">
					<el-form-item :label="t('message.dateCenter.labels.user')" prop="tabconfig.user">
						<el-input v-model="formData.tabconfig.user" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.user')}`" :rules="ruleForm['tabconfig.user']" />
					</el-form-item>

					<el-form-item :label="t('message.dateCenter.labels.password')" prop="tabconfig.passwd">
						<el-input v-model="formData.tabconfig.passwd" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.password')}`" :rules="ruleForm['tabconfig.passwd']" />
					</el-form-item>
				</div>

				<el-form-item :label="t('message.dateCenter.labels.dbName')" prop="tabconfig.dbName">
					<el-input v-model="formData.tabconfig.dbName" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.dbName')}`" :rules="ruleForm['tabconfig.dbName']" />
				</el-form-item>

				<el-form-item :label="t('message.dateCenter.labels.expression')" prop="tabconfig.queryType">
					<el-radio-group v-model="formData.tabconfig.queryType" :rules="ruleForm['tabconfig.queryType']">
						<el-radio label="tableName">{{ t('message.dateCenter.columns.value') }}</el-radio>
						<el-radio label="sql">Sql</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="" prop="tabconfig.tableName">
					<el-input
						v-model="formData.tabconfig.tableName"
						type="textarea"
						:placeholder="formData.tabconfig.queryType == 'sql' ? `${t('message.dateCenter.placeholders.input')} sql` : `${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.tableName')}`"
					/>
				</el-form-item>

				<el-form-item :label="t('message.dateCenter.labels.pk')" prop="tabconfig.pk">
					<el-input v-model="formData.tabconfig.pk" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.pk')}`" :rules="ruleForm['tabconfig.pk']" />
				</el-form-item>

				<el-form-item :label="t('message.dateCenter.labels.num')" prop="tabconfig.num">
					<el-input v-model="formData.tabconfig.num" :placeholder="`${t('message.dateCenter.placeholders.input')} ${t('message.dateCenter.labels.num')}`" :rules="ruleForm['tabconfig.num']" />
				</el-form-item>

				<el-form-item :label="t('message.dateCenter.labels.cronExpression')" prop="tabconfig.cronExpression">
					<div style="display: flex">
						<el-input v-model="formData.tabconfig.cronExpression" :placeholder="`${t('message.dateCenter.placeholders.input')} cron`" :rules="ruleForm['tabconfig.cronExpression']" />
						<el-button type="success" @click="showCron('tabconfig')" style="margin-left: 5px">{{ t('message.dateCenter.actions.edit') }}</el-button>
					</div>
				</el-form-item>
			</div>
		</el-form>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="onTest" type="warning" v-if="sourceId > 0">{{ t('message.dateCenter.actions.search') }}</el-button>

				<el-button @click="showDialog = false">{{ t('message.dateCenter.messages.cancel') }}</el-button>
				<el-button type="primary" @click="onSubmit">{{ t('message.dateCenter.messages.confirm') }}</el-button>
			</div>
		</template>
	</el-dialog>
	<el-dialog v-model="dialogVisible" :title="'Json'" width="30%">
		<JsonViewer :value="jsonData" boxed sort theme="jv-dark" @click="onKeyclick" />

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">{{ t('message.dateCenter.messages.cancel') }}</el-button>
			</span>
		</template>
	</el-dialog>

	<el-dialog v-model="cronShow" :title="'Cron'" width="60%">
		<vue3cron @handlelisten="handlelisten" :type="crontype" @close="cronclose"></vue3cron>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import api from '/@/api/datahub'
import deviceApi from '/@/api/device'
import { ruleRequired } from '/@/utils/validator'
import 'vue3-json-viewer/dist/index.css'
import vue3cron from '/@/components/vue3cron/vue3cron.vue'

import { ElMessage } from 'element-plus'
import { Delete, CircleClose } from '@element-plus/icons-vue'

const emit = defineEmits(['typeList'])

const showDialog = ref(false)
const { t } = useI18n()
const deviceOrProduct = ref('device')
const dialogVisible = ref(false)
const cronShow = ref(false)
const formRef = ref()
const jsonData = ref()
const crontype = ref()
const sourceData = ref<Array<{ key: string; name: string }>>([])
const producList = ref<Array<{ key: string; name: string }>>([])
const sourceId = ref()
const methodData = ref([
	{
		label: 'GET',
		value: 'get',
	},
	{
		label: 'POST',
		value: 'post',
	},
])

const paramData = ref([
	{
		label: 'header',
		value: 'header',
	},
	{
		label: 'body',
		value: 'body',
	},
	{
		label: 'param',
		value: 'param',
	},
])

const requestParams = ref([
	[
		{
			type: '',
			key: '',
			name: '',
			value: '',
		},
	],
])

const delParams = (index: number) => {
	requestParams.value.splice(index, 1)
}

const delParamss = (index: number, bbb: number) => {
	requestParams.value[index].splice(bbb, 1)
}

const addParamss = () => {
	requestParams.value.push([
		{
			type: '',
			key: '',
			name: '',
			value: '',
		},
	])
}
const addParams = (index: number) => {
	requestParams.value[index].push({
		type: '',
		key: '',
		name: '',
		value: '',
	})
}
const handlelisten = (e: any) => {
	if (e.type == 'config') {
		formData.config.cronExpression = e.cron
	} else if (e.type == 'tabconfig') {
		formData.tabconfig.cronExpression = e.cron
	}
}
const showCron = (type: string) => {
	crontype.value = type
	cronShow.value = true
}
const cronclose = () => {
	cronShow.value = false
}
const onTest = () => {
	if (formData.from == 1) {
		api.common.api(sourceId.value).then((res: any) => {
			jsonData.value = JSON.parse(res.data)
			dialogVisible.value = true
		})
	} else if (formData.from == 4) {
		api.common.devapi(sourceId.value).then((res: any) => {
			jsonData.value = JSON.parse(res.data)
			dialogVisible.value = true
		})
	}
}

const baseForm = {
	sourceId: undefined,
	name: '',
	key: '',
	desc: '',
	from: 1,
	config: {
		method: '',
		url: '',
		cronExpression: '',
		requestParams: [],
	},
	devconfig: {
		deviceKey: '',
		productKey: '',
	},
	tabconfig: {
		type: 'mysql',
		host: '',
		port: '',
		user: '',
		passwd: '',
		dbName: '',
		queryType: '',
		tableName: '',
		pk: '',
		num: '',
		cronExpression: '',
	},
}
const onKeyclick = () => {}
const formData = reactive({
	...baseForm,
})

const ruleForm = computed(() => {
	return {
		key: [ruleRequired(`${t('message.dateCenter.labels.sourceKey')}${t('message.dateCenter.placeholders.input')}`)],
		name: [ruleRequired(`${t('message.dateCenter.labels.sourceName')}${t('message.dateCenter.placeholders.input')}`)],
		from: [ruleRequired(`${t('message.dateCenter.labels.sourceFrom')}${t('message.dateCenter.placeholders.input')}`)],
		'config.method': [
			{ required: true, message: `${t('message.dateCenter.labels.method')}${t('message.dateCenter.placeholders.input')}` , trigger: 'change' },
			{
				validator: (rule: any, value: string, callback: any) => {
					if (formData.from === 1 && !formData.config.method) {
						callback(new Error(`${t('message.dateCenter.labels.method')}${t('message.dateCenter.placeholders.input')}`))
					} else {
						callback()
					}
				},
				trigger: 'change',
			},
		],
		'config.url': [ruleRequired(`${t('message.dateCenter.labels.url')}${t('message.dateCenter.placeholders.input')}`)],
		'config.cronExpression': [ruleRequired(`${t('message.dateCenter.labels.interval')}${t('message.dateCenter.placeholders.input')}`)],
		'devconfig.deviceKey': [ruleRequired(`${t('message.dateCenter.labels.deviceKey')}${t('message.dateCenter.placeholders.input')}`)],
		'devconfig.productKey': [ruleRequired(`${t('message.dateCenter.labels.productKey')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.type': [ruleRequired(`${t('message.dateCenter.labels.dbType')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.host': [ruleRequired(`${t('message.dateCenter.labels.host')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.port': [ruleRequired(`${t('message.dateCenter.labels.port')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.user': [ruleRequired(`${t('message.dateCenter.labels.user')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.passwd': [ruleRequired(`${t('message.dateCenter.labels.password')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.dbName': [ruleRequired(`${t('message.dateCenter.labels.dbName')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.queryType': [ruleRequired(`${t('message.dateCenter.labels.expression')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.tableName': [ruleRequired(`${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.pk': [ruleRequired(`${t('message.dateCenter.labels.pk')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.num': [ruleRequired(`${t('message.dateCenter.labels.num')}${t('message.dateCenter.placeholders.input')}`)],
		'tabconfig.cronExpression': [ruleRequired(`${t('message.dateCenter.labels.cronExpression')}${t('message.dateCenter.placeholders.input')}`)],
	}
})
const getDevData = () => {
	api.common.getdevList({}).then((res: any) => {
		sourceData.value = res.device
	})
	deviceApi.product.getLists().then((res: any) => {
		producList.value = res.product
	})
}

const onSubmit = async () => {
	await formRef.value.validate()

	if (formData.from == 1) {
		let form = {
			sourceId: sourceId.value ? sourceId.value : '',
			key: formData.key,
			name: formData.name,
			desc: formData.desc,
			from: formData.from,
			config: {
				...formData.config,
				requestParams: requestParams.value,
			},
		}
		const theApi = sourceId.value ? api.common.edit : api.common.add
		await theApi(form)
		ElMessage.success(t('message.dateCenter.messages.opSuccess'))
		resetForm()
		showDialog.value = false
		emit('typeList')
	} else if (formData.from == 4) {
		let form = {
			sourceId: formData.sourceId ? formData.sourceId : '',
			key: formData.key,
			name: formData.name,
			desc: formData.desc,
			from: formData.from,
			config: formData.devconfig,
		}
		const theApi = formData.sourceId ? api.common.devedit : api.common.devadd
		await theApi(form)
		ElMessage.success('操作成功')
		resetForm()
		showDialog.value = false
		emit('typeList')
	} else if (formData.from == 2) {
		let form = {
			sourceId: formData.sourceId ? formData.sourceId : '',
			key: formData.key,
			name: formData.name,
			desc: formData.desc,
			from: formData.from,
			config: formData.tabconfig,
		}
		const theApi = formData.sourceId ? api.common.dbedit : api.common.dbadd
		await theApi(form)
		ElMessage.success('操作成功')
		resetForm()
		showDialog.value = false
		emit('typeList')
	}
}

const resetForm = async () => {
	Object.assign(formData, { ...baseForm })
	formRef.value && formRef.value.resetFields()
	requestParams.value = [
		[
			{
				type: '',
				key: '',
				name: '',
				value: '',
			},
		],
	]
}

const openDialog = async (row: any) => {
	resetForm()
	showDialog.value = true

	nextTick(() => {
		if (row) {
			sourceId.value = row.sourceId
			api.common.detail(row.sourceId).then((res: any) => {
				Object.assign(formData, { ...res.data })
				if (res.data.from == 1) {
					formData.config = res.data.apiConfig
					requestParams.value = res.data.apiConfig.requestParams
				} else if (res.data.from == 4) {
					deviceOrProduct.value = res.data.deviceConfig.deviceKey ? 'device' : 'product'
					formData.devconfig = res.data.deviceConfig
				} else if (res.data.from == 2) {
					formData.tabconfig = res.data.dbConfig
				}
			})
		}
		getDevData()
	})
}

defineExpose({ openDialog })
</script>
<style scoped lang="scss">
.inline {
	display: inline-flex;
}

.el-input__wrapper {
	width: 98%;
}

.box-content {
	border: 1px solid #e8e8e8;
	margin: 10px;
	padding: 10px;
}

.content-f {
	display: flex;
	margin-bottom: 10px;
}

.content-f .el-input__wrapper {
	margin-right: 5px;
}

.addbutton {
	width: 100%;
	margin-top: 10px;
	background: #fff;
	border: 1px solid #d1d1d1;
	color: #8d8b8b;
}

.conicon {
	width: 55px;
	height: 25px;

	font-size: 28px;
	line-height: 28px;
	cursor: pointer;
}

.jv-node {
	margin-left: 25px;
}
</style>
