<template>
  <div class="app-container">
    <!-- filter -->
    <el-form ref="filterForm" :inline="true" :model="filterForm" class="filter">
      <el-form-item label="关键字" prop="key">
        <el-input v-model="filterForm.key" placeholder="关键字"/>
      </el-form-item>
      <el-form-item label="角色">
        <el-select
            v-model="filterForm.role"
            placeholder="所有"
            class="w100"
        >
          <el-option value="">所有</el-option>
          <el-option
              v-for="item in roleList"
              :key="item.key"
              :label="item.name"
              :value="item.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="店铺">
        <el-select
            v-model="filterForm.department"
            placeholder="所有"
            class="w100"
        >
          <el-option value="">所有</el-option>
          <el-option value="系统帐号">系统帐号</el-option>
          <el-option value="未指定">未指定</el-option>
          <el-option
              v-for="item in allDepts"
              :key="item._id"
              :label="item.name"
              :value="item._id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetFilterForm">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button
        v-permission="['admin:edit']"
        type="primary"
        @click="handleCreateAdmin"
    >
      {{$t('admin.addAdmin')}}
    </el-button>

    <el-table
        v-loading="isLoad"
        :data="tableData"
        style="width: 100%;margin-top:30px;"
        border
        :row-class-name="tableRowClassName"
    >
      <el-table-column
          align="center"
          label="帐号名"
      >
        <template slot-scope="{row}">
          {{row.showname}}({{row.username}})
        </template>
      </el-table-column>
      <el-table-column
          prop="department"
          align="center"
          label="店铺"
      >
        <template slot-scope="{row}">
          {{formatDept(row)}}
        </template>
      </el-table-column>
      <el-table-column
          prop="locked"
          align="center"
          label="状态"
      >
        <template slot-scope="{row}">
          <el-tag
              size="small"
              :type="row.locked ? 'danger': 'info'"
          >{{ formStatus(row.locked) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="sex"
          align="center"
          label="性别"
          :formatter="formSex"
      >
      </el-table-column>
      <el-table-column
          align="center"
          label="角色"
      >
        <template slot-scope="{row}">
          <el-tag
              v-for="(item, index) in row.roles"
              :key="index"
              size="small"
              style="margin-right: 10px;"
          >{{ formatRole(item) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          align="header-center"
          label="备注"
      >
        <template slot-scope="{row}">
          {{row.comment}}
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="操作"
          fixed="right"
          width="220"
      >
        <template slot-scope="scope">
          <el-button
              type="primary"
              size="small"
              v-permission="['admin:edit']"
              @click="handleEdit(scope)"
          >
            {{$t('admin.editAdmin')}}
          </el-button>
          <el-button
              type="danger"
              size="small"
              v-permission="['admin:delete']"
              @click="handleDelete(scope)"
          >
            {{$t('permission.delete')}}
          </el-button>

          <el-button
              type="warning"
              size="small"
              v-permission="['admin:lock']"
              @click="handleLock(scope)"
          >
            {{scope.row.locked? '解锁' : '锁定'}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination -->
    <el-pagination
        :hide-on-single-page="false"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="dataCount"
        class="al-r"
        @size-change="sizeChange"
        @current-change="pageChange"
    />
    <el-dialog
        :visible.sync="dialogVisible"
        :title="dialogType==='edit'?'Edit Admin':'New Admin'"
    >
      <el-form
          :model="record"
          ref="modalForm"
          :rules="modalRules"
          label-width="80px"
          label-position="left"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="record.username"
              placeholder="用户名"
              clearable
          />
        </el-form-item>
        <el-form-item label="密码" v-if="dialogType==='edit'">
          <el-input
              type="password"
              v-model="record.password"
              placeholder="不修改就留空"
          />
        </el-form-item>
        <el-form-item label="密码" v-if="dialogType!=='edit'">
          <el-input
              type="password"
              v-model="record.password"
              placeholder="密码"
          />
        </el-form-item>
        <el-form-item label="显示名" prop="showname">
          <el-input
              v-model="record.showname"
              placeholder="显示名"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group size='small' v-model="record.sex">
            <el-radio-button label="0">未指定</el-radio-button>
            <el-radio-button label="1">男</el-radio-button>
            <el-radio-button label="2">女</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox-group size="small" v-model="record.roles">
            <el-checkbox border v-for="role in roleList"
                         :key="role.key"
                         :label="role.key"
                         name="type"
            >{{role.name}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="帐号类型">
          <el-radio-group v-model="record.level" size="small">
            <el-radio-button :label="1">系统帐号</el-radio-button>
            <el-radio-button :label="9">店铺</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
            label="店铺"
            prop="department"
            v-if="record.level === 9"
        >
          <el-select
              v-model="record.department"
              :remote-method="getRemoteDeptList"
              filterable
              default-first-option
              remote
              placeholder=""
          >
            <el-option
                v-for="(item) in deptListOptions"
                :key="item._id"
                :label="item.name"
                :value="item._id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="锁定" v-permission="['admin:lock']">
          <el-switch v-model="record.locked"/>
        </el-form-item>
        <el-form-item
            prop="avatar"
            label="头像"
        >
          <upload-image v-model="record.avatar" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="record.comment"
              :autosize="{minRows: 2, maxRows: 4}"
              type="textarea"
              placeholder="备注"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button
            type="danger"
            @click="closeModal"
        >
          {{$t('permission.cancel')}}
        </el-button>
        <el-button
            type="primary"
            @click="confirmRole"
        >
          {{$t('permission.confirm')}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { cloneDeep } from 'lodash'
import { Component, Vue } from 'vue-property-decorator'
import UploadImage from '@/components/UploadImage/index.vue'
import { getRoles } from '@/api/roles'
import {
  changeLocker,
  defaultAdmin,
  deleteAdmin,
  getUsers,
  IAdmin,
  saveAdmin
} from '@/api/admins'
import { IRole } from '@/views/system/role.vue'
import { getShops } from '@/api/shop'
import { IShopData } from '@/api/types'

@Component({
  name: 'AdminSystem',
  components: {
    UploadImage
  }
})
export default class extends Vue {
  private record = Object.assign({}, defaultAdmin)
  private adminList: IAdmin[] = []
  private tableData: IAdmin[] = []
  private roleList: IRole[] = []
  private dialogVisible = false
  private dialogType = 'new'
  private checkStrictly = false
  private isLoad = false
  // pagination
  private currentPage = 1
  private pageSize = 5
  private dataCount = 0
  private deptListOptions = []
  private allDepts: IShopData[] = []

  private filterForm = {
    key: '',
    role: '',
    department: ''
  }

  $refs!: {
    modalForm: HTMLFormElement
    filterForm: HTMLFormElement
  }

  private modalRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
      {
        required: true,
        pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
        message: '用户名不支持特殊字符',
        trigger: 'blur'
      }],
    showname: [{ required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
      {
        required: true,
        pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
        message: '显示名不支持特殊字符',
        trigger: 'blur'
      }]
  }

  async created() {
    this.allDepts = await this.getRemoteDeptList('')
    await this.getRecords()
    await this.getAllRole()
  }

  private search() {
    this.tableData = this.filterData()
    this.currentPage = 1
  }

  private filterData() {
    let result = [...this.adminList]
    if (this.filterForm.key) {
      result = result.filter(user => {
        const reg = new RegExp(this.filterForm.key)
        return (reg.test(user.showname)) || (reg.test(user.username))
      })
    }
    if (this.filterForm.role) {
      result = result.filter(user => {
        return user.roles.indexOf(this.filterForm.role) >= 0
      })
    }
    if (this.filterForm.department) {
      if (this.filterForm.department === '系统帐号') {
        result = result.filter(user => {
          return user.level === 1
        })
      } else if (this.filterForm.department === '未指定') {
        result = result.filter(user => {
          return !user.department
        })
      } else {
        result = result.filter(user => {
          return user.department === this.filterForm.department
        })
      }
    }
    this.dataCount = result.length
    return result
  }

  private resetFilterForm() {
    this.$refs.filterForm.resetFields()
  }

  // pagination
  private sizeChange(val: number) {
    this.pageSize = val
    this.sliceData()
  }

  private pageChange(val: number) {
    this.currentPage = val
    this.sliceData()
  }

  private sliceData() {
    // 满足过滤条件 -> 分页
    const data = this.filterData()
    this.tableData = data.slice(
      (this.currentPage - 1) * this.pageSize,
      this.currentPage * this.pageSize
    )
    if (this.tableData.length === 0 && this.currentPage > 1) {
      this.currentPage -= 1
      this.sliceData()
    }
  }

  private async getRecords() {
    this.isLoad = true
    const { data } = await getUsers({ /* Your params here */ })
    this.adminList = data
    this.dataCount = data.length
    this.sliceData()
    this.isLoad = false
  }

  private async getAllRole() {
    const { data } = await getRoles({ /* Your params here */ })
    this.roleList = data
  }

  private formSex(row: number, column: number, cellValue: string) {
    switch (cellValue) {
      case '0':
        return '未指定'
      case '1':
        return '男'
      case '2':
        return '女'
      default:
        return '未指定'
    }
  }

  private formStatus(cellValue: boolean) {
    return cellValue ? '已锁定' : '正常'
  }

  private formatRole(val: string) {
    const data = this.roleList.find(o => {
      return o.key === val
    })
    return data?.name || ''
  }

  private handleCreateAdmin() {
    this.record = Object.assign({}, defaultAdmin)

    this.dialogType = 'new'
    this.dialogVisible = true
  }

  private handleEdit(scope: any) {
    this.dialogType = 'edit'
    this.dialogVisible = true
    this.checkStrictly = true
    this.record = cloneDeep(scope.row)
  }

  private async handleDelete(scope: any) {
    const { $index, row } = scope
    console.log($index, row)
    try {
      await this.$confirm('确定删除当前帐号?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await deleteAdmin(row.id)
      const index = this.adminList.indexOf(row)
      this.adminList.splice(index, 1)
      this.sliceData()
      this.$message({
        type: 'success',
        message: 'Deleted!'
      })
    } catch (err) {
      console.log(err)
    }
  }

  private async handleLock(scope: any) {
    const { row } = scope
    try {
      let txt = '确定锁定当前帐号?'
      if (row.locked) {
        txt = '确定解锁当前帐号?'
      }
      await this.$confirm(txt, 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await changeLocker(row.id, !row.locked)
      row.locked = !row.locked
      this.sliceData()
      this.$message({
        type: 'success',
        message: 'Deleted!'
      })
    } catch (err) {
      console.log(err)
    }
  }

  private closeModal() {
    this.dialogVisible = false
    this.$refs.modalForm.clearValidate()
  }

  private async confirmRole() {
    const isEdit = this.dialogType === 'edit'
    this.$refs.modalForm.validate(async(valid: boolean) => {
      if (!valid) {
        this.$message.error('请按要求填写表单')
        return false
      }
      const { data } = await saveAdmin(this.record)
      console.log(data)
      if (isEdit) {
        for (let index = 0; index < this.adminList.length; index++) {
          if (this.adminList[index].id === this.record.id) {
            this.adminList.splice(index, 1, Object.assign({}, this.record))
            break
          }
        }
      } else {
        this.adminList.push(data)
      }
      this.sliceData()
      const { username, showname } = this.record
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `
          <div>Admin Username: ${username}</div>
          <div>Admin Showname: ${showname}</div>
        `,
        type: 'success'
      })
    })
  }

  private async getRemoteDeptList(name: string) {
    const { data } = await getShops({ key: name })
    if (!data.records) return
    this.deptListOptions = data.records
    return data.records
  }

  private formatDept(row: any) {
    if (row.level === 1) {
      return '系统帐号'
    }
    let result = '未指定'
    for (const dep of this.allDepts) {
      if (dep._id === row.department) {
        result = dep.name
        break
      }
    }
    return result
  }

  private tableRowClassName({ row }: {row: any}) {
    if (row.level === 1) {
      return 'shop-row'
    }
    return ''
  }
}
</script>

<style lang="scss" >
  .el-table .shop-row {
    background: oldlace!important;
  }
</style>
