<template>
  <schema-table
    ref="table"
    :schema="schema"
  >
    <confirm-dialog
      ref="editDialog"
      title="新增账号"
      @confirm="onSave"
    >
      <template #default>
        <div class="c-grid-form u-align-self--center">
          <span class="c-grid-form__label u-required">账号</span>
          <div
            class="u-width has-info"
            data-info="仅可包含数字、字母"
          >
            <el-input
              v-model.trim="user.username"
              placeholder="4~20个字符"
              maxlength="20"
              clearable
            />
          </div>
          <span class="c-grid-form__label">姓名</span>
          <el-input
            v-model.trim="user.name"
            class="u-width--sm"
            placeholder="账号使用者姓名"
            maxlength="20"
            clearable
          />
          <span class="c-grid-form__label">部门</span>
          <div class="c-grid-form__auto u-overflow-x--auto">
            <el-tree
              ref="tree"
              class="inline-flex"
              :data="groups"
              node-key="path"
              :props="treeProps"
              :current-node-key="group.path"
              :default-expanded-keys="expandKeys"
              :expand-on-click-node="false"
              accordion
              highlight-current
              auto-expand-parent
              @node-click="onGroupClick"
            />
          </div>
        </div>
      </template>
    </confirm-dialog>
    <c-dialog
      ref="dialog"
      size="medium"
      title="设置"
    >
      <template #default>
        <settings
          :user="user"
          :tenant="tenant"
          :groups="groups"
          @del="onDel"
          @group="onGroupChange"
        />
      </template>
    </c-dialog>
    <confirm-dialog
      ref="eventDialog"
      title="自定义事件"
      @confirm="onConfirmEvents"
    >
      <el-checkbox-group
        v-model="selectedEvents"
        class="l-grid--info mini"
      >
        <el-checkbox
          v-for="item in events"
          :key="item.id"
          :label="item.id"
        >
          {{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
    </confirm-dialog>
  </schema-table>
</template>

<script>
import { mapGetters } from 'vuex'
import { AlarmLevelInfo } from '@/constant'
import {
  getUsersByDepartment,
  addUser,
  updateUserName,
  toggleUser,
  updateUserInformLevel,
  getUserInforms
} from '@/api/user'
import Settings from './Settings'

const CustomEvents = Object.freeze([
  { id: 1, level: 0, label: '播控器离线' },
  { id: 17, level: 2, label: '播控器工作时段离线' },
  { id: 15, level: 2, label: '播控器人为离线' },
  { id: 9, level: 0, label: '播控器上线' },
  { id: 32, level: 2, label: '播控器非工作时段上线' },
  { id: 40, level: 2, label: '播控器上线失败' },
  { id: 35, level: 0, label: '接收卡提示性预警' },
  { id: 2, level: 2, label: '接收卡紧急预警' },
  { id: 36, level: 2, label: '手动关闭电源' },
  { id: 37, level: 2, label: '手动开启电源' },
  { id: 42, level: 2, label: '电源定时任务' },
  { id: 0, level: 1, label: '屏幕疑似黑屏' },
  { id: 13, level: 2, label: '屏幕黑屏' },
  { id: 10, level: 2, label: '屏幕内容疑似不合规' },
  // { id: 3, level: 2, label: '屏幕内容不合规（拼接器）' },
  { id: 11, level: 2, label: '屏幕内容不合规' },
  { id: 18, level: 0, label: '温度传感器提示告警' },
  { id: 19, level: 0, label: '温度传感器一级告警' },
  { id: 20, level: 0, label: '温度传感器二级告警' },
  { id: 21, level: 1, label: '温度传感器三级告警' },
  { id: 22, level: 2, label: '温度传感器四级告警' },
  { id: 23, level: 2, label: '位移传感器报警' },
  { id: 7, level: 2, label: '屏幕监控摄像头离线' },
  { id: 8, level: 2, label: '人流监测摄像头离线' },
  { id: 33, level: 0, label: '屏幕监控摄像头上线' },
  { id: 34, level: 0, label: '人流监测摄像头上线' }
])

export default {
  name: 'Account',
  components: {
    Settings
  },
  props: {
    groups: {
      type: Array,
      required: true
    },
    group: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      schema: {
        list: this.getUsersByDepartment,
        condition: { recursive: 1 },
        buttons: [
          { type: 'add', on: this.onAdd }
        ],
        filters: [
          { key: 'recursive', type: 'checkbox', label: '级联' }
        ],
        cols: [
          { label: '部门', render: ({ path, tenant }) => this.groupMap[path || tenant] },
          { prop: 'userName', label: '账号' },
          { label: '使用者', render: (data, h) => h('edit-input', {
            props: {
              value: data.name || '',
              placeholder: '-'
            },
            on: { edit: val => this.onEditName(data, val) }
          }), 'class-name': 'c-edit-column' },
          { label: '消息推送', render: (data, h) => h('el-select', {
            props: {
              value: data.informLevel
            },
            on: {
              change: val => this.updateInformLevel(val, data)
            }
          }, [
            data.informLevel === 9999 && h('i', {
              slot: 'prefix',
              staticClass: 'l-flex--row center el-icon-edit u-font-size--md has-active',
              staticStyle: {
                height: '100%'
              },
              on: { click: e => {
                e.stopPropagation()
                this.onEditEvents(data)
              } }
            }),
            h('el-option', {
              key: 'none',
              props: {
                value: -1,
                label: '不预警'
              }
            }),
            h('el-option', {
              key: 'info',
              props: {
                value: 0,
                label: `${AlarmLevelInfo[0]}及以上`
              }
            }),
            h('el-option', {
              key: 'warning',
              props: {
                value: 1,
                label: `${AlarmLevelInfo[1]}及以上`
              }
            }),
            h('el-option', {
              key: 'error',
              props: {
                value: 2,
                label: AlarmLevelInfo[2]
              }
            }),
            h('el-option', {
              key: 'terror',
              props: {
                value: 9999,
                label: AlarmLevelInfo[9999]
              }
            })
          ]) },
          { type: 'tag', render: ({ userId, enabled }) => userId === this.userId
            ? null
            : {
              type: enabled ? 'success' : 'danger',
              label: enabled ? '启用' : '禁用'
            }, on: this.onToggle },
          { type: 'invoke', use: ({ userId }) => userId !== this.userId, render: [
            { label: '设置', on: this.onSettings }
          ] }
        ]
      },
      user: {},
      treeProps: { label: 'name', children: 'children' },
      events: CustomEvents,
      selectedEvents: []
    }
  },
  computed: {
    ...mapGetters(['tenant', 'userId']),
    expandKeys () {
      let groups = this.groups
      const group = this.group
      const arr = []
      const marks = group.path.split('/').filter(Boolean)
      let cpath = '/'
      while (marks.length > 1) {
        cpath += marks.shift()
        const tpath = cpath
        const temp = groups.find(({ path }) => path === tpath)
        arr.push(temp.path)
        groups = temp.children
        cpath += '/'
      }
      return arr.length ? arr : [this.tenant]
    },
    groupMap () {
      const map = {}
      this.createMap(this.groups, map)
      return map
    }
  },
  watch: {
    group () {
      this.$refs.table.pageTo(1)
    }
  },
  methods: {
    createMap (arr, map) {
      arr?.forEach(({ path, name, children }) => {
        map[path] = name
        this.createMap(children, map)
      })
    },
    getUsersByDepartment (params) {
      return getUsersByDepartment({
        departmentId: this.group.id,
        ...params
      })
    },
    onSettings (user) {
      this.user = user
      this.$refs.dialog.show()
    },
    onDel () {
      this.$refs.dialog.hide()
      this.$refs.table.decrease(1)
    },
    onGroupChange () {
      this.$refs.table.pageTo()
    },
    onAdd () {
      this.user = {
        username: '',
        name: ''
      }
      this.$department = { id: this.group.id, path: this.group.path, name: this.group.name }
      this.$refs.editDialog.show()
    },
    onGroupClick ({ id, path, name }) {
      this.$department = { id, path, name }
    },
    onSave (done) {
      const { username } = this.user
      if (!username) {
        this.$message({
          type: 'warning',
          message: '请填写用户账号'
        })
        return
      }
      if (username.length < 4) {
        this.$message({
          type: 'warning',
          message: '用户账号过短'
        })
        return
      }
      if (!/^[\da-zA-Z]{4,}$/.test(username)) {
        this.$message({
          type: 'warning',
          message: '用户账号格式错误'
        })
        return
      }
      addUser({
        ...this.user,
        ...(
          this.$department.id
            ? { departmentId: this.$department.id, departmentName: this.$department.name }
            : { departmentName: '顶层部门' }
        )
      }).then(() => {
        done()
        if (this.$department.path.indexOf(this.group.path) === 0) {
          this.$refs.table.pageTo(1)
        }
      })
    },
    onEditName (user, { newVal, oldVal }) {
      if (newVal === oldVal) {
        return
      }
      user.name = newVal
      updateUserName(user.userId, newVal).catch(() => {
        user.name = oldVal
      })
    },
    onToggle (user) {
      const enabled = [1, 0][user.enabled]
      this.$confirm(
        `${enabled ? '启用' : '停用'}账号${user.userName}？`,
        '操作确认',
        { type: 'warning' }
      ).then(() => toggleUser(
        user,
        enabled
      )).then(() => {
        user.enabled = enabled
      })
    },
    updateInformLevel (val, user) {
      updateUserInformLevel(user, val).then(() => {
        user.informLevel = val
        if (val === 9999) {
          this.onEditEvents(user)
        }
      })
    },
    onEditEvents (user) {
      this.$user = user
      getUserInforms(user).then(({ data }) => {
        this.selectedEvents = data
        this.$refs.eventDialog.show()
      })
    },
    onConfirmEvents (done) {
      updateUserInformLevel(this.$user, 9999, this.selectedEvents).then(done)
    }
  }
}
</script>
