<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true">
      <el-form-item label="规则名称" prop="rule_name">
        <el-input v-model="queryParams.rule_name" placeholder="请输入规则名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.statusn" placeholder="状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8" style="min-height:32px">
      <el-col :span="1.5" v-hasPermi="['system:rules:add']">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['system:rules:export']">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-card shadow="never">
      <el-table ref="tableRef" v-loading="loading" :data="rulesList" :default-sort="defaultSort">
        <el-table-column label="序号" align="center" type="index" width="50" />
        <el-table-column label="规则名称" align="center" prop="rule_name"/>
        <el-table-column label="规则内容" align="center" prop="text" />
        <el-table-column label="报警速度(KM/H)" align="center" prop="speed" width="150" />
        <el-table-column label="报警间隔(秒)" align="center" prop="rule_interval" width="150" />
		<el-table-column label="规则描述" align="center" prop="rule_describe" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.statusn" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" sortable="custom" :sort-orders="['descending', 'ascending']">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link icon="Edit" type="success" @click="handleUpdate(scope.row)">
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link icon="Delete" type="danger" @click="handleDelete(scope.row)">
                </el-button>
              </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body :fullscreen="false">
      <el-form ref="roleRef" :model="rulesForm" :rules="rules" label-width="100px" class="flex">
        <div class="flex-sub">
          <el-card shadow="never">
            <el-form-item label="规则名称" prop="rule_name">
            	<el-input v-model="rulesForm.rule_name" placeholder="请输入规则名称" />
            </el-form-item>
            <el-form-item label="规则内容" prop="text">
            	<el-input v-model="rulesForm.text" placeholder="请输入规则内容" />
            </el-form-item>
            <el-form-item label="报警速度" prop="speed">
            	<el-input placeholder="请输入报警速度" v-model="rulesForm.speed">
            		<template #append>海里/小时</template>
            	</el-input>
            </el-form-item>
            <el-form-item label="报警间隔" prop="rule_interval">
            	<el-input placeholder="请输入报警间隔" v-model="rulesForm.rule_interval">
            		<template #append>秒</template>
            	</el-input>
            </el-form-item>
            <el-form-item label="状态">
            	<el-radio-group v-model="rulesForm.statusn">
            		<el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
            	</el-radio-group>
            </el-form-item>
            <el-form-item label="规则描述">
            	<el-input v-model="rulesForm.rule_describe" type="textarea" placeholder="请输入规则描述" :rows="10"></el-input>
            </el-form-item>
          </el-card>
        </div>
        <div class="flex-sub">
			<el-form-item label="区域围栏">
				<el-checkbox v-model="regionExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
				<el-checkbox v-model="regionNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
				<ScrollBox style="height:calc(100vh - 300px);">
					<el-tree class="tree-border" :data="regionOptions" show-checkbox 
						ref="regionRef" node-key="id" empty-text="加载中，请稍候" 
						:props="{ label: 'group_name', children: 'children' }"></el-tree>
				</ScrollBox>
			</el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const rulesList = ref([]);


const regionOptions = ref([]);
const regionExpand = ref(false);
const regionNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const deptOptions = ref([]);
const openDataScope = ref(false);
const regionRef = ref(null);
const deptRef = ref(null);
const defaultSort = ref({ prop: "createTime", order: "" });

const data = reactive({
	rulesForm: {},
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		rule_name: undefined,
		statusn: undefined
	},
	rules: {
		rule_name: [{ required: true, message: "规则名称不能为空", trigger: "blur" }],
		text: [{ required: true, message: "规则内容不能为空", trigger: "blur" }],
		speed: [{ required: true, message: "报警速度不能为空", trigger: "blur" }],
		rule_interval: [{ required: true, message: "报警间隔不能为空", trigger: "blur" }]
	}
});

