<template>
  <el-dialog
    :title="`训练消耗指标数据 - ${operateTypeName}`"
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    width="35%"
    @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="12">
          <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="12">
          <el-form-item label="指标名称" prop="name">
            <el-input
              v-model="form.name"
              clearable
              disabled
              placeholder="请输入指标名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="指标总数量" prop="allNumber">
            <el-input
              v-model.number="form.allNumber"
              clearable
              disabled
              placeholder="请输入指标总数量"
              type="number"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="`${operateTypeName}数量`" prop="number">
            <el-input
              v-model.number="form.number"
              :placeholder="`请输入${operateTypeName}数量`"
              clearable
              type="number"
            ></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">
        {{
          operateTypeName
            .split('')
            .map(i => `${i} `)
            .join('')
        }}
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>
</template>

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

export default {
  name: 'InboundOutboundDialog',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const validateNumber = (rule, value, callback) => {
      const {allNumber = 0} = this.form

      if (!value) {
        callback(new Error(`${this.operateTypeName}数量不能为空`))
      } else if (!(Number.isInteger(+value) && +value > 0)) {
        callback(new Error(`${this.operateTypeName}数量需为大于0的正整数`))
      } else if (this.operateType === '2' && value > allNumber) {
        callback(new Error(`${this.operateTypeName}数量需小于等于指标总数量`))
      } else {
        callback()
      }
    }

    return {
      rules: {
        number: [
          {
            required: true,
            trigger: 'blur',
            validator: validateNumber
          }
        ]
      },
      form: {},
      saveLoading: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.rowInfo?.id || ''
    },
    operateType() {
      return this.rowInfo?.operateType || ''
    },
    operateTypeName() {
      return dictionaryEscape('crklx', this.operateType)
    }
  },
  created() {},
  methods: {
    dictionaryEscape,
    // 打开弹层
    open() {
      if (this.id) {
        this.saveLoading = true
        this.getDetail(this.id)
      }
    },

    // 关闭弹层后
    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 {number: allNumber = 0, ...form} = await api.tableDetail(id)
        this.form = {...form, allNumber, number: 0}
      } 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 {number = 0} = this.form
          const {id: indexId, operateType} = this

          try {
            const {state} = await api.inboundAndOutbound({
              number,
              indexId,
              operateType
            })

            if (state) {
              this.$emit('submit', 'inboundOutbound')
              this.$message.success(
                `训练消耗指标数据${this.operateTypeName}成功`
              )
              this.dialogVisible = false
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    }
  }
}
</script>

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