<template>
	<div class="ds-list">
		<template v-if="formConfig.dataSources && formConfig.dataSources.length">
			<el-descriptions :column="1" size="small" border="" v-for="(dataSource, index) in formConfig.dataSources" :key="index">
				<template slot="title">
					<span title="">{{ dataSource.uniqueName }}</span>
				</template>
				<template slot="extra">
					<el-button type="primary" icon="el-icon-edit" plain="" circle="" size="mini" @click="editDataSource(index)"></el-button>
					<el-button type="danger" icon="el-icon-delete" plian="" circle="" size="mini" @click="deleteDataSource(index)"></el-button>
				</template>
				<el-descriptions-item>
					<template slot="title">
						<i title="a" class="el-icon-s-platform"></i>
					</template>
					{{ dataSource.requestURL }}
				</el-descriptions-item>
			</el-descriptions>
		</template>
		<template v-else>
			<el-empty description="暂无数据源"></el-empty>
		</template>
		<div class="ds-button-wrapper"><el-button type="primary" icon="el-icon-plus" plain="" round="" @click="addDataSource">新增数据源</el-button></div>
		<el-drawer
			direction="rtl"
			:modal="!0"
			size="820"
			:show-close="!1"
			:visible.sync="showDataSourceDialogFlag"
			:destroy-on-close="!0"
			:append-to-body="!0"
			:wrapperClosable="!1"
			:close-on-press-escape="!1"
			custom-class="ds-setting-drawer header-small-mb"
		>
			<template slot="title">
				<span>数据源设置</span>
				<div style="float: right;">
					<el-button type="primary" @click="testDataSource" class="button-sty">测试数据源</el-button>
					<el-button type="primary" @click="saveDataSource" class="button-sty" icon="el-icon-check">保存数据源</el-button>
					<el-button type="primary" plain="" @click="showDataSourceDialogFlag = !1" class="button-sty" icon="el-icon-close">取消</el-button>
				</div>
				<!---->
			</template>
			<template slot="default">
				<el-form ref="dsForm" class="ds-form" :model="dsModel" :rules="formRules" label-width="140px" label-position="right">
					<el-form-item label="唯一名称" prop="uniqueName"><el-input v-model="dsModel.uniqueName"></el-input></el-form-item>
					<el-row style="width: 100%;">
						<el-col :span="20">
							<el-form-item label="请求地址" prop="requestURL"><el-input v-model="dsModel.requestURL"></el-input></el-form-item>
						</el-col>
						<el-col :span="4">
							<el-form-item class="no-left-margin" label-width="0" prop="requestaccessType">
								<el-select v-model="dsModel.requestaccessType" placeholder="请求URL类型">
									<el-option label="固定字符串" :value="'String'"></el-option>
									<!-- <el-option label="变量或表达式" :value="'Variable'"></el-option> -->
									<el-option label="SQL查询" :value="'SQL'"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="描述信息" prop="description"><el-input type="textarea" :row="2" v-model="dsModel.description"></el-input></el-form-item>
					<el-form-item label="请求方法" prop="requestMethod" style="margin-top:6px">
						<el-radio-group v-model="dsModel.requestMethod" size="small">
							<el-radio-button label="get"></el-radio-button>
							<el-radio-button label="post"></el-radio-button>
							<el-radio-button label="put"></el-radio-button>
							<el-radio-button label="delete"></el-radio-button>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="请求头（headers）">
						<el-row v-for="(t, n) in dsModel.headers" :key="n" class="rh-row" :gutter="8">
							<el-col :span="7">
								<el-form-item :prop="'headers.' + n +'.name'" :rules="nameRules" label-width="0">
									<el-input placeholder="名称" v-model="t.name"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="5">
								<el-form-item :prop="'headers.' + n +'.type'" label-width="0">
									<el-select placeholder="类型" v-model="t.type">
										<el-option label="字符串类型" :value="'String'"></el-option>
										<el-option label="数值类型" :value="'Number'"></el-option>
										<el-option label="布尔类型" :value="'Boolean'"></el-option>
										<el-option label="变量或表达式" :value="'Variable'"></el-option>
										<el-option label="表单数据" :value="'FormData'"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item :prop="'headers.' + n +'.value'" :rules="valueRules" label-width="0">
									<el-input placeholder="值" v-model="t.value"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="3"><el-button icon="el-icon-delete" plain="" circle="" @click="deleteRequestHeader(n)" size="mini"></el-button></el-col>
						</el-row>
						<el-row :span="6"><el-button type="text" icon="el-icon-plus" @click="addRequestHeader" class="button-sty">新增请求头</el-button></el-row>
					</el-form-item>
					<el-form-item label="参数（params）">
						<el-row v-for="(t, n) in dsModel.params" :key="n" class="rh-row" :gutter="8">
							<el-col :span="7">
								<el-form-item :prop="'params.' + n +'.name'" :rules="nameRules" label-width="0">
									<el-input placeholder="名称" v-model="t.name"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="5">
								<el-form-item :prop="'params.' + n +'.type'" label-width="0">
									<el-select placeholder="类型" v-model="t.type">
										<el-option label="字符串类型" :value="'String'"></el-option>
										<el-option label="数值类型" :value="'Number'"></el-option>
										<el-option label="布尔类型" :value="'Boolean'"></el-option>
										<el-option label="变量或表达式" :value="'Variable'"></el-option>
                    <el-option label="表单数据" :value="'FormData'"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item :prop="'params.' + n +'.value'" :rules="valueRules" label-width="0">
									<el-input placeholder="值" v-model="t.value"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="3"><el-button icon="el-icon-delete" plain="" circle="" @click="deleteRequestParam(n)"  size="mini"></el-button></el-col>
						</el-row>
						<el-row :span="6"><el-button type="text" icon="el-icon-plus" @click="addRequestParam" class="button-sty">新增请求参数</el-button></el-row>
					</el-form-item>
					<el-form-item label="发送数据（data）">
						<el-row v-for="(t, n) in dsModel.data" :key="n" class="rh-row" :gutter="8">
							<el-col :span="7">
								<el-form-item :prop="'data.' + n +'.name'" :rules="nameRules" label-width="0">
									<el-input placeholder="名称" v-model="t.name"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="5">
								<el-form-item :prop="'data.' + n +'.type'" label-width="0">
									<el-select placeholder="类型" v-model="t.type">
										<el-option label="字符串类型" :value="'String'"></el-option>
										<el-option label="数值类型" :value="'Number'"></el-option>
										<el-option label="布尔类型" :value="'Boolean'"></el-option>
										<el-option label="变量或表达式" :value="'Variable'"></el-option>
                    <el-option label="表单数据" :value="'FormData'"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item :prop="'data.' + n +'.value'" :rules="valueRules" label-width="0">
									<el-input placeholder="值" v-model="t.value"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="3"><el-button icon="el-icon-delete" plain="" circle="" @click="deleteRequestData(n)"  size="mini"></el-button></el-col>
						</el-row>
						<el-row :span="6"><el-button type="text" icon="el-icon-plus" @click="addRequestData" class="button-sty">新增发送数据</el-button></el-row>
					</el-form-item>
					<el-collapse v-model="activeNames">
						<el-collapse-item class="ch-collapse" title="请求配置" name="1">
							<el-alert type="info" :closable="!1" title="(config, isSandbox, DSV, VFR) => {"></el-alert>
							<code-editor ref="chEditor" mode="javascript" :readonly="!1" v-model="dsModel.configHandlerCode"></code-editor>
							<el-alert type="info" :closable="!1" title="}"></el-alert>
						</el-collapse-item>
						<el-collapse-item class="ch-collapse" title="数据处理" name="2">
							<el-alert type="info" :closable="!1" title="(result, isSandbox, DSV, VFR) => {"></el-alert>
							<code-editor ref="dhEditor" mode="javascript" :readonly="!1" v-model="dsModel.dataHandlerCode"></code-editor>
							<el-alert type="info" :closable="!1" title="}"></el-alert>
						</el-collapse-item>
						<el-collapse-item class="ch-collapse" title="错误处理" name="3">
							<el-alert type="info" :closable="!1" title="(error, isSandbox, DSV, $message, VFR) => {"></el-alert>
							<code-editor ref="ehEditor" mode="javascript" :readonly="!1" v-model="dsModel.errorHandlerCode"></code-editor>
							<el-alert type="info" :closable="!1" title="}"></el-alert>
						</el-collapse-item>
           <!-- <el-collapse-item class="ch-collapse" title="执行SQL" name="4">
            	<code-editor ref="sqlEditor" mode="javascript" :readonly="!4" v-model="dsModel.sqlHandlerCode"></code-editor>
            </el-collapse-item> -->
					</el-collapse>
					<!-- <el-form-item label="唯一名称" prop="uniqueName">

				</el-form-item>
				<el-form-item label="唯一名称" prop="uniqueName">

				</el-form-item> -->
				</el-form>
			</template>
		</el-drawer>
	</div>
