<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="科室级别" required>
        <el-select v-model="deptLevel" :disabled="!!form.id" @change="handleDeptLevelChange">
          <el-option label="一级科室" :value="1"></el-option>
          <el-option label="二级科室" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属院区" prop="wardId" required>
        <el-select
          v-model="form.wardId"
          :disabled="form.id && deptLevel == 2"
          @change="form.parentId = ''"
        >
          <el-option
            v-for="item in wardListOptions"
            :key="item.id"
            :disabled="item.disabled"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上级科室" prop="parentId" :required="deptLevel === 2">
        <el-select v-model="form.parentId" :disabled="!!form.id || deptLevel === 1">
          <el-option
            v-for="item in deptList"
            :label="item.name"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="科室名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入" :maxlength="32"></el-input>
      </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 { addDept, updateDept, getAllHospital, getAllFirstDept, checkDeptUse } from "@/api/admin";
export default {
  components: {
    Popup,
  },
  data() {
    return {
      deptLevel: 1,
      form: this.getFormDefaultValue(),
      wardList: [], // 院区
      deptList: [], // 一级科室
      rules: {
        name: [
          { required: true, message: "请输入科室名称", trigger: "blur" },
          { max: 32, message: "长度不能超过32个字符", trigger: "blur" },
        ],
        parentId: [
          {
            validator: (rule, value, callback) => {
              if (this.deptLevel === 2 && !value) {
                return callback(new Error("请选择上级科室"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        wardId: [{ required: true, message: "请选择所属院区", trigger: "change" }],
      },
      loading: false,
      defaultValue: {},
    };
  },
  created() {
    this.getHospitalList();
  },
  computed: {
    // 院区如果禁用了，需要回显，但是不可以选择
    wardListOptions() {
      if (!this.defaultValue.wardId) {
        return this.wardList;
      }
      if (this.wardList.find((item) => item.id === this.defaultValue.wardId)) {
        return this.wardList;
      }
      return [
        {
          id: this.defaultValue.wardId,
          name: this.defaultValue.wardName,
          disabled: true,
        },
        ...this.wardList,
      ];
    },
  },
  watch: {
    "form.wardId"() {
      if (this.form.wardId) {
        this.getDeptList();
      }
    },
  },
  methods: {
    getFormDefaultValue() {
      return {
        name: "",
        parentId: "",
        wardId: undefined,
      };
    },
    open(params) {
      if(params && params.parentId === '0') {
        params.parentId = undefined
      }

      const defaultValue = {};
      if (params) {
        for (const key of [...Object.keys(this.form), "id"]) {
          this.form[key] = params[key];
        }
        defaultValue.wardId = params.wardId;
        defaultValue.wardName = params.wardName;
      }
      this.defaultValue = defaultValue;
      this.deptLevel = (params && params.parentId && params.parentId !== '0') ? 2 : 1;
      this.$refs.popup.open(params);
      this.promise = {};
      return new Promise((resolve, reject) => {
        this.promise.resolve = resolve;
        this.promise.reject = reject;
      });
    },
    // 获取一级科室
    async getDeptList() {
      if (this.deptLevel === 1) {
        return;
      }
      const res = await getAllFirstDept({ wardId: this.form.wardId });
      this.deptList = res.data;
    },
    // 获取院区
    async getHospitalList() {
      const res = await getAllHospital();
      this.wardList = res.data;
    },
    handleDeptLevelChange() {
      this.form.parentId = "";
      this.form.wardId = "";
      this.$refs.form.clearValidate(["parentId", "wardId"]);
    },
    handleCancel() {
      this.$refs.popup.close();
    },
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let addRes = null;
          try {
            if (this.form.id) {
              // 如果修改院区，需要先检查一下【科室使用中，请勿更改院区】
              if (this.form.wardId !== this.defaultValue.wardId) {
                await checkDeptUse(this.form.id);
              }
              await updateDept({ ...this.form, parentId: this.form.parentId === '0' ? undefined : this.form.parentId });
              this.$message.success("修改成功");
            } else {
              const res = await addDept(this.form);
              addRes = res.data;
              this.$message.success("新增成功");
            }
          } finally {
            this.loading = false;
          }
          this.$refs.popup.close();
          this.promise.resolve(addRes);
        } else {
          // 表单校验失败
          return false;
        }
      });
    },
    dialogClosed() {
      this.form = this.getFormDefaultValue();
      this.deptList = [];
      this.$nextTick(this.$refs.form.clearValidate);
      // this.promise.reject();
    },
  },
};
</script>
