<template>
	<div>
		<div>
			<div class="codeBox">
				<p class="title">列表页面</p>
				<p class="soild"></p>
				<div>
					<el-button @click="openListData">列表数据模板设置<i class="el-icon-success el-icon--right"
							:class="{ active: dataSourceCoulmn.length > 0 }"></i></el-button>
					<el-button @click="openDefaultQuery">默认查询方案<i class="el-icon-success el-icon--right"
							:class="{ active: billQueryPlanData.length > 0 }"></i>
					</el-button>
				</div>
			</div>
			<div class="codeBox">
				<p class="title">新增页面</p>
				<p class="soild"></p>
				<div>
					<el-button>页面设计<i class="el-icon-success el-icon--right"></i></el-button>
				</div>
			</div>
			<div class="codeBox">
				<p class="title">编辑页面</p>
				<p class="soild"></p>
				<div>
					<el-button>页面设计<i class="el-icon-success el-icon--right"></i></el-button>
				</div>
			</div>
			<div class="codeBox">
				<p class="title">查看页面</p>
				<p class="soild"></p>
				<div>
					<el-button>页面设计<i class="el-icon-success el-icon--right"></i></el-button>
				</div>
			</div>
		</div>
		<!-- 数据源弹窗 -->
		<base-dialog :closeEscape="true" :showClose="true" :closeModal="false" :dialogVisible.sync="listDataDialog"
			:footerShow="false" ref="listDataDialog" title="" width="80%" top="10vh">
			<div>
				<div flex>
					<div style="width: 25%; margin-right: 20px">
						<p class="defaultTitle">数据查询SQL</p>
						<div style="
                border: 1px solid #ccc;
                border-radius: 4px;
                text-align: center;
              ">
							<el-input type="textarea" :rows="10" v-model="sqlStr"></el-input>
							<el-button type="primary" style="margin: 10px 0" @click="checkSql">SQL校验</el-button>
						</div>
						<div class="listDataMsg" style="">
							{{ listDataMsg }}
						</div>
					</div>
					<div style="flex: 1">
						<p class="defaultTitle">列表字段显示模板</p>
						<base-table ref="baseTable" :border="true" :showIndex="true" :tableHeight="tableHeight"
							:indexOperate="true" @newRow="newRow" :tableData="dataSourceCoulmn" :tableColumn="tableColumn" @row-class-name="tableRowClassName"
							:sortableSwitch="true">
							<!-- 宽度 -->
							<template v-slot:columnNameCN="{ row }">
								<el-input v-model="row.columnNameCN"></el-input>
							</template>
							<template v-slot:align="{ row }">
								<el-select v-model="row.align" placeholder="请选择">
									<el-option v-for="item in align" :key="item.value" :label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</template>
							<template v-slot:columnNameEN="{ row }">
								<el-input v-model="row.columnNameEN"></el-input>
							</template>
							<template v-slot:showLength="{ row }">
								<el-input v-model="row.showLength" type="number"></el-input>
							</template>
							<template v-slot:isCanSort="{ row }">
								<el-switch :inactive-value="0" :active-value="1" v-model="row.isCanSort"></el-switch>
							</template>
							<template v-slot:color="{ row }">
								<!-- <span @click="colorInputClick($event,row)">{{row.color ? row.color :'选择颜色'}}</span> -->
								<el-color-picker v-model="row.color"></el-color-picker>
							</template>
							<template v-slot:columntype="{ row }">
								<el-input v-model="row.columntype"></el-input>
							</template>
							<template v-slot:opeare="{ row }">
								<i class="el-icon-delete" style="color: red" @click="delTable(row)"></i>
							</template>
						</base-table>
					</div>
				</div>
				<div style="text-align: right; margin-top: 10px">
					<el-button type="primary" @click="confirmClick">保存</el-button>
					<el-button @click="listDataDialog = false">关闭</el-button>
				</div>
			</div>
		</base-dialog>
		<!-- 默认查询弹窗 -->
		<base-dialog :closeEscape="true" :showClose="true" :closeModal="false" :dialogVisible.sync="defaultQueryDialog"
			@handleConfirmClick="defaulthandleConfirmClick" :footerShow="true" ref="defaultQueryDialog" title="" width="80%"
			top="10vh">
			<div flex>
				<base-table ref="defaultLeftTable" :tableHeight="tableHeight" :tableData="dataSourceCoulmn"
					style="width: 45%; margin-right: 20px" @onSelectionChange="defaultSelectionChange"  @select="select" @selectAll="selectAll"
					:tableColumn="defaultLeftColumn" :showSelect="true">
				</base-table>
				<base-table ref="defaultRightTable" :tableHeight="tableHeight" :tableData="billQueryPlanData"
					style="flex: 1" :tableColumn="defaultRightColumn" :showIndex="true" :sortableSwitch="true">
					<template v-slot:compare="{ row }">
						<el-input v-model="row.compare" clearable type="text" placeholder="> < = like"></el-input>
					</template>
					<template v-slot:tag="{ row }">
						<el-select v-model="row.tag" placeholder="请选择">
							<el-option v-for="(item,ind) in tagOptions" :key="ind" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
					</template>
				</base-table>
			</div>
		</base-dialog>
	</div>
