<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="fmRate">
        <el-input v-model="formData.fmRate"></el-input>
      </el-form-item>
      <el-form-item label="合格率区间到(小于)" prop="toRate">
        <el-input v-model="formData.toRate"></el-input>
      </el-form-item>
      <el-form-item label="质检处理建议" prop="qcSuggest">
        <el-select v-model="formData.qcSuggest">
          <template v-for="item in $keys.strategy.qcRules.qcSuggest">
            <el-option :key="item.id" :label="item.name" :value="item.key"></el-option>
          </template>
        </el-select>
      </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="50410010210" type="primary" @click="save">确认</el-button>
    <el-button v-auth="50410010211" 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: {
        // formData写在 computed 就不能识别校验, 导致校验始终不通过
        fmRate: [{ required: true, message: '必填', trigger: 'change' }],
        toRate: [{ required: true, message: '必填', trigger: 'change' }],
        qcSuggest: [{ required: true, message: '必选', trigger: 'change' }],
      },
    }
  },
  methods: {
    // 重置, 若只使用form的resetField, 当表单为prop传过来详情时会重置为详情数据而不是置空
    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>
