<!--
 * @Author: zwq
 * @Date: 2021-11-18 14:16:25
 * @LastEditors: DY
 * @LastEditTime: 2024-03-21 15:21:32
 * @Description:
-->
<template>
	<el-drawer
		:visible.sync="visible"
		:show-close="false"
		:wrapper-closable="true"
		:before-close="beforeClose"
		class="drawer"
		size="60%">
		<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="code">
								<el-input
									v-model="dataForm.code"
									clearable
									:disabled="isdetail"
									placeholder="请输入物料编码" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="物料名称" prop="name">
								<el-input v-model="dataForm.name" :disabled="isdetail" clearable placeholder="请输入物料名称" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="英文名称" prop="engName">
								<el-input
									v-model="dataForm.engName"
									clearable
									:disabled="isdetail"
									placeholder="请输入英文名称" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="物料类型" prop="type">
								<el-select
									v-model="dataForm.type"
									filterable
									:disabled="isdetail"
									style="width: 100%"
									placeholder="请选择物料类型">
									<el-option
										v-for="dict in getDictDatas('material_type')"
										:key="dict.value"
										:label="dict.label"
										:value="dict.value" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="规格" prop="spec">
								<el-input
									v-model="dataForm.spec"
									clearable
									:disabled="isdetail"
									placeholder="请输入规格" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="供应商" prop="supplierId">
								<el-select
									v-model="dataForm.supplierId"
									filterable
									clearable
									:disabled="isdetail"
									style="width: 100%"
									placeholder="请选择供应商">
									<el-option
										v-for="dict in supplierList"
										:key="dict.id"
										:label="dict.name"
										:value="dict.id" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="单位" prop="unit">
								<el-select
									v-model="dataForm.unit"
									filterable
									:disabled="isdetail"
									style="width: 100%"
									placeholder="请选择物料单位">
									<el-option
										v-for="dict in getDictDatas('unit_dict')"
										:key="dict.value"
										:label="dict.label"
										:value="dict.value" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<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">
				<small-title
					style="margin: 16px 0; padding-left: 8px"
					:no-padding="true">
					物料属性
				</small-title>

				<div v-if="!isdetail" 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="materialAttrList">
					<method-btn
						v-if="!isdetail"
						slot="handleBtn"
						:width="120"
						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"
			:material-id="dataForm.id"
			@refreshDataList="getList" />
	</el-drawer>
</template>

<script>
import basicAdd from '../../core/mixins/basic-add';
import { createMaterial, updateMaterial, getMaterial, getCode, getSupplierList, getMaterialAttrList, deleteMaterialAttr } from "@/api/base/material";
import { listData } from "@/api/system/dict/data";
import SmallTitle from './SmallTitle';
import { parseTime } from '../../core/mixins/code-filter';
import attrAdd from './attr-add';
import { getDictDatas } from "@/utils/dict";

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, attrAdd },
	data() {
		return {
			tableBtn,
			tableProps,
			addOrUpdateVisible: false,
			urlOptions: {
			  isGetCode: true,
        codeURL: getCode,
				createURL: createMaterial,
				updateURL: updateMaterial,
				infoURL: getMaterial,
			},
			listQuery: {
				pageSize: 10,
				pageNo: 1,
				total: 0,
			},
			dataForm: {
        id: undefined,
        code: undefined,
        name: '',
				engName: '',
				type: '',
        spec: undefined,
				supplierId: undefined,
        remark: undefined,
				unit: ''
			},
			// materialList: [],
			supplierList: [],
			materialAttrList: [],
			unitList: [],
			visible: false,
			isdetail: false,
			idAttrShow: false,
			dataRule: {
        code: [{ required: true, message: "物料编码不能为空", trigger: "blur" }],
        name: [{ required: true, message: "物料名称不能为空", trigger: "blur" }],
				type: [{ required: true, message: "物料类型不能为空", trigger: "blur" }]
      }
		};
	},
	mounted() {
		this.getDict()
	},
	methods: {
		beforeClose(done) {
			if (!this.isdetail) {
				this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
			} else {
				done()
			}
		},
		async getDict() {
			// 物料类型列表
			// const res = await listData({
			// 	pageNo: 1,
      //   pageSize: 99,
      //   dictType: 'material_type',
			// });
			// this.materialList = res.data.list
			// this.materialList = res.data.list.map(item => {
			// 	return {
			// 		label: item.label,
			// 		value: Number(item.value)
			// 	}
			// });
			// 供应商列表
			const supplierRes = await getSupplierList();
			this.supplierList = supplierRes.data;
			// 物料单位列表
			// const unitRes = await listData({
			// 	pageNo: 1,
      //   pageSize: 99,
      //   dictType: 'goods_unit',
			// });
			// this.unitList = unitRes.data.list.map(item => {
			// 	return {
			// 		label: item.label,
			// 		value: Number(item.value)
			// 	}
			// });
		},
		initData() {
			this.materialAttrList.splice(0);
			this.listQuery.total = 0;
		},
		handleClick(raw) {
			if (raw.type === 'delete') {
				this.$confirm(
					`是否确认删除属性名为"${raw.data.attrName}"的数据项?`,
					'提示',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					}
				)
					.then(() => {
						deleteMaterialAttr(raw.data.id).then(({ data }) => {
							this.$message({
								message: '操作成功',
								type: 'success',
								duration: 1500,
								onClose: () => {
									this.getList();
								},
							});
						});
					})
					.catch(() => {});
			} else {
				this.addNew(raw.data.id);
			}
		},
		getList() {
			// 获取物料的属性列表
			getMaterialAttrList({
				...this.listQuery,
				materialId: this.dataForm.id,
			}).then((response) => {
				this.materialAttrList = response.data.list;
				this.listQuery.total = response.data.total;
			});
		},
		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;
						if (this.dataForm.unit) {
							this.dataForm.unit = String(this.dataForm.unit)
						}
						if (this.dataForm.type) {
							this.dataForm.type = String(this.dataForm.type)
						}
          });
					// 获取物料的属性列表
					this.getList();
				} else {
					if (this.urlOptions.isGetCode) {
            this.getCode()
          }
				}
			});
		},
		// 表单提交
    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.idAttrShow = true
					this.dataForm.id = response.data
          this.$emit("refreshDataList");
        });
      });
    },
		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: 76vh;
	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>