</template>

<script>
import i18n from '../../../../components/xform/utils/i18n';
import { deepClone, generateId,runDataSourceRequest } from '../../../../components/xform/utils/util';
import regeneratorRuntime from "regenerator-runtime";

export default {
	name: 'data-source-setting',
	mixins: [i18n],
	inject: ['getGlobalDsv'],
	components: { },
	props: {
		designer: Object,
		formConfig: Object
	},
	data: function() {
		return {
			activeNames: ['2'],
			dsModel: {
				dataSourceId: null,
				uniqueName: '',
				requestURL: '',
				requestaccessType: 'String',
				description: '',
				headers: [],
				params: [],
				data: [],
				requestMethod: 'get',
				configHandlerCode: '  return config',
				dataHandlerCode: '  return result.data.data;',
				// errorHandlerCode: '  $message.error(error.message);',
        errorHandlerCode: ''
			},
			curEditDSIdx: -1,
			formRules: {
				uniqueName: [
					{
						required: !0,
						trigger: ['blur', 'change'],
						message: this.i18nt('designer.setting.fieldValueRequired')
					}
				],
				requestURL: [
					{
						required: !0,
						trigger: ['blur', 'change'],
						message: this.i18nt('designer.setting.fieldValueRequired')
					}
				],
				requestMethod: [
					{
						required: !0,
						trigger: ['blur', 'change'],
						message: this.i18nt('designer.setting.fieldValueRequired')
					}
				]
			},
			nameRules: [
				{
					required: !0,
					trigger: ['blur', 'change'],
					message: this.i18nt('designer.setting.fieldValueRequired')
				}
			],
			valueRules: [
				{
					required: !0,
					trigger: ['blur', 'change'],
					message: this.i18nt('designer.setting.fieldValueRequired')
				},
				{
					validator: this.validateValueInput,
					trigger: ['blur', 'change']
				}
			],
			showDataSourceDialogFlag: !1,
			dsvJson: '{\n  \n}',
			dsResultJson: '',
			showTestDataSourceDialogFlag: !1
		};
	},
	methods: {
		validateValueInput: function(e, t, i) {
			var n = e.field,
				o = n.substring(0, n.indexOf('.')),
				a = Number(n.substring(n.indexOf('.') + 1, n.lastIndexOf('.'))),
				l = this.dsModel[o][a].type;
			'Number' === l
				? isNaN(t)
					? i(new Error(this.i18nt('designer.setting.dsRequestNumberTypeError')))
					: i()
				: 'Boolean' === l
				? 'true' === t.toLowerCase() || 'false' === t.toLowerCase() || 'null' === t.toLowerCase() || '1' === t || '0' === t
					? i()
					: i(new Error(this.i18nt('designer.setting.dsRequestBooleanTypeError')))
				: i();
		},
		addDataSource: function() {
			(this.curEditDSIdx = -1),
				// (this.dsModel = deepClone(this.dsModel)),
				(this.dsModel = deepClone(this.dsModel)),
				(this.dsModel.dataSourceId = null),
				(this.dsModel.uniqueName = ''),
				(this.dsModel.requestURL = ''),
				(this.dsModel.requestaccessType = 'String'),
				(this.dsModel.requestMethod = 'get'),
				(this.dsModel.description = ''),
				this.dsModel.headers.splice(0, this.dsModel.headers.length),
				this.dsModel.params.splice(0, this.dsModel.params.length),
				this.dsModel.data.splice(0, this.dsModel.data.length),
				(this.dsModel.configHandlerCode = '  return config'),
				(this.dsModel.dataHandlerCode = '  return result.data.data;'),
				// (this.dsModel.errorHandlerCode = '  $message.error(error.message);'),
        (this.dsModel.errorHandlerCode = ''),
				(this.showDataSourceDialogFlag = !0);
		},
		editDataSource: function(e) {
			(this.dsModel = deepClone(this.formConfig.dataSources[e])), (this.curEditDSIdx = e), (this.showDataSourceDialogFlag = !0);
		},
		saveDataSource: function() {
			var e = this;
			console.log('dsModel is: ', this.dsModel),
				this.$refs['dsForm'].validate(function(t, i) {
					if (t) {
						e.dsModel.dataSourceId = e.dsModel.dataSourceId || 'ds' + generateId();

						var n = e.dsModel.dataSourceId,
							o = e.dsModel.uniqueName,
							a = !1;
						e.formConfig.dataSources.map(function(e) {
							e.uniqueName === o && e.dataSourceId !== n && (a = !0);
						}),
							a
								? e.$message.error(e.i18nt('designer.setting.dsDuplicatedNameError'))
								: e.curEditDSIdx >= 0
								? (e.formConfig.dataSources.splice(e.curEditDSIdx, 1, deepClone(e.dsModel)), (e.showDataSourceDialogFlag = !1))
								: (e.formConfig.dataSources.push(e.dsModel), (e.showDataSourceDialogFlag = !1));
					} else e.$message.error(e.i18nt('designer.setting.dsValidationError'));
				});
		},
		deleteDataSource: function(e) {
			var t = this;
			this.$confirm(this.i18nt('designer.setting.deleteDataSourceHint'), this.i18nt('render.hint.prompt'), {
				confirmButtonText: this.i18nt('render.hint.confirm'),
				cancelButtonText: this.i18nt('render.hint.cancel')
			})
				.then(function() {
					t.formConfig.dataSources.splice(e, 1);
				})
				.catch(function(e) {
					console.error(e);
				});
		},
		addRequestHeader: function() {
			this.dsModel.headers.push({
				name: '',
				type: 'String',
				value: ''
			});
		},
		deleteRequestHeader: function(e) {
			this.dsModel.headers.splice(e, 1);
		},
		addRequestParam: function() {
			this.dsModel.params.push({
				name: '',
				type: 'String',
				value: ''
			});
		},
		deleteRequestParam: function(e) {
			this.dsModel.params.splice(e, 1);
		},
		addRequestData: function() {
			this.dsModel.data.push({
				name: '',
				type: 'String',
				value: ''
			});
		},
		deleteRequestData: function(e) {
			this.dsModel.data.splice(e, 1);
		},
		testDataSource: function() {
			var e = this.getGlobalDsv() || {};
			(this.dsvJson = JSON.stringify(e, null, '  ')), (this.showTestDataSourceDialogFlag = !0);
		},
		doDataSourceRequest: function() {
			var e = this;
			return Object(ie['a'])(
				regeneratorRuntime.mark(function t() {
					var i, n;
					return regeneratorRuntime.wrap(function(t) {
						while (1)
							switch ((t.prev = t.next)) {
								case 0:
									return (i = JSON.parse(e.dsvJson)), (t.next = 3), runDataSourceRequest(e.dsModel, i, null, !0, e.$message);
								case 3:
									(n = t.sent), e.$refs.dsResultEditor.setValue(JSON.stringify(n, null, '  '));
								case 5:
								case 'end':
									return t.stop();
							}
					}, t);
				})
			)();
		},
		clearRequestResult: function() {
			this.$refs.dsResultEditor.setValue('');
		}
	}
};
</script>

<style></style>
