<template>
  <el-dialog
    :title="`训练消耗器材数据 - ${statusName}`"
    :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="totalNum">
            <el-input
              v-model.number="form.totalNum"
              clearable
              disabled
              placeholder="请输入器材总数量"
              type="number"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="`${statusName}人员`" prop="userId">
            <el-select
              v-model="form.userId"
              :placeholder="`请选择${statusName}人员`"
              clearable
              filterable
              style="width: 100%;"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.fullname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="`${statusName}数量`" prop="num">
            <el-input
              v-model.number="form.num"
              :placeholder="`请输入${statusName}数量`"
              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">
        {{
          statusName
            .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/trainEquipmentData'
import {dictionaryEscape} from '@/utils/dictionary'
import {getOrgUserQuery} from '@/api/systemInterface'
import {refineRequestBody} from '@/utils/requestWrappers'

export default {
  name: 'BorrowingReturningDialog',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const validateNumber = (rule, value, callback) => {
      const {totalNum = 0} = this.form
      if (!value) {
        callback(new Error(`${this.statusName}数量不能为空`))
      } else if (!(Number.isInteger(+value) && +value > 0)) {
        callback(new Error(`${this.statusName}数量需为大于0的正整数`))
      } else if (this.status === '0' && value > totalNum) {
        callback(new Error(`${this.statusName}数量需小于等于器材总数量`))
      } else {
        callback()
      }
    }

    return {
      rules: {
        num: [{required: true, trigger: 'blur', validator: validateNumber}],
        userId: [
          {
            required: true,
            message: `${this.statusName}不能为空`,
            trigger: 'change'
          }
        ]
      },
      form: {},
      saveLoading: false,
      userList: []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.rowInfo?.id || ''
    },
    status() {
      return this.rowInfo?.status || ''
    },
    statusName() {
      return dictionaryEscape('xlqcjcghzt', this.status)
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    dictionaryEscape,
    // 打开弹层
    open() {
      if (this.id) {
        this.saveLoading = true
        this.getDetail(this.id)
      }
    },

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

      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, num: 0}
      } finally {
        this.saveLoading = false
      }
    },

    // 获得用户列表
    async getUserList() {
      const {rows = []} = await getOrgUserQuery(
        refineRequestBody({
          querys: [{property: 'DEM_ID_', value: '1258608622670319616'}]
        })
      )
      this.userList = rows
    },

    // 保存
    handleSave() {
      this.$refs.form.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          const {num = 0, userId} = this.form
          const {id: equipmentId, status, userList = []} = this
          const {fullname: userName = ''} =
            userList.find(i => i.id === userId) || {}

          try {
            const {state} = await api.borrowingAndReturning({
              num,
              equipmentId,
              status,
              userId,
              userName
            })

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

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