<template>
	<div class="contain_bom">
		<div class="title">
			<span>
				<el-button size="small" icon="ele-Plus" :disabled="material.isLock" @click="addClickPar"> 新增一级物料 </el-button>
				<el-button size="small" icon="ele-Mouse" :disabled="material.isLock" @click="changeSort"> 调整排序及层级 </el-button>
				<!--                <el-button size="small" icon="ele-GobletFull"-->
				<!--                    :disabled="material.isLock || material.bomApproveStatus == 1" @click="submitAbove"> 提交审核-->
				<!--                </el-button>-->
				<!--                <el-button size="small" icon="ele-Connection" :disabled="material.isLock" @click="versionClick"> 版本更新-->
				<!--                </el-button>-->
				<!--                <span style="margin-left: 10px;">当前版本：<el-input v-model="material.bomVerNo" disabled-->
				<!--                        style="width: 200px;" placeholder="请输入版本号"></el-input> </span>-->
			</span>
			<!--            <span>-->
			<!--                <span style="font-size:12px;">-->
			<!--                    <el-button size="small" icon="ele-Search" @click="histroyClick"> 历史版本查询-->
			<!--                    </el-button>-->
			<!--                </span>-->
			<!--            </span>-->
			<!-- <el-button size="small" icon="ele-Plus"> 提交审批
            </el-button> -->
		</div>
		<!-- <div class="approve">
            <img src="/@/assets/submitok.png" v-if="material.bomApproveStatus == 2" style="width:100px;" />
            <img src="/@/assets/pedding.png" v-else style="width:100px;" />
        </div> -->
		<div class="table" style="margin-top: 10px">
			<el-table
				:data="bomData"
				id="bomtable"
				style="width: 100%; margin-bottom: 10px"
				max-height="400px"
				size="small"
				row-key="id"
				border
				default-expand-all
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
			>
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column  label="" width="100" />
				<el-table-column prop="materialCode" label="物料编码" width="200" show-overflow-tooltip="" />
				<el-table-column prop="materialName" label="物料名称" width="140" show-overflow-tooltip="" />
				<el-table-column prop="specs" label="规格型号" show-overflow-tooltip="" />
				<el-table-column prop="unitName" label="计量单位名称" show-overflow-tooltip="" />
				<!-- <el-table-column prop="purchaseUnitUse" label="采购用量" width="120" show-overflow-tooltip="" /> -->
				<el-table-column prop="unitUse" label="单位用量" width="120" show-overflow-tooltip="" />
				<el-table-column prop="supplyType" label="供应方式" show-overflow-tooltip="">
					<template #default="scope">
						<span v-if="scope.row.supplyType == 1">外协</span>
						<span v-else>自制</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="140" align="center" show-overflow-tooltip="">
					<template #default="scope">
						<el-button icon="ele-Plus" :disabled="material.isLock" size="small" text="" type="primary" @click="addChildrenClick(scope.row)"> </el-button>
						<el-button icon="ele-Edit" :disabled="material.isLock" size="small" text="" type="primary" @click="openEditMesProductBom(scope.row)"> </el-button>
						<el-button icon="ele-Delete" :disabled="material.isLock" size="small" text="" type="primary" @click="delMesProductBom(scope.row)"> </el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-dialog v-model="isShowDialog" :width="800" draggable="" destroy-on-close>
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>{{ title }}</span>
				</div>
			</template>
			<el-form :model="ruleForm" ref="ruleFormRef" label-width="120" :rules="rules">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="物料编码" prop="materialCode">
							<el-input v-model="ruleForm.materialCode" @click="chooseProduct" placeholder="请输入物料编码" maxlength="100" show-word-limit clearable />
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="层级" prop="layout">
                            <el-input v-model="ruleForm.layout" placeholder="请输入层级" maxlength="100" show-word-limit
                                clearable />
                        </el-form-item>
                    </el-col> -->
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="排序" prop="sort">
                            <el-input-number v-model="ruleForm.sort" placeholder="请输入排序" clearable />
                        </el-form-item>
                    </el-col> -->

					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="采购用量" prop="purchaseUnitUse">
                            <el-input-number v-model="ruleForm.purchaseUnitUse" style="width:100%;"
                                placeholder="请输入采购用量" clearable />
                        </el-form-item>
                    </el-col> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="单位用量" prop="unitUse">
							<el-input-number v-model="ruleForm.unitUse" style="width: 100%" placeholder="请输入单位用量" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="供应方式 " prop="supplyType">
							<el-select v-model="ruleForm.supplyType" style="width: 100%" placeholder="请输入供应方式">
								<el-option label="自制" :value="0"> </el-option>
								<el-option label="外协" :value="1"> </el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="ruleForm.remark" placeholder="请输入备注" maxlength="255" show-word-limit clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="isShowDialog = false">取 消</el-button>
					<el-button type="primary" @click="submitClick">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="sortShow" :width="600" destroy-on-close>
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>调整Bom排序及层级</span>
				</div>
			</template>
			<div>
				<el-tree :data="TreeList" node-key="id" default-expand-all draggable>
					<template #default="{ node, data }">
						<span class="custom-tree-node">
							<span>{{ data.materialCode }}-{{ data.materialName }} </span>
						</span>
					</template>
				</el-tree>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="sortShow = false">取 消</el-button>
					<el-button type="primary" @click="sortOk">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="histroyShow" :width="1000" destroy-on-close>
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>Bom历史版本查询</span>
				</div>
			</template>
			<div>
				<el-select v-model="histroyValue" placeholder="请选择" @change="versionChange">
					<el-option v-for="item in histroyList" :label="item.verNo" :value="item.id"> </el-option>
				</el-select>
				<el-table
					:data="bomhistroy"
					id="bomtable"
					style="width: 100%; margin: 10px 0px"
					size="small"
					row-key="id"
					border
					default-expand-all
					:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				>
					<!-- <el-table-column type="index" label="序号" width="55" align="center" /> -->
					<!-- <el-table-column prop="layout" label="层级" show-overflow-tooltip="" /> -->
					<el-table-column prop="materialCode" label="物料编码" width="140" show-overflow-tooltip="" />
					<el-table-column prop="materialName" label="物料名称" width="140" show-overflow-tooltip="" />
					<el-table-column prop="specs" label="规格型号" show-overflow-tooltip="" />
					<el-table-column prop="unitName" label="计量单位名称" show-overflow-tooltip="" />
					<el-table-column prop="purchaseUnitUse" label="采购用量" width="120" show-overflow-tooltip="" />
					<el-table-column prop="unitUse" label="单位用量" width="120" show-overflow-tooltip="" />
					<el-table-column prop="supplyType" label="供应方式" show-overflow-tooltip="">
						<template #default="scope">
							<span v-if="scope.row.supplyType == 1">外协</span>
							<span v-else>自制</span>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>
		<materialDialog title="选择产品" ref="materialDialogRef" :isMore="false" @finish="onChooseFinish"></materialDialog>
	</div>
