<template>
<el-dialog
  class="creator"
  title="质检项明细"
  width="70%"
  :visible="showCreator"
  @close="close"
>
  <div class="creator__body">
    <el-form
      inline
      ref="form"
      label-position="top"
      :model="formData"
      :rules="rules"
    >
      <el-form-item label="质检项名称" prop="qcItem">
        <el-input v-model="formData.qcItem"></el-input>
      </el-form-item>
      <el-form-item label="质检方式" prop="qcWay">
        <el-select v-model="formData.qcWay">
          <template v-for="item in $keys.warehouseBasic.qcItems.qcWay">
            <el-option :key="item.id" :label="item.name" :value="item.key"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="质检参考标准" prop="qcRef">
        <el-input v-model="formData.qcRef"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark"></el-input>
      </el-form-item>
    </el-form>
  </div>
  <div class="creator__foot">
    <el-button v-auth="50300030206" type="primary" @click="save">确认</el-button>
    <el-button v-auth="50300030207" type="primary" @click="saveAndCreate">确认并添加</el-button>
  </div>
</el-dialog>
</template>

<script>
export default {
  props: ['showCreator', 'detailData', 'selectedIndex'],
  watch: {
    detailData: {
      immediate: true,
      handler (val) {
        this.formData = { ...val }
      }
    },
  },
  computed: {
    // 父组件选择的行index
    computedIndex () {
      return this.selectedIndex !== undefined ? this.selectedIndex : this.index
    },
  },

  data () {
    return {
      index: undefined,
      // 表单对象
      formData: {},
      // 表单验证
      rules: {
        qcItem: [{ required: true, message: '必填', trigger: 'change' }],
      },
    }
  },
  methods: {
    // 重置
    reset () {
      this.$refs.form.resetFields() // 单纯是为了清空校验
    },
    // 保存
    save () {
      this.saveAndCreate('needClose')
    },
    // 关闭
    close () {
      this.$emit('close')
    },
    // 保存并新增
    saveAndCreate (needClose) {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$emit('createDone', { ...this.formData }, this.computedIndex) // 通知父组件新增完毕, 刷新列表
          if (needClose === 'needClose') {
            this.close()
          } else {
            this.index = undefined // 防止继续新增改掉之前的数据
          }
          this.reset()
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
  .el-collapse-item {
    margin-bottom: 20px;
  }
  .creator__foot {
    margin-top: 20px;
  }
</style>
