<template>
  <div class="cmain">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="父级科室" prop="parentId">
        <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="请选择父级科室" />
      </el-form-item>
      <el-form-item label="科室名称" prop="deptname">
        <el-input v-model="form.deptname" placeholder="请输入科室名称" />
      </el-form-item>
      <el-form-item label="科室描述">
        <editor v-model="form.deptdesc" :min-height="192"/>
      </el-form-item>
    </el-form>
    <div class="mfooter">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="$layer.close(layerid)">取 消</el-button>
    </div>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
export default {
  components: {
    Treeselect
  },
  data() {
    return {
      // 医院科室树选项
      deptOptions: [],
      form: { orderNum: 0, state: 0 },
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "父级科室不能为空", trigger: "blur" }
        ],
        deptname: [
          { required: true, message: "科室名称不能为空", trigger: "blur" }
        ],
        deptdesc: [
          { required: true, message: "科室描述不能为空", trigger: "blur" }
        ]
      }
    };
  },
  props: {
    param: {
      type: Object,
      default: () => {
        return {};
      }
    },
    layerid: {
      type: String
    }
  },
  mounted() {
    this.getTreeselect()
    if (this.param.id) {
      this.ajax({ url: '/work/dept/detail/' + this.param.id }).then((response) => {
        this.form = response.data;
      });
    }else{
      this.form.parentId = this.param.parentId
    }
  },
  methods: {
    getTreeselect() {
      this.ajax({ url: '/work/dept/list' }).then((response) => {
        this.deptOptions = [];
        const data = { id: 0, deptname: '全科科室', children: [] };
        data.children = this.handleTree(response.rows, "id", "parentId");
        this.deptOptions.push(data);
      });
    },
    /** 转换医院科室数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.deptname,
        children: node.children
      };
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            this.ajax({ method: 'post', url: '/work/dept/edit', data: this.form }).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.$layer.close(this.layerid);
              this.$parent.getList();
            });
          } else {
            this.ajax({ method: 'post', url: '/work/dept/add', data: this.form }).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.$layer.close(this.layerid);
              this.$parent.getList();
            });
          }
        }
      });
    }
  }
};
</script>
