<template>
  <el-dialog :visible.sync="visible" :before-close="cancelDialog">
    <el-divider />
    <label slot="title" style="float: left;">{{ dialogTitle }}</label>

    <el-row>
      <el-form ref="form" :model="form" :rules="formRules" label-suffix="：" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入部门名称" clearable />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model.trim="form.leader" placeholder="请输入负责人" clearable />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model.trim="form.phone" placeholder="请输入电话" clearable />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="form.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model.trim="form.sort" controls-position="right" clearable />
        </el-form-item>
        <el-form-item label="顶级部门">
          <el-radio-group v-model="isTop" style="width: 140px">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="isTop === '0'" style="margin-bottom: 0;" label="上级部门" prop="parentId">
          <el-cascader
            v-model="form.parentId"
            :options="options"
            :props="{ checkStrictly: true,expandTrigger: 'hover' }"
            :show-all-levels="false"
            clearable
          />
        </el-form-item>
      </el-form>
    </el-row>

    <div slot="footer" class="dialog-footer">
      <el-divider />
      <el-button @click="cancelDialog">取 消</el-button>
      <el-button type="primary" @click="handleSave">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import deptApi from '@/api/platform/deptApi'

export default {
  name: 'EditDeptDialog',
  props: {
    dialogTitle: {
      type: String,
      default: () => {
        return ''
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
    form: {
      type: Object,
      default: () => {
        return {
          id: '',
          parentId: '',
          name: '',
          leader: '',
          phone: '',
          email: '',
          sort: 0
        }
      }
    },
    isTop: {
      type: String,
      default: () => {
        return '1'
      }
    }
  },
  data() {
    return {
      options: [],
      formRules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      }
    }
  },
  watch: {
    'form.parentId': {
      handler(val) {
        if (val !== null) {
          if (val.length !== 0) {
            if (val[val.length - 1] === this.form.id) {
              if (this.form.id === '') { // 防止关闭弹框时弹出提示
                return
              }
              this.$message('上级部门不能选为自己')
              this.form.parentId = ''
            }
          }
        }
      },
      immediate: true
    },
    isTop(val) {
      if (val === '0') {
        deptApi.nodes().then(data => {
          this.options = data
        })
      }
    },
    visible(val) {
      if (val === true) {
        this.form.parentId = this.getNodePathArray(this.options, this.form.parentId, [])
      }
    }
  },
  mounted() {
    deptApi.nodes().then(data => {
      this.options = data
    })
  },
  methods: {
    // 根据节点树（data）,父节点id，查找父节点节点路径，以数组返回。如节点路径为1-2，则返回['1','2']
    // indexArray在使用时传入空数组即可
    getNodePathArray(data, id, indexArray) {
      const arr = Array.from(indexArray)
      for (let i = 0, len = data.length; i < len; i++) {
        arr.push(data[i].value)
        if (data[i].value === id) {
          return arr
        }
        const children = data[i].children
        if (children && children.length) {
          const result = this.getNodePathArray(children, id, arr)
          if (result) {
            return result
          }
        }
        arr.pop()
      }
      return false
    },
    cancelDialog() {
      this.form = {
        id: '',
        parentId: '',
        name: '',
        leader: '',
        phone: '',
        email: '',
        sort: 0
      }
      this.$refs['form'].resetFields()
      this.$emit('cancelDialog', false)
    },
    handleSave() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }
        const mform = {
          id: this.form.id,
          parentId: '',
          name: this.form.name,
          leader: this.form.leader,
          phone: this.form.phone,
          email: this.form.email,
          sort: this.form.sort
        }
        // 将数组parentId转为字符串
        if (this.form.parentId !== null) {
          if (this.form.parentId.length !== 0) {
            mform.parentId = this.form.parentId[this.form.parentId.length - 1]
          }
        }
        if (this.isTop === '1') {
          mform.parentId = ''
        }
        deptApi.saveOrUpdate(mform).then(data => {
          this.$refs['form'].resetFields()
          this.$emit('cancelDialog', false)
          this.$emit('refresh')
        })
      })
    }
  }
}

</script>
<style>
</style>
