<!--
 * @Author: zwq
 * @Date: 2021-11-18 14:16:25
 * @LastEditors: zwq
 * @LastEditTime: 2024-07-09 13:40:03
 * @Description:
-->
<template>
  <el-drawer :visible.sync="visible" :show-close="false" :wrapper-closable="false" class="drawer" size="50%">
    <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="equipmentId">
                <el-select v-model="dataForm.equipmentId" filterable :disabled="isdetail" style="width: 100%"
                  @change="getCode" placeholder="请选择设备名称">
                  <el-option v-for="dict in equipmentList" :key=" dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备编码" prop="equipmentCode">
                <el-input v-model="dataForm.equipmentCode" clearable :disabled="isdetail" placeholder="请输入设备编码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备Bom编码" prop="code">
                <el-input v-model="dataForm.code" clearable :disabled="isdetail" placeholder="请输入设备Bom编码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备物料BOM名称" prop="name">
                <el-input v-model="dataForm.name" clearable :disabled="isdetail" placeholder="请输入设备物料BOM名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="当前状态" prop="enabled">
                <el-switch v-model="dataForm.enabled" :active-value="1" :inactive-value="0" />
              </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 v-if="!isdetail" class="drawer-body__footer">
        <el-button style="" @click="goback()">取消</el-button>
        <el-button v-if="isdetail" type="primary" @click="goEdit()">
          编辑
        </el-button>
        <el-button v-else type="primary" @click="dataFormSubmit()">确定</el-button>
      </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="productAttrList">
          <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 class="drawer-body__footer">
          <el-button type="primary" @click="goback()">关闭</el-button>
        </div>
      </div>

    </div>

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

<script>
import basicAdd from '../../core/mixins/basic-add';
import {
  getProcessEquMaterialBom,
  createProcessEquMaterialBom,
  updateProcessEquMaterialBom,
  getEquipmentList,
  processEquMaterialBomDetPage,
  deleteProcessEquMaterialBomDet,
  getMaterialCode
} from '@/api/extend/processEquMaterialBom';
import SmallTitle from './SmallTitle';
import { parseTime } from '../../core/mixins/code-filter';
import attrAdd from './attr-add';
// import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import { publicFormatter } from '@/utils/dict';
const tableBtn = [
	{
		type: 'edit',
		btnName: '编辑',
	},
	{
		type: 'delete',
		btnName: '删除',
	},
];
const tableProps = [
	{
    prop: 'materialName',
		label: '物料名称',
	},
	{
    prop: 'materialCode',
    label: '物料编码',
	},
	{
    prop: 'unit',
    label: '单位',
    filter: publicFormatter('unit_dict')
  },
  {
    prop: 'num',
    label: '数量',
  },
  {
    prop: 'remark',
    label: '备注',
  },
];

const topBtnConfig = [
  {
    type: 'add',
    btnName: 'btn.add'
  }
]

export default {
	mixins: [basicAdd],
	components: { SmallTitle, attrAdd },
	data() {
		return {
			tableBtn,
			tableProps,
			topBtnConfig,
			addOrUpdateVisible: false,
			urlOptions: {
			  isGetCode: false,
        // codeURL: getCode,
        createURL:createProcessEquMaterialBom,
        updateURL: updateProcessEquMaterialBom,
        infoURL: getProcessEquMaterialBom,
			},
			listQuery: {
				pageSize: 10,
				pageNo: 1,
				total: 0,
      },
      equipmentList:[],
			dataForm: {
        id: undefined,
        code: undefined,
        name: '',
				equipmentId: undefined,
        equipmentCode: undefined,
        enabled:1,
        // area: undefined,
				// specifications: undefined,
				// processTime: 0,
        remark: undefined,
				// unit: undefined
			},
			productAttrList: [],
			visible: false,
			isdetail: false,
			idAttrShow: false,
			dataRule: {
        // code: [{ required: true, message: "设备物料编码不能为空", trigger: "blur" }],
        name: [{ required: true, message: "设备物料名称不能为空", trigger: "blur" }],
				equipmentId: [{ required: true, message: "设备名称不能为空", trigger: "change" }],
				// : [{ required: true, message: "产品类型不能为空", trigger: "change" }],
				// processTime: [{ required: true, message: "产线生产单位用时不能为空", trigger: "blur" }]
      }
		};
	},
  mounted() {
  },
  methods: {
    getCode(val) {
      this.equipmentList.forEach((ele) => {
        if (val === ele.id) {
          this.dataForm.equipmentCode = ele.code
        }
      })
    },
    // clickTopBtn(val) {
    //   if (val === 'add') {
    //     this.addNew()
    //   }
    // },
		initData() {
			this.productAttrList.splice(0);
			this.listQuery.total = 0;
    },
    getDict() {
      getEquipmentList().then((res) => {

        // console.log(res);
        // console.log(response);
        this.equipmentList = res.data
      })
      getMaterialCode().then(res => {
        this.dataForm.code = res.data
      })
    },
		handleClick(raw) {
			if (raw.type === 'delete') {
				this.$confirm(
					`确定对${
          raw.data.materialName
            ? '[物料名称为' + raw.data.materialName + ']'
            : '[序号为' + raw.data.materialName + ']'
					}进行删除操作?`,
					'提示',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					}
				)
					.then(() => {
            deleteProcessEquMaterialBomDet(raw.data.id).then(({ data }) => {
							this.$message({
								message: '操作成功',
								type: 'success',
								duration: 1500,
								onClose: () => {
									this.getList();
								},
							});
						});
					})
					.catch(() => {});
			} else {
				this.addNew(raw.data.id);
			}
		},
		getList() {
			// 获取产品属性列表
      processEquMaterialBomDetPage({
				...this.listQuery,
				bomId: this.dataForm.id,
			}).then((response) => {
				this.productAttrList = response.data.list;
				this.listQuery.total = response.data.total;
			});
		},
		init(id, isdetail) {
      this.initData()
      this.getDict()
			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({
            bomId: id,
            pageNo: 1,
            pageSize:10
          }).then(response => {
            this.dataForm = response.data
						this.dataForm.unit = String(this.dataForm.unit)
						this.dataForm.materialType = String(this.dataForm.materialType)
						this.dataForm.productType = String(this.dataForm.productType)
          });
					// 获取产品属性列表
					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,this.dataForm.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: 5px 15px;
  font-size: 14px;
}
.add {
	color: #0b58ff;
}
</style>
