<template>
  <Popup ref="popup" title="院区信息" @closed="dialogClosed">
    <el-form :model="form" :rules="rules" ref="form" label-width="130px" v-loading="loading">
      <el-form-item label="院区名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入" :maxlength="32"></el-input>
      </el-form-item>
      <el-form-item label="是否为本院区" prop="isHead">
        <el-radio-group v-model="form.isHead">
          <el-radio v-for="item in IS_MY_HOSPITAL.options" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </Popup>
</template>

<script>
import Popup from "@/components/Popup";
import { addHospital, updateHospital } from "@/api/admin";
import { IS_MY_HOSPITAL } from '@/enums/index'
export default {
  components: {
    Popup,
  },
  data() {
    return {
      IS_MY_HOSPITAL,
      form: this.getFormDefaultValue(),
      rules: {
        name: [
          { required: true, message: "请输入院区名称", trigger: "blur" },
          { max: 32, message: "长度不能超过32个字符", trigger: "blur" },
        ],
        isHead: [{ required: true, message: "请选择是否为本院区", trigger: "change" }],
      },
      loading: false,
    };
  },
  methods: {
    getFormDefaultValue() {
      return {
        name: "",
        isHead: 1,
      };
    },
    open(params) {
      if (params) {
        for (const key of [...Object.keys(this.form), "id"]) {
          this.form[key] = params[key];
        }
      }
      this.promise = {};
      return new Promise((resolve, reject) => {
        this.promise.resolve = resolve;
        this.promise.reject = reject;
        this.$refs.popup.open(params);
      });
    },
    handleCancel() {
      this.$refs.popup.close();
    },
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            if (this.form.id) {
              await updateHospital(this.form);
              this.$message.success("修改成功");
            } else {
              await addHospital(this.form);
              this.$message.success("新增成功");
            }
          } finally {
            this.loading = false;
          }
          this.promise.resolve();
          this.$refs.popup.close();
        } else {
          // 表单校验失败
          return false;
        }
      });
    },
    dialogClosed() {
      this.form = this.getFormDefaultValue();
      this.$nextTick(this.$refs.form.clearValidate);
      // this.promise.reject();
    },
  },
};
</script>
