<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
        />
        <template v-if="isTenant">
          <span class="c-grid-form__label">AI机审：</span>
          <div class="l-flex--row c-grid-form__option">
            <el-switch
              v-model="group.aiAudit"
              class="c-sibling-item"
              active-value="1"
              inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </div>
        </template>
      </div>
    </confirm-dialog>
    <confirm-dialog
      ref="strategyDialog"
      title="告警设置"
      @confirm="onSaveStrategy"
    >
      <div class="u-align-self--center">
        <div
          v-for="strategy in strategies"
          :key="strategy.level"
          class="c-sibling-item--v far"
        >
          <div class="c-sibling-item--v u-bold">{{ strategy.name }}</div>
          <div class="l-flex--row c-sibling-item--v">
            <div
              v-for="option in strategy.options"
              :key="option.key"
              class="c-sibling-item far"
            >
              <span class="c-sibling-item">{{ option.label }}</span>
              <el-switch
                v-model="option.value"
                class="c-sibling-item"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </div>
          </div>
        </div>
      </div>
    </confirm-dialog>
  </wrapper>
</template>

<script>
import {
  getTenants,
  addTenant,
  addSubGroup,
  updateGroup,
  deleteGroup
} from '@/api/user'
import {
  getInformStrategy,
  updateInformStrategy
} from './api'
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: '名称' },
          { label: 'AI机审', type: 'tag', render ({ parentGroup, aiAudit }) {
            return parentGroup
              ? null
              : {
                type: aiAudit === '1' ? 'success' : 'danger',
                label: aiAudit === '1' ? '开启' : '关闭'
              }
          } },
          { type: 'invoke', width: 240, render: [
            { label: '编辑', on: this.onEdit },
            { label: '告警设置', render ({ parentGroup }) { return !parentGroup }, on: this.onStrategy },
            { 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: '',
        aiAudit: '1'
      }
      this.$refs.editDialog.show()
    },
    onEdit (group) {
      this.isAdd = false
      this.isTenant = !group.parentGroup
      this.dialogTitle = group.parentGroup ? '编辑部门' : '编辑租户'
      const { id, name, remark, aiAudit } = group
      this.$group = group
      this.group = { id, name, remark, aiAudit: this.isTenant ? aiAudit : void 0 }
      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
        || this.isTenant && this.$group.aiAudit !== this.group.aiAudit
      ) {
        updateGroup(this.group).then(() => {
          done()
          this.$group.remark = this.group.remark
          this.$group.aiAudit = this.group.aiAudit
        })
      }
    },
    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)
          })
      })
    },
    onStrategy ({ path }) {
      this.$tenant = path
      getInformStrategy(path).then(data => {
        console.log(data)
        this.strategies = data
        this.$refs.strategyDialog.show()
      })
    },
    onSaveStrategy (done) {
      const strategies = {}
      this.strategies.forEach(({ level, options }) => {
        const strategy = {}
        options.forEach(({ key, value }) => {
          strategy[key] = value
        })
        strategies[level] = strategy
      })
      updateInformStrategy(this.$tenant, strategies).then(done)
    }
  }
}
</script>

<style lang="scss" scoped>
.o-strategy-name {
  width: 60px;
}
</style>
