<template>
	<el-drawer
		v-model="visible"
		:title="dataForm.id ? '编辑快速开发报表' : '新增快速开发报表'"
		:close-on-click-modal="false"
		:modal="false"
		size="95%"
		:wrapper-closable="false"
		class="detailDrawer"
	>
		<template #title><span>快速开发报表</span></template>
		<div style="padding: 10px">
			<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="140px">
				<el-row>
					<el-col :span="6">
						<el-form-item prop="reportCode">
							<template #label>
								报表编码
								<el-tooltip placement="top">
									<template #content>系统保存后自动生成<br /></template>
									<el-icon>
										<QuestionFilled />
									</el-icon>
								</el-tooltip>
							</template>
							<el-input v-model="dataForm.reportCode" readonly placeholder="系统自动生成" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="报表名称" prop="reportName">
							<el-input v-model="dataForm.reportName" placeholder="" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="系统产品" prop="systemProduct">
							<el-select v-model="dataForm.systemProduct" clearable placeholder="">
								<el-option :value="10" label="FAST" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="动态数据源" prop="reportDbSource">
							<el-input v-model="dataForm.reportDbSource" placeholder="" clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item label="是否树形" prop="isTree">
							<el-switch v-model="dataForm.isTree" :active-value="1" :inactive-value="0" />
						</el-form-item>
					</el-col>
					<el-col :span="18">
						<el-form-item label="报表描述" prop="reportContent">
							<el-input v-model="dataForm.reportContent" placeholder="" clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="快捷功能" prop="btnList">
							<el-checkbox-group v-model="dataForm.btnList">
								<el-checkbox key="form" label="form"><span style="color: #9fc5e8">表单</span></el-checkbox>
								<el-checkbox key="add" label="add"><span style="color: #666666">新增</span></el-checkbox>
								<el-checkbox key="del" label="del"><span style="color: #a45050">删除</span></el-checkbox>
								<el-checkbox key="batchDel" label="batchDel"><span style="color: #a45050">批量删除</span></el-checkbox>
								<el-checkbox key="update" label="update"><span style="color: #3e993e">修改</span></el-checkbox>
								<el-checkbox key="detail" label="detail"><span style="color: #9fc5e8">详情</span></el-checkbox>
								<el-checkbox key="import" label="import"><span style="color: #9fc5e8">导入</span></el-checkbox>
								<el-checkbox key="export" label="export"><span style="color: #9fc5e8">导出</span></el-checkbox>
							</el-checkbox-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item label="自定义URL" prop="isUrl">
							<el-switch v-model="dataForm.isUrl" :active-value="1" :inactive-value="0" />
						</el-form-item>
					</el-col>
					<el-col :span="18" v-if="dataForm.isUrl=='1'">
						<el-form-item label="URL地址" prop="reportUrl">
							<el-input v-model="dataForm.reportUrl" placeholder="" clearable />
						</el-form-item>
					</el-col>
				</el-row>
        <el-row v-if="dataForm.isUrl!='1'">
          <el-col :span="6">
            <el-form-item label="是否启用数据权限" prop="isUseDataScope">
              <el-switch v-model="dataForm.isUseDataScope" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dataForm.isUseDataScope=='1'">
            <el-form-item label="数据权限类型" prop="dataScopeListStr">
              <fast-select v-model="dataForm.dataScopeListStr" dict-type="dataScopeList" multiple="true" clearable placeholder="数据权限类型"></fast-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="dataForm.isUseDataScope=='1'">
            <el-form-item label="数据权限表别名" prop="dataScopeTableName">
              <el-input v-model="dataForm.dataScopeTableName" placeholder="" clearable />
            </el-form-item>
          </el-col>
        </el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="报表SQL" prop="reportSql">
							<el-input v-model="dataForm.reportSql" placeholder="" clearable type="textarea" :rows="10" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item>
							<el-button v-prevent-reclick type="primary" @click="createItem()">生成列明细</el-button>
							<el-button v-prevent-reclick type="primary" @click="clearItem()">清空列明细</el-button>
							<el-button v-prevent-reclick type="primary" @click="addSearchItem()">添加查询条件</el-button>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item class="sql-desc">
							<div>1、变量名：【租户】、【用户名】、【姓名】、【用户ID】、【数据权限】、【查询条件】、【#列JAVA属性】,其中 【#列JAVA属性】根据业务情况是否需要加单引号;</div>
							<div>2、显现在SQL中的位置为空时，如有【查询条件】 变量，则将为空的放在【查询条件】位置中，否则叠加条件语句;</div>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<report-item-tabs ref="reportItemTabsRef" :form="dataForm"></report-item-tabs>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<template #footer>
			<el-button v-prevent-reclick type="primary" @click="submitHandle()">确认</el-button>
			<el-button v-prevent-reclick @click="visible = false">取消</el-button>
			<el-button v-prevent-reclick type="primary" @click="getExeclTemp">快捷复制导出模型</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { createItemApi, useReportApi, useReportSubmitApi } from '../api/report'
import { ElMessageBox } from 'element-plus'
import { isEmpty } from '@/utils/validate'
import { QuestionFilled } from '@element-plus/icons-vue'
import reportItemTabs from '@/views/ebo/fast/report/reportItemTabs.vue'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()
const reportItemTabsRef = ref()
const dataForm = reactive({
	id: '',
	reportCode: '',
	reportName: '',
	systemProduct: '',
	reportDbSource: '',
	reportContent: '',
	isTree: '0',
	isUrl: '0',
	reportUrl: '',
	btnList: [],
	reportSql: '',
	fastReportItemList: [],
	fastReportSeachList: []
})