</template>
<script lang="ts" setup>
import { ref, defineProps, computed, defineExpose, watch, toRefs, onMounted, nextTick, defineEmits } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { FormRules } from 'element-plus';
import { saveBom, getBomList, getVerNos, getVerInfo, approve } from '/@/api/mes/mesProduct.ts';
import materialDialog from '/@/businessComponents/chooseMaterial.vue';
import Sortable from 'sortablejs';
const props = defineProps({
	material: {
		type: Object,
		default: () => {},
	},
});
import { ElLoading } from 'element-plus';
import { deepClone, listToTree } from '/@/utils/other.ts';
const materialDialogRef = ref();
const title = ref('新增');
const ruleForm = ref({});
const TreeList = ref([]);
const isShowDialog = ref(false);

const currentRow = ref<any>(null);
let editRow = {};
let bomList = [];
let intnum = 10000;
const sortShow = ref(false);
const { material } = toRefs(props);

const emits = defineEmits(['versionClick', 'submitAduitAfter']);
const versionClick = () => {
	emits('versionClick', {
		productCode: material.value.materialCode,
		verType: 2,
	});
};
const rules = ref<FormRules>({
	materialCode: [{ required: true, message: '请输入编码！', trigger: 'blur' }],
	unitUse: [{ required: true, message: '请输入单位用量！', trigger: 'blur' }],
	purchaseUnitUse: [{ required: true, message: '请输入采购用量！', trigger: 'blur' }],
});

const histroyShow = ref(false);
const histroyValue = ref('');
const histroyList = ref<any[]>([]);
const bomhistroy = ref<any[]>([]);
const versionChange = (val: any) => {
	console.log(val);
	getVerInfo({
		id: val,
	}).then((res) => {
		console.log(res.data.result);
		const data = res.data.result?.dataJson;
		const bomdata = JSON.parse(data);
		console.log(bomdata);
		bomhistroy.value = listToTree(bomdata?.productBom, 'productBomId', 'pid');
	});
};
const histroyClick = () => {
	getVerNos({
		productCode: material.value.materialCode,
		verType: 2,
		VerNo: 'all',
	}).then((res) => {
		histroyList.value = res.data.result || [];
		histroyShow.value = true;
	});
};

watch(material, () => {
	console.log('change', material);
	getBomData();
});
const changeSort = () => {
	TreeList.value = deepClone(bomData.value);
	sortShow.value = true;
};

