<!--
 * @Author: zwq
 * @Date: 2021-11-18 14:16:25
 * @LastEditors: DY
 * @LastEditTime: 2023-11-22 11:09:44
 * @Description:
-->
<template>
	<el-drawer
		:visible.sync="visible"
		:show-close="false"
		:wrapper-closable="false"
		class="drawer"
		size="70%">
		<small-title slot="title" :no-padding="true">
			{{ isdetail ? '详情' : !dataForm.id ? '新增' : '编辑' }}
		</small-title>
		<div class="content">
			<div class="visual-part">
				<el-form
					:model="dataForm"
					:rules="dataRule"
					ref="dataForm"
					@keyup.enter.native="dataFormSubmit()"
					label-width="100px"
					label-position="top">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="产品名称" prop="productId">
								<el-select
									v-model="dataForm.productId"
									filterable
									clearable
									:disabled="isdetail"
									style="width: 100%"
									placeholder="请选择产品">
									<el-option
										v-for="dict in productList"
										:key="dict.id"
										:label="dict.name"
										:value="dict.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="产品BOM编码" prop="code">
								<el-input v-model="dataForm.code" :disabled="isdetail" placeholder="请输入产品Bom编码" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="备注" prop="remark">
						<el-input v-model="dataForm.remark" :disabled="isdetail" clearable placeholder="请输入备注" />
					</el-form-item>
				</el-form>
			</div>
			<div class="attr-list" v-if="idAttrShow">
				<small-title
					style="margin: 16px 0; padding-left: 8px"
					:no-padding="true">
					BOM明细
				</small-title>

				<!-- <base-table
					:table-props="tableProps"
					:page="listQuery.pageNo"
					:limit="listQuery.pageSize"
					:add-button-show="isdetail ? null : '添加属性'"
					@emitButtonClick="addNew()"
					:table-data="materialAttrList">
					<method-btn
						v-if="!isdetail"
						slot="handleBtn"
						:width="120"
						label="操作"
						:method-list="tableBtn"
						@clickBtn="handleClick" />
				</base-table> -->
				<el-button v-show="!isdetail" type="success" size="small" style="float: right" @click="addRow()">添加一行</el-button>
				<el-table
					:data="tableData"
      		style="width: 100%">
					<el-table-column type="index" label="序号" />
					<el-table-column prop="createTime" label="添加时间">
						<template slot-scope="scope">
							<span>{{ parseTime(scope.row.createTime) }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="materialId" label="物料名称">
						<template slot-scope="scope">
							<el-select
									v-model="scope.row.materialId"
									filterable
									clearable
									:disabled="!scope.row.isEdit"
									placeholder="请选择物料"
									@change="setCode(scope.row)">
									<el-option
										v-for="dict in materialList"
										:key="dict.id"
										:label="dict.name"
										:value="dict.id" />
								</el-select>
						</template>
					</el-table-column>
					<el-table-column prop="materialCode" label="物料编码" />
					<el-table-column prop="mUnit" label="单位" />
					<el-table-column prop="num" label="数量">
						<template slot-scope="scope">
							<el-input v-model="scope.row.num" :disabled="!scope.row.isEdit"></el-input>
						</template>
					</el-table-column>
					<el-table-column prop="remark" label="备注">
						<template slot-scope="scope">
							<el-input v-model="scope.row.remark" :disabled="!scope.row.isEdit"></el-input>
						</template>
					</el-table-column>
					<el-table-column v-if="!isdetail" label="操作">
						<template slot-scope="scope">
							<el-tooltip v-if="!scope.row.isEdit" placement="top" content="编辑">
								<el-button
									type="text"
									:style="{color:'#0B58FF'}"
									size="mini"
									@click="edit(scope.row)"
								>
									<!-- 此处的icon的名字命名为'table_'加上按钮的type -->
									<svg-icon style="width: 18px; height: 18px" class="item-icon" icon-class="edit" />
									<!-- <span>{{ item.btnName | i18nFilter }}</span> -->
								</el-button>
							</el-tooltip>
							<el-button v-else type="text" size="small" @click="saveData(scope.row)">保存</el-button>
							<el-tooltip placement="top" content="删除">
								<el-button
									type="text"
									:style="{color:'#FF5454'}"
									size="mini"
									@click="deleteDetail(scope.row)"
								>
									<!-- 此处的icon的名字命名为'table_'加上按钮的type -->
									<svg-icon style="width: 18px; height: 18px" class="item-icon" icon-class="table_delete" />
									<!-- <span>{{ item.btnName | i18nFilter }}</span> -->
								</el-button>
							</el-tooltip>
						</template>
					</el-table-column>
				</el-table>
				<pagination
					v-show="listQuery.total > 0"
					:total="listQuery.total"
					:page.sync="listQuery.pageNo"
					:limit.sync="listQuery.pageSize"
					:page-sizes="[5, 10, 15]"
					@pagination="getList" />
			</div>

			<div class="drawer-body__footer">
				<el-button style="" @click="goback()">{{ isdetail ? '关闭' : '取消' }}</el-button>
				<!-- <el-button v-if="isdetail" type="primary" @click="goEdit()">
					编辑
				</el-button> -->
				<el-button v-if="!isdetail" type="primary" @click="dataFormSubmit()">确定</el-button>
			</div>
		</div>

		<!-- <attr-add
			v-if="addOrUpdateVisible"
			ref="addOrUpdate"
			:material-id="dataForm.id"
			@refreshDataList="getList" /> -->
	</el-drawer>
</template>

<script>
import basicAdd from '../../core/mixins/basic-add';
import { createMaterialPB, updateMaterialPB, getMaterialPB, getCode, getProList, getProBomList, createMaterialPBDet, updateMaterialPBDet, deleteMaterialPBDet } from "@/api/base/materialProductBom";
import { getMaterialList } from "@/api/base/material";
import { listData } from "@/api/system/dict/data";
import SmallTitle from '../material/SmallTitle';
import { parseTime } from '../../core/mixins/code-filter';
// import attrAdd from './attr-add';

const tableBtn = [
	{
		type: 'edit',
		btnName: '编辑',
	},
	{
		type: 'delete',
		btnName: '删除',
	},
];
const tableProps = [
	{
		prop: 'createTime',
		label: '添加时间',
		filter: parseTime,
	},
	{
		prop: 'attrName',
		label: '属性名',
	},
	{
		prop: 'attrValue',
		label: '属性值',
	},
];

export default {
	mixins: [basicAdd],
	components: { SmallTitle },
	data() {
		return {
			tableBtn,
			tableProps,
			addOrUpdateVisible: false,
			urlOptions: {
			  isGetCode: true,
        codeURL: getCode,
				createURL: createMaterialPB,
				updateURL: updateMaterialPB,
				infoURL: getMaterialPB,
			},
			listQuery: {
				pageSize: 10,
				pageNo: 1,
				total: 0,
			},
			dataForm: {
        id: undefined,
        code: undefined,
        productId: '',
        remark: undefined,
			},
			productList: [],
			materialAttrList: [],
			materialList: [],
			tableData: [],
			unitList: [],
			visible: false,
			isdetail: false,
			idAttrShow: false,
			dataRule: {
        productId: [{ required: true, message: "产品不能为空", trigger: "blur" }]
      }
		};
	},
	mounted() {
		this.getDict()
	},
	methods: {
		async getDict() {
			// 产品列表
			const proRes = await getProList();
			this.productList = proRes.data;
			// 物料列表
			const res = await getMaterialList();
			this.materialList = res.data;
			// 物料单位列表
			const unitRes = await listData({
				pageNo: 1,
        pageSize: 99,
        dictType: 'unit_dict',
			});
			this.unitList = unitRes.data.list.map(item => {
				return {
					label: item.label,
					value: Number(item.value)
				}
			});
		},
		initData() {
			// this.materialAttrList.splice(0);
			this.listQuery.total = 0;
		},
		deleteDetail(raw) {
			this.$confirm(
				`确定删除关于物料编码为${
					raw.materialCode}的数据?`,
				'提示',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
				.then(() => {
					deleteMaterialPBDet(raw.id).then(({ data }) => {
						this.$message({
							message: '操作成功',
							type: 'success',
							duration: 1500,
							onClose: () => {
								this.getList();
							},
						});
					});
				})
				.catch(() => {});
		},
		setCode(row) {
			const tempM = this.materialList.filter(item => {
				if (row.materialId === item.id) {
					row.materialCode = item.code
				}
				return row.materialId === item.id
			})
			if (tempM[0].unit) {
				this.unitList.filter(u => {
					if (tempM[0].unit === u.value) {
						row.unit = u.value
						row.mUnit = u.label
					}
				})
			}
			// row.materialCode = tempList[0].code
			// row.unit = tempList[0].unit
		},
		edit(row) {
			row.isEdit = true
		},
		saveData(row) {
			// this.$refs['dataForm'].validate((valid) => {
				// if (valid) {
				// 	修改的提交
				if (row.id) {
					updateMaterialPBDet({
						...row
					}).then((response) => {
						this.$modal.msgSuccess('修改成功');
						// this.visible = false;
						this.getList();
					});
					return;
				}
					// 添加的提交
			createMaterialPBDet({
				...row
			}).then((response) => {
				this.$modal.msgSuccess('新增成功');
				// this.visible = false;
				this.getList();
			});
				// }
			// });
		},
		getList() {
			// 获取产品Bom详细列表
			getProBomList({
				...this.listQuery,
				bomId: this.dataForm.id
			}).then((response) => {
				this.tableData = response.data.records.map(item => {
					this.unitList.filter(u => {
						if (item.unit === u.value) {
							item.mUnit = u.label
						}
					})
					item.isEdit = false
					return item
				});
				this.listQuery.total = response.data.total;
			});
		},
		// 构造一行
		addRow() {
			const row = {
				bomId: this.dataForm.id,
				materialId: '',
				num: 0,
				materialCode: undefined,
				unit: undefined,
				remark: '',
				isEdit: true
			}
			this.tableData.push(row)
		},
		init(id, isdetail) {
			this.initData();
			this.isdetail = isdetail || false;
			this.dataForm.id = id || undefined;
			this.visible = true;
			if (id) {
				this.idAttrShow = true
			} else {
				this.idAttrShow = false
			}

			this.$nextTick(() => {
				this.$refs['dataForm'].resetFields();

				if (this.dataForm.id) {
					// 获取物料详情
					this.urlOptions.infoURL(id).then(response => {
            this.dataForm = response.data;
          });
					// 获取Bom明细
					this.getList();
				} else {
					if (this.urlOptions.isGetCode) {
            this.getCode()
          }
				}
			});
		},
		goback() {
			this.$emit('refreshDataList');
			this.visible = false;
			// this.initData();
		},
		goEdit() {
			this.isdetail = false;
		},
		// 新增 / 修改
		addNew(id) {
			this.addOrUpdateVisible = true;
			this.$nextTick(() => {
				this.$refs.addOrUpdate.init(id);
			});
		}
	}
};
</script>
<style scoped>
.drawer >>> .el-drawer {
	border-radius: 8px 0 0 8px;
	display: flex;
	flex-direction: column;
}

.drawer >>> .el-form-item__label {
	padding: 0;
}

.drawer >>> .el-drawer__header {
	margin: 0;
	padding: 32px 32px 24px;
	border-bottom: 1px solid #dcdfe6;
}
.drawer >>> .el-drawer__body {
	flex: 1;
	height: 1px;
	display: flex;
	flex-direction: column;
}

.drawer >>> .content {
	padding: 30px 24px;
	flex: 1;
	display: flex;
	flex-direction: column;
	/* height: 100%; */
}

.drawer >>> .visual-part {
	flex: 1 auto;
	max-height: 30vh;
	overflow: hidden;
	overflow-y: scroll;
	padding-right: 10px; /* 调整滚动条样式 */
}

.drawer >>> .el-form,
.drawer >>> .attr-list {
	padding: 0 16px;
}

.drawer-body__footer {
	display: flex;
	justify-content: flex-end;
	padding: 18px;
}
</style>