const { queryParams, rulesForm, rules } = toRefs(data);
/** 查询角色列表 */
function getList() {
	// loading.value = true;
	// listRole(queryParams.value).then((response) => {
		// rulesList.value = response.rows;
		// total.value = response.total;
		rulesList.value = [{
			ruleId: 88,
			rule_name:"航速管制规则",
			text:"您已超速，请注意航速",
			speed: 5,
			rule_interval: 30,
			statusn: "0",
			rule_describe:"次规则规定船舶航速不得超过5",
			fence_ids: '{"fence_ids":[14]}',
			createTime: "1682256425"
		}]
		loading.value = false;
	// });
}
/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	getList();
}
/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm("queryRef");
	queryParams.value.pageNum = 1;
	proxy.$refs["tableRef"].sort(defaultSort.value.prop, defaultSort.value.order);
}
/** 删除按钮操作 */
function handleDelete(row) {
	const ruleIds = row.ruleId;
	proxy.$modal
		.confirm('是否确认删除"' + row.rule_name + '"的数据项?')
		.then(function () {
		// return delRole(ruleIds);
	}).then(() => {
		getList();
		proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
	proxy.download(
		"system/role/export",
		{
		...queryParams.value,
		},
		`role_${new Date().getTime()}.xlsx`
	);
}
/** 角色状态修改 */
function handleStatusChange(row) {
	let text = row.status === "0" ? "启用" : "停用";
	// proxy.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
 //    .then(function () {
	// 	return changeRoleStatus(row.roleId, row.status);
 //    })
 //    .then(() => {
	// 	proxy.$modal.msgSuccess(text + "成功");
 //    })
 //    .catch(function () {
	// 	row.status = row.status === "0" ? "1" : "0";
 //    });
}
/** 查询菜单树结构 */
function getMenuTreeselect() {
	regionOptions.value = [{
		group_name: "广州易站",
		department: "区域管理",
		id: 4,
		pid: 0,
		type: 0,
		fence_type: null,
		add_userid: 1,
		children: [{
			id: 14,
			group_name: "易站001",
			department: "广州易站",
			pid: 4,
			type: 1,
			fence_type: 1,
			add_userid: 1
		},{
			id: 15,
			group_name: "易站002",
			department: "广州易站",
			pid: 4,
			type: 1,
			fence_type: 1,
			add_userid: 1
		},{
			id: 16,
			group_name: "易站003",
			department: "广州易站",
			pid: 4,
			type: 1,
			fence_type: 1,
			add_userid: 1
		}]
	}];
	// menuTreeselect().then((response) => {
	// 	regionOptions.value = response.data;
	// });
}
/** 重置新增的表单以及其他数据  */
function reset() {
	if (regionRef.value != undefined) {
		regionRef.value.setCheckedKeys([]);
	}
	regionExpand.value = false;
	regionNodeAll.value = false;
	deptExpand.value = true;
	deptNodeAll.value = false;
	rulesForm.value = {
		ruleId: undefined,
		rule_name: undefined,
		text: undefined,
		speed: 0,
		rule_interval: 0,
		statusn: "0",
		rule_describe: undefined,
		fence_ids: ""
	};
	proxy.resetForm("roleRef");
}
/** 添加角色 */
function handleAdd() {
	reset();
	getMenuTreeselect();
	open.value = true;
	title.value = "添加规则信息";
}
/** 修改角色 */
function handleUpdate(row) {
	reset();
	getMenuTreeselect()
	// const roleId = row.roleId || ids.value;
	// const roleMenu = getRoleMenuTreeselect(roleId);
	// getRole(roleId).then((response) => {
	// 	rulesForm.value = response.data;
	// 	rulesForm.value.roleSort = Number(rulesForm.value.roleSort);
		rulesForm.value = JSON.parse(JSON.stringify(row))
		open.value = true;
	// 	nextTick(() => {
	// 		roleMenu.then((res) => {
				let checkedKeys = JSON.parse(rulesForm.value.fence_ids).fence_ids;
				checkedKeys.forEach((v) => {
					nextTick(() => {
						regionRef.value.setChecked(v, true, false);
					});
				});
	// 		});
	// 	});
		title.value = "修改规则信息";
	// });
}
/** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeselect(roleId) {
	return roleMenuTreeselect(roleId).then((response) => {
		regionOptions.value = response.menus;
		return response;
	});
}
/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
	let treeList = regionOptions.value;
	for (let i = 0; i < treeList.length; i++) {
		regionRef.value.store.nodesMap[treeList[i].id].expanded = value;
	}
}
/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
	regionRef.value.setCheckedNodes(value ? regionOptions.value : []);
}
/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
	// 目前被选中的菜单节点
	let checkedKeys = regionRef.value.getCheckedKeys();
	// 半选中的菜单节点
	let halfCheckedKeys = regionRef.value.getHalfCheckedKeys();
	checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
	return checkedKeys;
}
/** 提交按钮 */
function submitForm() {
	proxy.$refs["roleRef"].validate((valid) => {
		if (valid) {
			if (rulesForm.value.ruleId != undefined) {
			rulesForm.value.fence_ids = getMenuAllCheckedKeys();
			// updateRole(rulesForm.value).then((response) => {
				proxy.$modal.msgSuccess("修改成功");
				open.value = false;
				// getList();
			// });
			} else {
				rulesForm.value.fence_ids = getMenuAllCheckedKeys();
				// addRole(rulesForm.value).then((response) => {
					proxy.$modal.msgSuccess("新增成功");
					open.value = false;
					// getList();
				// });
			}
			console.log(rulesForm.value)
		}
	});
}
/** 取消按钮 */
function cancel() {
	open.value = false;
	reset();
}
getList();


</script>
