<!--
 * @Author: zwq
 * @Date: 2024-07-01 14:54:06
 * @LastEditors: zwq
 * @LastEditTime: 2024-07-08 15:12:18
 * @Description:
-->
<template>
	<div style="display: flex; gap: 16px; flex: 1; background: #eff1f6">
		<div
			class="app-container"
			style="background: white; width: 280px; border-radius: 8px">
			<div class="head-container">
				<el-input
					v-model="treeName"
					placeholder="请输入名称"
					clearable
					size="small"
					prefix-icon="el-icon-search"
					style="margin-bottom: 20px" />
			</div>
			<div class="head-container">
				<el-tree
					v-loading="treeLoading"
					element-loading-text="拼命加载中"
					element-loading-spinner="el-icon-loading"
					element-loading-background="rgba(0, 0, 0, 0.8)"
					:data="deptOptions1"
					:props="defaultProps"
					node-key="id"
					:expand-on-click-node="false"
					:filter-node-method="filterNode"
					ref="tree"
					default-expand-all
					highlight-current
					@node-click="handleNodeClick">
					<span class="custom-tree-node" slot-scope="{ node, data }">
						<span>{{ node.label }}</span>
						<span style="float: right" v-if="data.parentId !== -1">
							<el-button
								class="btnHover"
								type="text"
								icon="el-icon-edit"
								size="mini"
								v-if="data.parentId !== 0"
								@click="() => edit(node, data)" />
							<el-button
								class="btnHover"
								type="text"
								icon="el-icon-circle-plus-outline"
								size="mini"
								@click="() => append(data)" />
							<el-button
								class="btnHover"
								type="text"
								icon="el-icon-remove-outline"
								size="mini"
								v-if="data.parentId !== 0"
								@click="() => remove(node, data)" />
						</span>
					</span>
				</el-tree>
			</div>
		</div>

		<div
			class="app-container"
			style="background: #fff; border-radius: 8px; width: 1px; flex: 1">
			<search-bar
				:formConfigs="formConfig"
				ref="searchBarForm"
				@headBtnClick="buttonClick" />
			<base-table
				v-loading="dataListLoading"
				:table-props="tableProps"
				:page="listQuery.pageNo"
				:limit="listQuery.pageSize"
				:table-data="tableData">
				<method-btn
					v-if="tableBtn.length"
					slot="handleBtn"
					:width="80"
					label="操作"
					:method-list="tableBtn"
					@clickBtn="handleClick" />
			</base-table>
			<pagination
				:limit.sync="listQuery.pageSize"
				:page.sync="listQuery.pageNo"
				:total="listQuery.total"
				@pagination="getDataList" />
			<base-dialog
				:dialogTitle="addOrEditTitle"
				:dialogVisible="addOrUpdateVisible"
				@cancel="handleCancel"
				@confirm="handleConfirm"
				:before-close="handleCancel"
				width="50%">
				<add-or-update
					ref="addOrUpdate"
					@refreshDataList="successSubmit"></add-or-update>
			</base-dialog>
		</div>

		<!-- 添加或修改菜单对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="700px">
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="父类型">
							<treeselect
								v-model="form.parentId"
								:options="deptOptions"
								:normalizer="normalizer"
								:show-count="true"
								:appendToBody="true"
								z-index="99999"
								placeholder="选择父类型" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="名称" prop="name">
							<el-input v-model="form.name" placeholder="请输入名称" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import AddOrUpdate from './add-or-updata';
import basicPage from '../../core/mixins/basic-page';
import { parseTime } from '../../core/mixins/code-filter';
import { publicFormatter } from '@/utils/dict';
import {
	getProductMaterialPage,
	deleteProductMaterial,
	getMaterialTree,
	createMaterialTree,
	updateMaterialTree,
	deleteMaterialTree,
} from '@/api/base/material';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

const tableProps = [
	{
		prop: 'createTime',
		label: '添加时间',
		filter: parseTime,
		width: 150,
	},
	{
		prop: 'name',
		label: '物料产品名称',
	},
	{
		prop: 'code',
		label: '物料产品编码',
	},
	{
		prop: 'typeNameChain',
		label: '物料产品类型',
	},
	{
		prop: 'unit',
		label: '单位',
		filter: publicFormatter('unit_dict'),
		width: 60,
	},
	{
		prop: 'specifications',
		label: '规格',
	},
	{
		prop: 'supplierName',
		label: '供应商',
	},
	{
		prop: 'remark',
		label: '备注',
	},
];