</template>

<script>
import bus from "./eventBus";
import baseDialog from "@/components/base/BaseNewDialog/index.vue";
import baseTable from "@/components/base/baseTable";
import {
	encryp,
	decrypt
} from "@/utils/cryptoEncryption";
import {
	BillMachineCheckSql,
	BillMachineGetDataSource,
	BillMachineGetBillQueryPlan,
	BillMachineSaveDataSource,
	BillMachineSaveBillQueryPlan,
} from "@/api/apis/documentManagement";
import designConfigData from "./designConfigData";
import {
	Sketch
} from "vue-color";
import eventBus from "./eventBus";
export default {
	components: {
		baseDialog,
		baseTable,
		"sketch-picker": Sketch,
	},
	data() {
		return {
			listOption: true,
			listData: false,
			addDesign: false,
			editDesign: false,
			seeDesign: false,
			listDataDialog: false,
			// dataSourceCoulmn: [{}],
			tableHeight: "420px",
			tableColumn: designConfigData.tableColumn,
			listDataMsg: "",
			isShowColors: false,
			color: "#ccc",
			colorLeft: "",
			colorTop: "",
			colorForm: {},
			sqlStr: "",
			billKindID: null,
			defaultQueryDialog: false,
			defaultLeftColumn: designConfigData.defaultLeftColumn,
			defaultRightColumn: designConfigData.defaultRightColumn,
			dataSourceCoulmn: [],
			billQueryPlanData: [],
			sqlCheck: false,
			tagOptions: [{
				label: "文本",
				value: "elInput"
			},
			{
				label: "日期",
				value: "elDatePicker"
			},
			{
				label: "单选",
				value: "elRadio"
			},
			{
				label: "开关",
				value: "elSwitch"
			},
			{
				label: "参照",
				value: "elDialog"
			},
			{
				label: "下拉",
				value: "elSelect"
			},
			],
			align: [{
				label: "居中",
				value: "center"
			},
			{
				label: "左对齐",
				value: "left"
			},
			{
				label: "右对齐",
				value: "right"
			},
			]
		};
	},
	created() {
		bus.$on("bm_DataSourceSQL", (el) => {
			this.sqlStr = el;
		});
	},
	methods: {
		initPage(id) {
			this.billKindID = id;
			this.getDataSource(id);
		},
		// 打开列表弹窗
		openListData() {
			this.listDataDialog = true;
		},

		// 颜色输入框点击事件处理
		colorInputClick(e, val) {
			let windowHight = window.innerHeight * 0.1;
			let windowWidth = window.innerHeight * 0.2;
			this.colorTop = e.clientY - windowHight;
			this.colorLeft = e.clientX - windowWidth - 110;
			this.color = val.color;
			this.colorForm = val;
			this.isShowColors = !this.isShowColors;
		},
		// 颜色值改变事件处理
		colorValueChange(val) {
			// 取颜色对象的十六进制值
			this.color = val.hex;
		},
		colorSure() {
			this.dataSourceCoulmn[this.colorForm.index].color = this.color;
			this.$refs.baseTable.setTableKey();
			this.isShowColors = false;
		},
		updateValue() { },
		async checkSql() {
			this.$confirm('当前操作会覆盖列表字段显示模板，是否继续？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.BillMachineCheckSql()
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消操作'
				});
			});
		},
		async BillMachineCheckSql() {
			let column = this.sqlStr.substring(this.sqlStr.indexOf("select") + 6, this.sqlStr.indexOf("from")).split(",").map(column => column.trim()).join(", ");
			// let column = this.sqlStr.substring(this.sqlStr.indexOf("select") + 6, this.sqlStr.indexOf("from")); //字段集合
			let tablesList = [];
			if (this.sqlStr.indexOf("where") != -1) {
				let tables = this.sqlStr.substring(
					this.sqlStr.indexOf("from") + 4,
					this.sqlStr.indexOf("where")
				);
				tablesList.push(tables);
			} else {
				const regex = /join(.*?) on/g;
				let match;
				while ((match = regex.exec(this.sqlStr)) !== null) {
					tablesList.push(match[1]);
				}
				if (this.sqlStr.indexOf("left") != -1) {
					let tables = this.sqlStr.substring(
						this.sqlStr.indexOf("from") + 4,
						this.sqlStr.indexOf("left")
					);
					tablesList.push(tables);
				} else if (this.sqlStr.indexOf("right") != -1) {
					let tables = this.sqlStr.substring(
						this.sqlStr.indexOf("from") + 4,
						this.sqlStr.indexOf("right")
					);
					tablesList.push(tables);
				}
				console.log(tablesList, "22");
			}
			////

			// let tables = this.sqlStr.split("from")[1].split(" ")[2];
			// tablesList.push(tables);
			// this.sqlStr.split("join").forEach((el, index) => {
			// 	if (index != 0) {
			// 		tablesList.push(el.split(" ")[2]);
			// 	}
			// });
			let params = {
				sqlStr: encryp(this.sqlStr),
				column: column,
				// tables: tablesList.join(",").replace(/\s*/g, ""),
				tables: tablesList.join(","),
			};
			let res = await BillMachineCheckSql(params);
			if (res.code == 1) {
				this.sqlCheck = true;
				this.dataSourceCoulmn = res.data[0];
				this.listDataMsg = res.message || "成功";
			}
		},
		newRow() {
			this.dataSourceCoulmn.push({});
		},
		openDefaultQuery() {
			this.defaultQueryDialog = true;
			let selectList = [];
			let billQueryPlanData = []
			this.billQueryPlanData.forEach((el) => {
				billQueryPlanData.push(el)
				this.dataSourceCoulmn.forEach((item) => {
					if (el.columnNameEN == item.columnNameEN) {
						selectList.push(item);
					}
				});
			});
			this.$nextTick(() => {
				this.$refs.defaultLeftTable.toggleSelection(selectList, true);
				this.billQueryPlanData = billQueryPlanData;
			});
		},

		delTable(row) {
			this.$delConfirm().then((res) => {
				this.dataSourceCoulmn.splice(row.index, 1);
			});
		},
		defaultSelectionChange(val) {
			// this.billQueryPlanData = val;
		},
		selectAll(val) {
			if (val.length == 0) {
				this.billQueryPlanData = []
			} else {
				let data = val.filter(item => !this.billQueryPlanData.some(el => el.columnNameEN == item.columnNameEN))
				this.billQueryPlanData.push(...data)
			}
		},
		select(selection, row){
			delete row.compare
			if (selection[selection.length -1] == row) {
				this.billQueryPlanData.push(row)
			} else {
				this.billQueryPlanData.forEach((el,index) => {
					if (el.columnNameEN == row.columnNameEN) {
						this.billQueryPlanData.splice(index,1)
					}
				})
			}
		},
		// handleInput(val,item) {
		// 	console.log(item);
		// 	this.billQueryPlanData[item.index].compare = val
		// },
		// 查询方案-获取单据查询方案
		async getQueryPlan(id) {
			let res = await BillMachineGetBillQueryPlan({
				billKindID: id,
			});
			if (res.code == 1) {
				this.billQueryPlanData = res.data[0];
				this.billQueryPlanData.forEach((item) => {
					this.dataSourceCoulmn.forEach((el) => {
						if (el.columnNameEN == item.columnNameEN) {
							el.compare = item.compare;
						}
					});
				});
			}
		},
		// 数据源-获取单据标准数据源
		async getDataSource(id) {
			let res = await BillMachineGetDataSource({
				billKindID: id,
				type: 0
			});
			if (res.code == 1) {
				this.dataSourceCoulmn = res.data[0];
				this.getQueryPlan(id);
			}
		},
		// 数据源--保存
		async confirmClick() {
			if (this.dataSourceCoulmn.length == 0) {
				this.$vmNews("sql未校验，无法保存", "warning");
				return;
			}
			// if (this.sqlCheck == false) {
			//   this.$vmNews("sql未校验，无法保存", "warning");
			//   return;
			// }
			// for (let i = 0; i < this.dataSourceCoulmn.length; i++) {
			//   if (this.dataSourceCoulmn[i].columnNameCN == null) {
			//     this.$vmNews(`第${i + 1}行字段名称(中文)为空，无法保存`, "warning");
			//     return;
			//   }
			// }
			this.dataSourceCoulmn.forEach((el) => {
				el.sort = el.index;
				el.isShow = 0;
			});
			let params = {
				type: 0,
				sqlStr: encryp(this.sqlStr),
				billKindID: this.billKindID,
				// tableNameEN: '所鼠标',
				// columntype: '字段类型，接口无',
				dataSourceCoulmn: this.dataSourceCoulmn,
			};
			let res = await BillMachineSaveDataSource(params);
			if (res.code == 1) {
				this.$vmNews("保存成功", "success");
				this.listDataDialog = false;
			}
		},
		async defaulthandleConfirmClick() {
      		for (let i = 0; i < this.billQueryPlanData.length; i++) {
      		  if (!this.billQueryPlanData[i].tag || this.billQueryPlanData[i].tag == "") {
      		    this.$message({
      		      message: `请录入查询方案行${i + 1}控件名称`,
      		      type: "warning",
      		    });
      		    return;
      		  } else if (!this.billQueryPlanData[i].compare || this.billQueryPlanData[i].compare == "") {
      		    this.$message({
      		      message: `请录入查询方案行${i + 1}比较符`,
      		      type: "warning",
      		    });
      		    return;
      		  }
      		}
			let params = {
				billKindID: this.billKindID,
				billQueryPlan: this.billQueryPlanData,
			};
			let res = await BillMachineSaveBillQueryPlan(params);
			if (res.code == 1) {
				this.$vmNews("保存成功", "success");
				this.defaultQueryDialog = false;
			}
		},
		tableRowClassName(obj, callback) {
			if (obj.rowIndex + 1 == this.dataSourceCoulmn.length) {
				callback('fiexTableBottm')
			}
		},
	},
};
</script>