const init = (id?: number) => {
	dataForm.id = ''
	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
		Object.assign(dataForm, { fastReportItemList: [], fastReportSeachList: [] })
	}
	visible.value = true
	// id 存在则为修改
	if (id) {
		getReport(id)
	}
}

// 获取信息
const getReport = (id: number) => {
	useReportApi(id).then(res => {
		var columnShowList = ','
		res.data.fastReportItemList.forEach(item => {
			item.isSearch = item.isSearch + ''
      item.searchHidden = item.searchHidden + ''
			item.isOrder = item.isOrder + ''
			item.isShow = item.isShow + ''
			item.searchMode = item.searchMode + ''
			if (item.isShow == '1') {
				columnShowList += item.columnLabel + ','
			}
		})
		res.data.columnShowList = columnShowList
		res.data.fastReportSeachList.forEach(item => {
			item.isSearch = item.isSearch + ''
      item.searchHidden = item.searchHidden + ''
			item.searchMode = item.searchMode + ''
		})
		Object.assign(dataForm, res.data)
    if(dataForm.dataScopeList && dataForm.dataScopeList!=''){
      dataForm.dataScopeListStr = dataForm.dataScopeList.split(',');
    }

	})
}

const dataRules = ref({
	reportName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  dataScopeTableName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

const addSearchItem = () => {
	reportItemTabsRef.value.addSearchItemModels({})
}

const clearItem = () => {
	ElMessageBox.confirm('请确定要生成列明细吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		for (var i = 0; i < dataForm.fastReportItemList.length; i++) {
			reportItemTabsRef.value.handleOrderItemDelete(i)
			i--
		}
	})
}

const createItem = () => {
	ElMessageBox.confirm('请确定要生成列明细吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		createItemApi(dataForm).then(reponse => {
			ElMessage.success('生成列成功')
			let size = dataForm.fastReportItemList.length
			let value = new Map()
			var c = 10
			dataForm.fastReportItemList.forEach(item => {
				item.orderNum = c
				c += 10
				value.set(item.columnName, item)
			})
			var columnShowList = ','
			reponse.data.forEach(item => {
				if (size > 0 && !isEmpty(value.get(item.columnName))) {
				} else {
					item.orderNum = c
					reportItemTabsRef.value.addOrderItemModels(item)
					columnShowList += item.columnLabel + ','
					c += 10
				}
			})
			dataForm.columnShowList = columnShowList
		})
	})
}

const getExeclTemp = () => {
	var extempStr = ''
	var extempStrValue = ''
	dataForm.fastReportItemList.forEach(item => {
		if (item.isShow == '1') {
			extempStr += item.columnLabel + '\t'
			extempStrValue += '{.' + item.columnJavaName + '}\t'
		}
	})
	var outStr = extempStr + '\n' + extempStrValue;
	if(navigator.clipboard && window.isSecureContext) {
		navigator.clipboard.writeText(outStr).then(() => {
			ElMessage.success({
				message: '快捷复制导出模型，请粘贴在execl表格中',
				duration: 500,
				onClose: () => {
					//visible.value = false
					//emit('refreshDataList')
				}
			})
		}).catch(err => {
			// 复制失败
			console.error('复制失败')
		})
	}else {
		const textArea = document.createElement("textarea");
		textArea.value = outStr;
		textArea.style.position = "absolute";
		textArea.style.opacity = '0';
		textArea.style.left = "-999999px";
		textArea.style.top = "-999999px";
		document.body.appendChild(textArea);
		textArea.focus();
		textArea.select();
		document.execCommand('Copy');
		textArea.remove();
		ElMessage.success({
			message: '快捷复制导出模型，请粘贴在execl表格中',
			duration: 500,
			onClose: () => {
				//visible.value = false
				//emit('refreshDataList')
			}
		})
	}
}

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
    if(dataForm.dataScopeListStr!=null && dataForm.dataScopeListStr!=''){
      dataForm.dataScopeList = dataForm.dataScopeListStr.join(',');
    }else{
      dataForm.dataScopeList = '';
    }
		useReportSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					//visible.value = false
					//emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>

<style lang="scss" scoped>
.mod__menu {
	::v-deep(.el-popover.el-popper) {
		overflow-x: hidden;
	}

	.popover-list {
		::v-deep(.el-input__inner) {
			cursor: pointer;
		}

		::v-deep(.el-input__suffix) {
			cursor: pointer;
		}
	}

	&-icon-inner {
		width: 100%;
		max-height: 350px;
		overflow-x: hidden;
		overflow-y: auto;
		// 滚动条的宽度
		&::-webkit-scrollbar {
			width: 8px;
			height: 8px;
			background: transparent;
		}

		// 滚动条的设置
		&::-webkit-scrollbar-thumb {
			background-color: #dddddd;
			background-clip: padding-box;
			min-height: 28px;
			border-radius: 4px;
		}

		&::-webkit-scrollbar-thumb:hover {
			background-color: #bbb;
		}
	}

	&-icon-list {
		width: 100% !important;
		padding: 0;
		margin: -8px 0 0 -8px;

		> .el-button {
			padding: 8px;
			margin: 18px 0 0 8px;
			height: 45px;
			width: 45px;

			> span {
				display: inline-block;
				vertical-align: middle;
				width: 18px;
				height: 18px;
				font-size: 18px;
			}
		}
	}
}
.sql-desc {
	background: #F2F6FC;
	box-shadow: 0 0 2px #dcdfe6 inset;
	border-radius: 4px;
	padding: 10px;
	:deep(.el-form-item__content) {
		flex-direction: column;
		align-items: start;
	}
}
</style>
