<template>
  <el-dialog
    :title="`${id ? '编辑' : '新增'} - 训练消耗指标数据`"
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    width="60%"
    @closed="closed"
    @open="open"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="top"
      label-width="auto"
    >
      <el-row :gutter="24" style="flex-wrap:wrap" type="flex">
        <el-col :span="6">
          <el-form-item label="责任单位" prop="orgName">
            <el-input
              v-model="form.orgName"
              clearable
              disabled
              placeholder="请输入责任单位"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="指标名称" prop="name">
            <el-input
              v-model="form.name"
              clearable
              placeholder="请输入指标名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="指标类型" prop="type">
            <el-select
              v-model="form.type"
              clearable
              placeholder="请选择指标类型"
              style="width: 100%;"
            >
              <el-option
                v-for="item in getDictionaryByCode('zb_type')"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="!id" :span="6">
          <el-form-item label="数量" prop="number">
            <el-input
              v-model.number="form.number"
              clearable
              placeholder="请输入数量"
              type="number"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计量单位" prop="unit">
            <el-select
              v-model="form.unit"
              clearable
              placeholder="请选择计量单位"
              style="width: 100%;"
            >
              <el-option
                v-for="item in getDictionaryByCode('jldw')"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item label="仓库位置" prop="warehouseLocation">
            <el-input
              v-model="form.warehouseLocation"
              clearable
              placeholder="请输入仓库位置"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="memo">
            <el-input
              v-model="form.memo"
              :autosize="{minRows: 1, maxRows: 3}"
              clearable
              placeholder="请输入备注"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        确 认
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as api from '@/api/examDataMenu/examSafeguardData/examIndexData.js'
import {getDictionaryByCode} from '@/utils/dictionary'

export default {
  name: 'AddEditDialog',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowInfo: {
      type: Object,
      default: () => ({})
    },
    activeTreeItem: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const validateNumber = (rule, value, callback) => {
      if (typeof value === 'string' && !value) {
        callback(new Error(`数量不能为空`))
      } else if (!Number.isInteger(+value)) {
        callback(new Error(`数量需为正整数`))
      } else {
        callback()
      }
    }

    return {
      rules: {
        name: [{required: true, message: '指标名称不能为空', trigger: 'blur'}],
        number: [{required: true, validator: validateNumber, trigger: 'blur'}],
        orgName: [
          {required: true, message: '责任单位不能为空', trigger: 'change'}
        ],
        type: [{required: true, message: '指标类型不能为空', trigger: 'change'}]
      },
      form: {
        orgName: '',
        orgId: '',
        type: '1',
        unit: '个',
        number: 0
      },
      saveLoading: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.rowInfo?.id || ''
    }
  },
  created() {},
  methods: {
    getDictionaryByCode,
    // 打开弹层
    open() {
      if (this.id) {
        this.saveLoading = true
        this.getDetail(this.id)
      } else {
        const {name: orgName = '', id: orgId = ''} = this.activeTreeItem
        this.form = {...this.form, orgName, orgId}
      }
    },

    // 关闭弹层后
    closed() {
      const {rules} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {rules})

      this.$nextTick(_ => {
        this.$refs.form.$el.scrollTop = 0
        this.$refs.form.clearValidate()
      })
    },

    // 获取详情
    async getDetail(id) {
      try {
        const {...form} = await api.tableDetail(id)
        this.form = {...form}
      } finally {
        this.saveLoading = false
      }
    },

    // 保存
    handleSave() {
      this.$refs.form.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          const myInterFace = this.id ? api.tableEdit : api.tableAdd

          const {...addEditForm} = this.form

          try {
            let {state, message} = await myInterFace({...addEditForm})

            if (state) {
              this.$emit('submit', this.id ? 'edit' : 'add')
              message = this.id ? '编辑' : '新增'
              this.$message.success(`训练消耗指标数据${message}成功`)
              this.dialogVisible = false
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