<style scoped lang="scss">
.codeBox {
	padding-bottom: 50px;

	.soild {
		margin-top: 16px;
		margin-bottom: 12px;
		height: 1px;
		background-color: #f2f2f2;
	}

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

	.active {
		color: #2bd630;
	}
}

.defaultTitle {
	border-left: 3px solid #2261f6;
	padding-left: 10px;
	margin-bottom: 20px;
}

.controls-box {
	position: absolute;
	left: 150px;
	top: 50px;
	width: 300px;
	padding: 10px;
	background-color: #fafafa;
	border: 1px solid #c3c3c3;
	border-radius: 5px;
}

.label-col {
	padding: 8px 5px;
}

.color-select-layer {
	position: absolute;
	box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15), 0 8px 16px rgba(0, 0, 0, 0.15);
	background-color: white;
	border-radius: 5px;
	// left: -36px;
	// top: 10px;
	padding: 10px 0;

	.operate {
		background-color: white;
		justify-content: space-around;
		background-color: white;

		.sure {
			color: #55aaff;
			cursor: pointer;
		}

		.close {
			cursor: pointer;
		}
	}
}

.vc-sketch-presets {
	overflow: auto;
}

.vc-sketch {
	box-shadow: none;
}

.listDataMsg {
	border-radius: 4px;
	height: 155px;
	border: 1px solid #ccc;
	margin-top: 15px;
}
</style>
