<template>
  <wrapper
    fill
    margin
    padding
    background
  >
    <schema-table
      ref="table"
      row-key="id"
      :schema="schema"
      :tree-props="{ children: 'subGroups' }"
      @row-click="onRowClick"
    />
    <confirm-dialog
      ref="editDialog"
      :title="dialogTitle"
      @confirm="onSave"
    >
      <div class="c-grid-form u-align-self--center">
        <template v-if="isAdd">
          <span class="c-grid-form__label required">标识</span>
          <div
            class="c-grid-form__info"
            data-info="仅可包含数字、字母和-_符号"
          >
            <el-input
              v-model.trim="group.name"
              placeholder="最多50个字符"
              maxlength="50"
              clearable
            />
          </div>
        </template>
        <span class="c-grid-form__label required">名称</span>
        <el-input
          v-model.trim="group.remark"
          placeholder="最多50个字符"
          maxlength="50"
          clearable
        />
      </div>
    </confirm-dialog>
  </wrapper>
</template>

<script>
import {
  getTenants,
  addTenant,
  addSubGroup,
  updateGroup,
  deleteGroup
} from '@/api/user'
import { unbindDevices } from '@/api/device'

export default {
  name: 'Tenant',
  data () {
    return {
      isAdd: false,
      isTenant: false,
      dialogTitle: '',
      schema: {
        condition: { name: '' },
        list: getTenants,
        buttons: [
          { type: 'add', on: this.onAdd }
        ],
        filters: [
          { key: 'name', type: 'search', placeholder: '标识' }
        ],
        cols: [
          { prop: 'name', label: '标识' },
          { prop: 'remark', label: '名称' },
          { type: 'invoke', width: 240, render: [
            { label: '编辑', on: this.onEdit },
            { label: '新增下级', render ({ parentGroup }) { return !parentGroup }, on: this.onAddSub },
            { label: '删除', on: this.onDel }
          ] }
        ]
      },
      group: {},
      strategies: []
    }
  },
  methods: {
    onRowClick (row) {
      this.$refs.table.getInst().toggleRowExpansion(row)
    },
    onAdd () {
      this.isAdd = true
      this.isTenant = true
      this.dialogTitle = '新增租户'
      this.group = {
        name: '',
        remark: ''
      }
      this.$refs.editDialog.show()
    },
    onEdit (group) {
      this.isAdd = false
      this.isTenant = !group.parentGroup
      this.dialogTitle = group.parentGroup ? '编辑部门' : '编辑租户'
      const { id, name, remark } = group
      this.$group = group
      this.group = { id, name, remark }
      this.$refs.editDialog.show()
    },
    onAddSub (group) {
      this.isAdd = true
      this.isTenant = false
      this.dialogTitle = '新增下级部门'
      this.group = { name: '', remark: '', parentGroup: group }
      this.$refs.editDialog.show()
    },
    onSave (done) {
      if (this.isAdd) {
        const { name, remark } = this.group
        if (!name) {
          this.$message({
            type: 'warning',
            message: '请填写标识'
          })
          return
        }
        if (!/^[\da-zA-Z\-_]+$/.test(name)) {
          this.$message({
            type: 'warning',
            message: '标识格式错误'
          })
          return
        }
        if (!remark) {
          this.$message({
            type: 'warning',
            message: '请填写名称'
          })
          return
        }
        this.addGroup(this.group).then(() => {
          done()
          this.$refs.table.pageTo()
        })
        return
      }
      if (this.$group.remark !== this.group.remark) {
        updateGroup(this.group).then(() => {
          done()
          this.$group.remark = this.group.remark
        })
      }
    },
    addGroup (group) {
      const { parentGroup } = group
      if (parentGroup) {
        return addSubGroup(parentGroup, this.group)
      }
      return addTenant(this.group)
    },
    onDel (group) {
      const tenant = group.parentGroup || group
      this.$confirm(
        `删除租户 ${tenant.remark}${group.parentGroup ? ` 的下级部门 ${group.remark} ` : ' '}？`,
        { type: 'warning' }
      ).then(() => {
        const loading = this.$showLoading()
        unbindDevices({ org: group.path })
          .then(() => deleteGroup(group))
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            if (group.parentGroup) {
              this.$refs.table.pageTo()
            } else {
              this.$refs.table.decrease(1)
            }
          })
          .finally(() => {
            this.$closeLoading(loading)
          })
      })
    }
  }
}
</script>
