<template>
	<div>
		<!-- 数据表 -->
		<div class="sourceBox">
			<div flex="cross:center main:justify" class="sourceBox_head">
				<span class="title">数据表</span>
				<el-button type="primary" @click="openTablesDialog('add')">新增</el-button>
			</div>
			<base-table ref="tablesData" :border="true" :showIndex="true" :highlightCurrent="true"
				:tableHeight="tableHeight" :tableData="tablesData" :tableColumn="tablesColumn" @radioChange="radioChange"
				@rowDblclick="rowDblclick">
				<!-- 操作 -->
				<template v-slot:tableType="{ row }">
					<!-- <span>{{ tableTypeNameList[row.tableType + 1] }}</span> -->
					<span>{{ row.tableType == 1 ? '主表' : row.tableType == 2 ? '子表' : '孙表' }}</span>
				</template>
				<template v-slot:operate="{ row }">
					<div flex="cross:center main:around" class="operate_icon">
						<i class="el-icon-edit-outline operate_icon_edit" @click="openTablesDialog('edit', row)"
							title="编辑"></i>
						<i class="el-icon-delete  operate_icon_delete" @click="tablesDataDel(row)" title="删除"></i>
					</div>
				</template>
				<template v-slot:isCreate="{ row }">
					<span>{{ row.isCreate == 1 ? '已生成' : '未生效' }}</span>
				</template>
			</base-table>
		</div>
		<!-- 数据表 -->
		<div class="sourceBox">
			<div flex="cross:center main:justify" class="sourceBox_head">
				<span class="title">数据源表字段</span>
				<el-button type="primary" @click="generateDatabase">生成数据库表</el-button>
			</div>
			<div class="sourceBox_table">
				<base-table ref="tableCoulmnData" :border="true" :showIndex="true" :indexOperate="true" @newRow="newRow"
					@row-class-name="tableRowClassName" :tableHeight="tableCoulmnDHeight" :tableData="tableCoulmnData"
					:tableColumn="tableCoulmnColumn" @radioChange="radioChange">
					<!-- 中文名 -->
					<template v-slot:fieldNameCN="{ row }">
						<el-input v-model="row.fieldNameCN"></el-input>
					</template>
					<!-- 英文名 -->
					<template v-slot:fieldNameEN="{ row }">
						<el-input v-model="row.fieldNameEN"></el-input>
					</template>
					<!-- 字段类型 -->
					<template v-slot:fieldType="{ row }">
						<el-select v-model="row.fieldType" placeholder="请选择字段类型" @change="dataTypeChange($event, row)">
							<el-option v-for="item in fieldTypeList" :key="item.value" :label="item.ddd_DicDetailsName"
								:value="item.ddd_DicDetailsName">
							</el-option>
						</el-select>
					</template>
					<!-- 长度 -->
					<template v-slot:fieldTypeLength="{ row }">
						<el-input v-model="row.fieldTypeLength"></el-input>
					</template>
					<!-- 必填 -->
					<template v-slot:isMustFill="{ row }">
						<el-switch style="display: block" v-model="row.isMustFill" active-color="#24D40A" :active-value="1"
							:inactive-value="0">
						</el-switch>
					</template>
					<!-- 显示 -->
					<template v-slot:isVisible="{ row }">
						<el-switch style="display: block" v-model="row.isVisible" active-color="#24D40A" :active-value="1"
							:inactive-value="0">
						</el-switch>
					</template>
					<!-- 显示类型 -->
					<template v-slot:dataType="{ row }">
						<el-select v-model="row.dataType" placeholder="请选择字段类型">
							<el-option v-for="item in dataTypeList" :key="item.value" :label="item.label"
								:value="item.value">
							</el-option>
						</el-select>
					</template>
					<!-- 数据类型 -->
					<template v-slot:displayType="{ row }">
						<el-input v-model="row.displayType"></el-input>
					</template>
					<!-- 数据源 -->
					<template v-slot:dataSource="{ row }">
						<el-input v-model="row.dataSource"></el-input>
					</template>
					<!-- 				显示类型
					<template v-slot:dataType="{row}">
						<div>
							<i class="el-icon-delete"></i>
						</div>
					</template> -->
					<!-- 操作 -->
					<template v-slot:operate="{ row }">
						<div class="operate_icon">
							<i class="el-icon-delete operate_icon_delete" @click="tableCoulmnDataDel(row)" title="删除"></i>
						</div>
					</template>
				</base-table>
			</div>
		</div>
		<!-- 新增/编辑数据库表名 -->
		<base-dialog :closeEscape="true" :showClose="true" :closeModal="false" @handleConfirmClick="tablesDialogClick"
			:appendBody="true" :dialogVisible.sync="tablesDialog" class="userDialog" width="600px" top="10vh"
			:footerShow="true">
			<base-form ref="tablesForm" :formRow="tablesFormRow" :isFunBtn="false" :rules="tablesRules"
				@onChangeRadio="onChangeRadio">
				<div slot="tableNameEN" flex="corss:center">
					<span>{{ typeNameList[dataMain.bm_type] }}_</span>
					<el-input v-model="tablesRuleForm.tableNameEN" style="flex: 1;"></el-input>
				</div>
			</base-form>
		</base-dialog>
	</div>
