<!--
 * @Author: zwq
 * @Date: 2021-11-18 14:16:25
 * @LastEditors: DY
 * @LastEditTime: 2024-04-11 16:44:41
 * @Description:
-->
<template>
	<el-drawer
		:visible.sync="visible"
		:show-close="false"
		:wrapper-closable="true"
		:before-close="beforeClose"
		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="8">
							<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="8">
							<el-form-item label="产品BOM编码" prop="code">
								<el-input v-model="dataForm.code" :disabled="isdetail" placeholder="请输入产品Bom编码" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="备注" prop="remark">
								<el-input v-model="dataForm.remark" :disabled="isdetail" clearable placeholder="请输入备注" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<div class="attr-list" v-if="idAttrShow && this.$auth.hasPermiAnd(['base:material-product-bom:query', 'base:material-product-bom-det:query'])">
				<small-title
					style="margin: 16px 0; padding-left: 8px"
					:no-padding="true">
					BOM明细
				</small-title>

				<div v-if="!isdetail && this.$auth.hasPermi('base:material-product-bom:create')" class="action_btn">
          <template>
            <span style="display: inline-block;">
              <el-button type="text" @click="addNew()" icon="el-icon-plus">添加</el-button>
            </span>
          </template>
        </div>
				<base-table
					:table-props="tableProps"
					:page="listQuery.pageNo"
					:limit="listQuery.pageSize"
					:table-data="tableData">
					<method-btn
						v-if="!isdetail"
						slot="handleBtn"
						:width="90"
						label="操作"
						:method-list="tableBtn"
						@clickBtn="handleClick" />
				</base-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 v-if="!isdetail" class="drawer-body__footer">
				<el-button style="" @click="goback()">取消</el-button>
				<el-button type="primary" @click="dataFormSubmit()">确定</el-button>
			</div>
		</div>

		<attr-add
			v-if="addOrUpdateVisible"
			ref="addOrUpdate"
			:bom-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';
import { publicFormatter } from '@/utils/dict';

// const tableBtn = [
// 	{
// 		type: 'edit',
// 		btnName: '编辑',
// 	},
// 	{
// 		type: 'delete',
// 		btnName: '删除',
// 	},
// ];
const tableProps = [
	{
		prop: 'createTime',
		label: '添加时间',
		filter: parseTime,
	},
	{
		prop: 'materialName',
		label: '物料名称',
	},
	{
		prop: 'materialCode',
		label: '物料编码',
	},
	{
		prop: 'unit',
		label: '单位',
		filter: publicFormatter('unit_dict'),
	},
	{
		prop: 'num',
		label: '数量',
	},
	{
		prop: 'remark',
		label: '备注',
	}
];

export default {
	mixins: [basicAdd],
	components: { SmallTitle, attrAdd },
	data() {
		return {
			tableBtn: [
				this.$auth.hasPermiAnd([
					'base:material-product-bom:update',
					'base:material-product-bom-det:create',
					'base:material-product-bom-det:update'
				]) ?
				{
					type: 'edit',
					btnName: '编辑',
				}
				: undefined,
				this.$auth.hasPermi('base:material-product-bom:delete') ? 
					{
						type: 'delete',
						btnName: '删除',
					}
				: undefined,
			],
			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: [],
			tableData: [],
			unitList: [],
			visible: false,
			isdetail: false,
			idAttrShow: false,
			dataRule: {
        productId: [{ required: true, message: "产品不能为空", trigger: "blur" }]
      }
		};
	},
	mounted() {
		this.getDict()
	},
	methods: {
		beforeClose(done) {
			if (!this.isdetail) {
				this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
			} else {
				done()
			}
		},
		handleClick(raw) {
			if (raw.type === 'delete') {
				this.deleteDetail(raw.data);
			} else {
				this.addNew(raw.data.id);
			}
		},
		// 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (!valid) {
          return false;
        }
        // 修改的提交
        if (this.dataForm.id) {
          this.urlOptions.updateURL(this.dataForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.visible = false; 
            this.$emit("refreshDataList");
          });
          return;
        }
        // 添加的提交
        this.urlOptions.createURL(this.dataForm).then(response => {
          this.$modal.msgSuccess("新增成功");
          // this.visible = false;
					this.idAttrShow = true;
					this.dataForm.id = response.data
          this.$emit("refreshDataList");
        });
      });
    },
		async getDict() {
			// 产品列表
			const proRes = await getProList();
			this.productList = proRes.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.tableData.splice(0);
			this.listQuery.total = 0;
		},
		deleteDetail(raw) {
			this.$confirm(
				`是否确认删除物料名称为"${raw.materialName}"的数据项?`,
				'提示',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
				.then(() => {
					deleteMaterialPBDet(raw.id).then(({ data }) => {
						this.$message({
							message: '操作成功',
							type: 'success',
							duration: 1500,
							onClose: () => {
								this.getList();
							},
						});
					});
				})
				.catch(() => {});
		},
		getList() {
			// 获取产品Bom详细列表
			getProBomList({
				...this.listQuery,
				bomId: this.dataForm.id
			}).then((response) => {
				this.tableData = response.data.records
				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: 20vh;
	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;
}
.action_btn {
  float: right;
  margin: -40px 15px;
  font-size: 14px;
}
.add {
	color: #0b58ff;
}
</style>