export default {
	mixins: [basicPage],
	name: '',
	components: {
		AddOrUpdate,
		Treeselect,
	},
	data() {
		return {
			// 部门树选项
			treeName: undefined,
			deptOptions: undefined,
			deptOptions1: undefined,
			treeLoading: false,
			defaultProps: {
				children: 'children',
				label: 'name',
			},
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 表单参数
			form: {
				id: undefined,
				parentId: undefined,
				name: undefined,
				defaultType: false,
			},
			// 表单校验
			rules: {
				name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
			},
			urlOptions: {
				getDataListURL: getProductMaterialPage,
				deleteURL: deleteProductMaterial,
			},
			tableProps,
			tableBtn: [
				this.$auth.hasPermi(`base:core-product:update`)
					? {
							type: 'edit',
							btnName: '编辑',
					  }
					: undefined,
				this.$auth.hasPermi(`base:core-product:delete`)
					? {
							type: 'delete',
							btnName: '删除',
					  }
					: undefined,
			].filter((v) => v),
			tableData: [],
			formConfig: [
				{
					type: 'input',
					label: '物料产品名称',
					placeholder: '物料产品名称',
					param: 'name',
				},
				{
					type: 'input',
					label: '物料产品编号',
					placeholder: '物料产品编号',
					param: 'code',
				},
				{
					type: 'input',
					label: '物料产品类型',
					param: 'type',
					disabled: true,
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
				{
					type: 'separate',
				},
				{
					type: this.$auth.hasPermi('base:material:create') ? 'button' : '',
					btnName: '新增',
					name: 'add',
					color: 'success',
					plain: true,
				},
			],
		};
	},
	watch: {
		// 根据名称筛选部门树
		treeName(val) {
			this.$refs.tree.filter(val);
		},
	},
	created() {
		this.getDataList();
		this.getTreeselect();
	},
	methods: {
		// 删除
		deleteHandle(id, name, index) {
			this.$confirm(`是否确认删除物料产品名称为"${name}"的数据项`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					this.urlOptions.deleteURL(id).then(({ data }) => {
						this.$message({
							message: '操作成功',
							type: 'success',
							duration: 1500,
							onClose: () => {
								this.getDataList();
							},
						});
					});
				})
				.catch(() => {});
		},
		buttonClick(val) {
			switch (val.btnName) {
				case 'search':
					this.listQuery.pageNo = 1;
					this.listQuery.pageSize = 10;
					this.listQuery.name = val.name ? val.name : undefined;
					this.listQuery.code = val.code ? val.code : undefined;
					this.getDataList();
					break;
				case 'add':
					this.addOrEditTitle = '新增';
					this.addOrUpdateVisible = true;
					this.$nextTick(() => {
						this.$refs.addOrUpdate.init();
						this.$refs.addOrUpdate.typeId(this.listQuery.typeId,this.listQuery.product);
					});
					break;
				case 'export':
					this.handleExport();
					break;
				default:
					console.log(val);
			}
		},

		/** 树操作 */

		// 查询下拉树结构
		getTreeselect() {
			this.treeLoading = true;
			getMaterialTree().then((response) => {
				// treeArr[0].push(...this.handleTree(response.data, 'id'));
				// 处理 deptOptions 参数
				this.deptOptions = [];
				this.treeLoading = false;
				this.deptOptions.push(...this.handleTree(response.data, 'id'));
				const arr = [{ name: '全部', parentId: -1 }];
				this.deptOptions1 = arr.concat(this.deptOptions);
			});
		},
		// 筛选节点
		filterNode(value, data) {
			if (!value) return true;
			return data.name.indexOf(value) !== -1;
		},
		// 节点单击事件
		handleNodeClick(data) {
			this.listQuery.typeId = data.id || undefined;
			this.listQuery.product = data.product;
			this.$refs.searchBarForm.formInline.type = data.name || undefined;
		},
		// 新增节点
		append(data) {
			this.open = true;
			this.title = '新增物料产品类型';
			this.form.id = undefined;
			this.form.parentId = data.id;
		},
		// 删除节点
		remove(node, data) {
			this.$confirm(`是否确认删除名称为"${data.name}"的数据项`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					deleteMaterialTree(data.id).then(({ data }) => {
						this.$message({
							message: '操作成功',
							type: 'success',
							duration: 1500,
							onClose: () => {
								this.getTreeselect();
							},
						});
					});
				})
				.catch(() => {});
		},
		// 编辑节点
		edit(node, data) {
			this.open = true;
			this.title = '编辑物料产品类型';
			this.form.id = data.id;
			this.form.name = data.name;
			this.form.parentId = data.parentId;
		},

		/** 转换菜单数据结构 */
		normalizer(node) {
			if (node.children && !node.children.length) {
				delete node.children;
			}
			return {
				id: node.id,
				label: node.name,
				children: node.children,
			};
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				parentId: 0,
				name: undefined,
				defaultType: false,
			};
			this.resetForm('form');
		},
		// 表单提交
		submitForm() {
			this.$refs['form'].validate((valid) => {
				if (!valid) {
					return false;
				}
				// 修改的提交
				if (this.form.id) {
					updateMaterialTree(this.form).then((response) => {
						this.$modal.msgSuccess('修改成功');
						this.cancel();
						this.getTreeselect();
					});
					return;
				}
				// 添加的提交
				createMaterialTree(this.form).then((response) => {
					this.$modal.msgSuccess('新增成功');
					this.cancel();
					this.getTreeselect();
				});
			});
		},
	},
};
</script>

<style scoped>
.btnHover:hover {
	color: #67c23a;
	transform: scale(1.5);
}
</style>