</template>

<script>
import baseTable from "@/components/base/baseTable"


import baseDialog from "@/components/base/BaseNewDialog"
import baseForm from "@/components/base/baseNewForm"
import dialogConfigData from './dialogConfigData'
import fieldsData from './fieldsData'
import {
	SaveData,
	GetBillData,
	GetTablesCoulmn,
	DelTableColumn,
	DelTables,
	BillMachineCreateDBTables
} from '@/api/apis/documentManagement'
import {
	dataDictionaryGetBillList
} from '@/api/apis/dataDictionary'
export default {
	components: {
		baseTable,
		baseDialog,
		baseForm
	},
	data() {
		return {
			tableHeight: '200px',
			tablesData: [],
			tablesColumn: dialogConfigData.tablesColumn,
			tablesDialog: false,
			tablesFormRow: dialogConfigData.tablesFormRow,
			tablesRules: dialogConfigData.tablesRules,
			tablesRuleForm: {},
			tableCoulmnDHeight: '400px',
			tableCoulmnData: [],
			tableCoulmnColumn: dialogConfigData.tableCoulmnColumn,
			typeNameList: {
				0: 'Sys',
				1: 'Business',
				2: 'Base',
			},
			tableTypeNameList: {
				1: '主表',
				2: '子表',
				3: '孙表',
			},
			editIndex: null,
			fieldTypeList: [], //字段类型List
			dataTypeList: [{
				label: '文本',
				value: 1
			}, {
				label: '日期',
				value: 2,
			}, {
				label: '下拉',
				value: 3
			}, {
				label: '弹窗',
				value: 4
			}], //数据类型List
			dataMain: {},
			bm_id: null,
			dbTablesRow: null
		}
	},
	mounted() {

	},
	methods: {
		initPage(id) {
			this.getDetail(id)
			this.getFieldType()
		},
		radioChange(row) {
		},
		onChangeRadio(val, index, indexRow, row) {
			// console.log(val, index, indexRow, row);
		},
		openTablesDialog(type, row) {
			this.tablesDialog = true
			this.editIndex = null
			this.$nextTick(() => {
				this.$refs.tablesForm.resetFields()
				if (type == 'edit') {
					this.editIndex = row.index
					let tableNameENBefore = row.tableNameEN.split('_')[0] + "_"
					this.tablesRuleForm = Object.assign({}, row)
					this.tablesRuleForm.tableNameEN = row.tableNameEN.split(tableNameENBefore)[1]
					this.$refs.tablesForm.choiceAssignment(this.tablesRuleForm)
				}
				this.tablesRuleForm = this.$refs.tablesForm.ruleForm
			})
		},
		tablesDialogClick() {
			this.$refs.tablesForm.$refs['ruleForm'].validate(valid => {
				if (valid) {
					let ruleForm = Object.assign({}, this.tablesRuleForm)
					// if(ruleForm.tableType != 0 && !ruleForm.associatedTable){
					// 	this.$tipConfirm("关联表名称需要填写")
					// 	return
					// }
					// if(ruleForm.tableType != 0 && !ruleForm.associatedColumn){
					// 	this.$tipConfirm("关联表字段需要填写")
					// 	return
					// }
					ruleForm.sort = this.tablesData.length + 1
					ruleForm.showType = 1
					ruleForm.tableNameEN = this.typeNameList[this.dataMain.bm_type] + "_" + ruleForm
						.tableNameEN
					try {
						this.tablesData.forEach(el => {
							if (ruleForm.tableNameEN == el.tableNameEN && ruleForm.detail_ID != el
								.detail_ID) {
								throw new Error() //结束循环
							}
						})
					} catch {
						this.$tipConfirm("英文名重复")
						return
					}
					if (this.editIndex == null) {
						this.tablesData.push(ruleForm)
					} else {
						this.tablesData[this.editIndex] = ruleForm
						this.$refs.tablesData.setTableKey()
					}
					if (this.editIndex && this.onChangeRadio) {
						this.$confirm('原表类型数据表已保存,是否更新表数据', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
							ruleForm.tableCoulmnData = []
						}).catch(() => { });
					}
					this.tablesDialog = false
				}
			})

		},
		rowDblclick(row) {
			this.dbTablesRow = row
			if (!row.tableCoulmnData) {
				// row.tableCoulmnData = []
				this.getTableCoulmnData(row)
			} else {
				this.tableCoulmnData = row.tableCoulmnData
				this.$refs.tableCoulmnData.setTableKey()
			}
		},
		// 数据表删除
		tablesDataDel(row) {
			this.$delConfirm().then((res) => {
				if (row.detail_ID) {
					this.tablesDel(row.detail_ID)
				} else {
					this.tablesData.splice(row.index, 1)
				}
			})
		},
		// 表字段删除
		tableCoulmnDataDel(row) {
			this.$delConfirm().then((res) => {
				if (row.detail_ID) {
					this.tableCoulmnDel(row.detail_ID,row.index)
				} else {
					this.tableCoulmnData.splice(row.index, 1)
				}
			})
		},
		dataTypeChange(e, row) {
			let fieldTypeLength = ""
			switch (e) {
				case "uniqueidentifier":
					fieldTypeLength = ""
					break;
				case "int":
					fieldTypeLength = ""
					break;
				case "datatime":
					fieldTypeLength = ""
					break;
				case "nvarchar":
					fieldTypeLength = "(200)"
					break;
				case "numeric":
					fieldTypeLength = "(18,2)"
					break;
				default:
					break;
			}
			this.$set(this.tableCoulmnData[row.index], 'fieldTypeLength', fieldTypeLength)
		},
		// 添加表字段
		newRow() {
			this.tableCoulmnData.push({})
		},
		saveDto(type) {
			if (type == 'next') {
				for (let i = 0; i < this.tablesData.length; i++) {
					if (this.tablesData[i].isCreate == 0) {
						this.$vmNews("请先保存数据库结构")
						return
					}
				}
			}
			this.saveForm(type)
		},
		async saveForm(type) {
			const loading = this.$loading({
				lock: true,
				text: '正在提交，请稍等',
				spinner: 'el-icon-loading',
				background: '#fff'
			});
			setTimeout(() => {
				loading.close()
			}, 10000);
			let tableCoulmnData = []
			this.tablesData.forEach(el => {
				if (el.tableCoulmnData) {
					el.tableCoulmnData.forEach((item, itemIndex) => {
						item.sort = itemIndex
						item.tableNameEN = el.tableNameEN
						tableCoulmnData.push(item)
					})
				}
			})
			let params = {
				dataMain: this.dataMain,
				tablesData: this.tablesData,
				tableCoulmnData: tableCoulmnData
			}
			let res = await SaveData(params)
			if (res.success == 'true') {
				this.$vmNews('保存成功', 'success')
				loading.close()
				// this.$refs.customForm.getField('bm_id', res.data[0])
				if (type == 'save') {
					this.getDetail(this.bm_id)
				}
				this.$emit('dataSourceSave', type, this.bm_id)
			}
		},
		async getDetail(id) {
			this.bm_id = id
			const loading = this.$loading({
				lock: true,
				text: '正在获取，请稍等',
				spinner: 'el-icon-loading',
				background: '#fff'
			});
			setTimeout(() => {
				loading.close();
			}, 10000);
			let res = await GetBillData({
				id: id
			})
			if (res.success == 'true') {
				this.dataMain = res.data[0]
				this.tablesData = res.data[1]
				this.tableCoulmnData = []
				loading.close()
			}
		},
		async getTableCoulmnData(row) {
			let res = await GetTablesCoulmn({
				tableNameEN: row.tableNameEN
			})
			if (res.success == 'true') {
				if (res.data[0].length == 0) {
					if (row.tableType == 1) {
						row.tableCoulmnData = Object.assign([], fieldsData.mainTablemData)
					}
					if (row.tableType == 2) {
						row.tableCoulmnData = Object.assign([], fieldsData.subtableData)
					}
					if (row.tableType == 3) {
						row.tableCoulmnData = Object.assign([], fieldsData.grandsonTableData)
					}
					this.tableCoulmnData = row.tableCoulmnData
					this.$refs.tableCoulmnData.setTableKey()
				} else {
					row.tableCoulmnData = res.data[0]
					this.tableCoulmnData = row.tableCoulmnData
					// this.tableCoulmnData.push({})
				}
			}
		},
		// 获取字段类型
		async getFieldType() {
			let params = {
				KindId: 22,
				page: 1,
				limit: 999,
				Sequence: '',
				SequenceName: ''
			}
			let res = await dataDictionaryGetBillList(params)
			if (res.code == 1) {
				this.fieldTypeList = res.data[1]
				// configData.fieldFormRow[0].elCol[0].options = arrList
			}
		},
		// 删除数据库行数据
		async tablesDel(id) {
			let res = await DelTables({
				id: id
			})
			if (res.code == 1) {
				this.getDetail(this.bm_id)
			}
		},
		// 删除数据库行数据
		async tableCoulmnDel(id,index) {
			let res = await DelTableColumn({
				id: id
			})
			if (res.code == 1) {
				this.tableCoulmnData.splice(index, 1)
			}
		},
		// 生成数据库表
		async generateDatabase() {
			if (!this.dbTablesRow) {
				this.$vmNews("请选择数据表")
				return
			}
			if (!this.dbTablesRow.detail_ID) {
				this.$vmNews("请先保存")
				return
			}
			let res = await BillMachineCreateDBTables({
				id: this.dbTablesRow.detail_ID
			})
			if (res.code == 1) {
				this.$vmNews("生成成功", 'success')
				this.tablesData[this.dbTablesRow.index].isCreate = 1
				this.tableCoulmnData = []
				this.dbTablesRow = null
				this.$refs.tablesData.setTableKey()
			}
		},
		tableRowClassName(obj, callback) {
			if (obj.rowIndex + 1 == this.tableCoulmnData.length) {
				callback('fiexTableBottm')
			}
		},
	}
}
</script>

<style scoped lang="scss">
.sourceBox {
	&_head {
		margin-bottom: 10px;
	}

	&_table {
		.el-table__row:last-child {
			position: sticky;
			bottom: 0;

		}

		;
	}

	.title {
		border-left: 3px solid #2261F6;
		padding-left: 10px;
	}
}

.sourceBox+.sourceBox {
	margin-top: 20px;
}

.operate_icon {
	font-size: 14px;

	&_delete {
		cursor: pointer;
		color: #E40D0D
	}

	&_edit {
		cursor: pointer;
		color: #333
	}
}
</style>