const submitAbove = () => {
	ElMessageBox.confirm(`确定要提交审核吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'success',
	})
		.then(async () => {
			const loading = ElLoading.service({
				lock: true,
				text: 'Loading',
				background: 'rgba(255,  255, 255, 0.7)',
			});

			approve({
				productCode: material.value.materialCode,
				type: 0,
			})
				.then((res) => {
					loading.close();
					ElMessage({
						type: 'success',
						message: '提交成功',
					});
					emits('submitAduitAfter');
				})
				.catch(() => {
					loading.close();
				});
		})
		.catch(() => {});
};
const saveData = () => {
	saveBom({
		productCode: material.value.materialCode,
		bomList: bomData.value,
		bomVerNo: material.value.bomVerNo,
	}).then((res) => {
		getBomData();
		ElMessage({
			type: 'success',
			message: '保存完成',
		});
	});
};

const setindexPid = (arr: any[], pid: number) => {
	arr.forEach((row) => {
		intnum = intnum + 1;
		row.id = intnum;
		row.pid = pid;
		if (row.children && row.children.length > 0) {
			setindexPid(row.children, row.id);
		}
	});
};
const sortOk = () => {
	setindexPid(TreeList.value, 0);
	bomData.value = deepClone(TreeList.value);
	sortShow.value = false;
};
// const initSortable = () => {
//     const el1 = document.querySelector('#bomtable .el-table__body tbody')
//     console.log(el1)
//     Sortable.create(el1, {
//         // handle: '.move-icon',
//         onEnd: ({ newIndex, oldIndex }) => {
//             console.log(newIndex, oldIndex)
//             // const arr = state.sewList
//             // const currRow = arr.splice(oldIndex, 1)[0]
//             // arr.splice(newIndex, 0, currRow)
//             // state.sewList = []
//             nextTick(() => {
//                 // state.sewList = arr
//             })
//         }
//     })
// }

// getBomLevel
// watch(bomData, () => {
//     bomList=[];
//     bomData
// })
let initStr = '';
onMounted(() => {
	getBomData();
});
// 产品选择完成
const onChooseFinish = (e: any) => {
	if (e) {
		const data = e;
		ruleForm.value.materialCode = data.materialCode;
		ruleForm.value.materialName = data.materialName;
		ruleForm.value.specs = data.specs;
		ruleForm.value.unitGroupName = data.unitGroupName;
		ruleForm.value.unitName = data.unitName;
	}
};
//打开产品选择页面
const chooseProduct = () => {
	materialDialogRef.value.openDialog({ codes: [] });
};
const getParentRow = (arr: any[], id: number) => {
	let obj = {};
	arr.forEach((row) => {
		if (row.productBomId == id) {
			obj = row;
		} else {
			if (row.children && row.children.length > 0) {
				obj = getParentRow(row.children, id);
			}
		}
	});
	return obj;
};
const vaildChange = () => {
	return initStr != JSON.stringify(bomData.value);
};
const delMesProductBom = (row) => {
	ElMessageBox.confirm(`确定要删除吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			if (row.pid == 0) {
				bomData.value = bomData.value.filter((item) => item.id != row.id);
			} else {
				const pRow = getParentRow(bomData.value, row.pid);
				console.log(pRow);
				pRow.children = pRow.children.filter((item) => item.id != row.id);
			}
		})
		.catch(() => {});
};

const openEditMesProductBom = (row) => {
	editRow = row;
	ruleForm.value = Object.assign({}, row);
	title.value = '编辑';
	isShowDialog.value = true;
};
const addChildrenClick = (row: any) => {
	title.value = '新增';
	ruleForm.value = { purchaseUnitUse: 1, unitUse: 1, supplyType: 0 };
	currentRow.value = row;
	ruleForm.value.pid = row.productBomId;
	isShowDialog.value = true;
};
const addClickPar = () => {
	title.value = '新增';
	ruleForm.value = { purchaseUnitUse: 1, unitUse: 1, supplyType: 0 };
	ruleForm.value.pid = 0;
	isShowDialog.value = true;
};
const ruleFormRef = ref();
const submitClick = () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			if (title.value == '新增') {
				if (ruleForm.value.pid != 0) {
					const obj = Object.assign({}, ruleForm.value);
					let num = currentRow.value.children.length + 1;
					currentRow.value.children.push({
						...obj,
						layout: `${currentRow.value.layout}.${num}`,
						children: [],
						id: new Date().getTime(),
					});
				} else {
					const obj = Object.assign({}, ruleForm.value);
					let num = bomData.value.length + 1;
					bomData.value.push({
						...obj,
						layout: num,
						children: [],
						id: new Date().getTime(),
					});
				}
			} else {
				const obj = Object.assign({}, ruleForm.value);
				for (var i in editRow) {
					editRow[i] = obj[i];
				}
			}
			isShowDialog.value = false;
			console.log(bomData.value);
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: 'error',
			});
		}
	});
};
const bomData = ref<any[]>([]);
const getBomData = () => {
	getBomList({ productCode: material.value.materialCode }).then((res) => {
		const data = res.data.result;
		bomData.value = listToTree(data, 'productBomId', 'pid');
		initStr = JSON.stringify(bomData.value);
	});
};
defineExpose({
	saveData,
	vaildChange,
});
</script>
<style lang="scss">
.approve {
	position: absolute;
	z-index: 100;
	top: 0px;
	right: 250px;
}

.contain_bom {
	width: 100%;
	position: relative;

	.title {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
}
</style>
