<template>
    <!-- 往来单位 新增、编辑 表单组件 -->
    <div>
        <el-form
            label-width="100px"
            size="medium"
            ref="contactUnitsParamsRef"
            :model="storageParams"
            :rules="storageParamsRules"
        >
            <el-form-item label="仓库名称" prop="name">
                <el-input v-model="storageParams.name" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="storageParams.remark" />
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="onSubmit">确定</el-button>
                <el-button
                    @click="
                        () => {
                            this.$emit('closeDialog')
                        }
                    "
                    >取消</el-button
                >
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {
  addStorageListApi,
  updateStorageListApi
} from '@/api/material/storage'
export default {
    name: 'FormStorage',
    props: {
        editParams: {
            type: Object,
            default: () => null,
        },
    },
    mounted() {
        if (this.editParams) {
            Object.assign(this.storageParams, this.editParams)
            this.subSort = 2
        } else {
            this.subSort = 1
        }
    },
    data() {
        return {
            subSort: '', // 提交类型：新增 1 / 修改 2
            storageParams: {
                name: '', // 仓库名称
                remark: '', // 备注
            },
            // 校验规则
            storageParamsRules: {
                name: [
                    {
                        required: true,
                        message: '请输入仓库名称',
                        trigger: 'blur',
                    },
                ],

            },
        }
    },
    methods: {
        /** 确认按钮 */
        onSubmit() {
            this.$refs.contactUnitsParamsRef.validate((valid) => {
                if (valid) {
                    console.log('校验通过', this.storageParams, this.subSort)
                    // 1. 表单校验通过后调后台 Api
                    if(this.subSort === 1) {
                      addStorageListApi(this.storageParams).then(res => {
                        console.log(res)
                        this.$modal.msgSuccess('新增成功')
                      }).catch(err => {})
                    } else if(this.subSort === 2) {
                      updateStorageListApi(this.storageParams).then(res => {
                        console.log(res)
                        this.$modal.msgSuccess('修改成功')
                      }).catch(err => {})
                    }
                    // 2. 成功之后通知父组件关闭弹框
                    this.$emit('closeDialog', true)
                }
            })
        },
    },
}
</script>

<style scoped>
::v-deep .el-select {
    width: 100%;
}
::v-deep .el-form-item__label{
  font-weight: normal;
}
</style>
