<template>
  <div>
    <div class="flex-h mb-12">
      <QueryInput v-model="find_user_params.likeName" @query="findAllUser" />
      <ElCascader
        v-model="find_user_params.org"
        :options="org_options"
        @change="findAllUser"
        v-bind="cascaderProps"
        placeholder="组织机构"
        class="ml-12 mr-12"
      />
      <ElCascader
        v-model="find_user_params.role"
        :options="role_options"
        @change="findAllUser"
        v-bind="cascaderProps"
        placeholder="角色"
      />
      <div class="flex-1"></div>
      <el-button type="danger" round @click="toDeletes()">删除选中</el-button>
      <el-button round icon="el-icon-plus" @click="toBatchAdd"
        >批量添加</el-button
      >
      <el-button type="primary" round icon="el-icon-plus" @click="toCreateUser"
        >添加用户</el-button
      >

    </div>

    <TableLayout
      selection
      ref="tableRef"
      :column="column"
      :data="user_list"
      :pageInfo="pageInfo"
      @page-info-change="findAllUser"
      @selection-change="onTableSelectionChange"
    >
      <template v-slot:sex="{ row }">{{
        String(row.sex) ? ["女", "男"][row.sex] : ""
      }}</template>
      <template v-slot:birthday="{ row }">{{
        row.birthday ? new Date(row.birthday).format("yyyy-MM-dd") : ""
      }}</template>
      <template v-slot:photo="{ row }">
        <img
          v-if="row.photoResource"
          :src="row.photoResource.diskname.fileLinkTransfer()"
          width="50"
          height="50"
        />
      </template>
      <template v-slot:action="{ row }">
        <template v-if="row.username != 'admin'">
          <el-button type="text" icon="el-icon-edit" @click="toUpdate(row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            class="color-danger"
            icon="el-icon-delete"
            @click="toDeletes(row.id)"
            >删除</el-button
          >
          <el-button
            type="text"
            class="color-warning"
            icon="el-icon-view"
            @click="toResetPassword(row)"
            >重置密码</el-button
          >
        </template>
      </template>
    </TableLayout>

    <DialogLayout
      title="添加用户"
      width="380px"
      bodyHeight="46vh"
      shadowBar
      :visible="form_data"
      @onCancel="form_data = null"
      @onConfirm="onConfirm"
    >
      <FormLayout
        ref="formLayoutRef"
        :items="form_items"
        :model="form_data"
        :rules="rules"
        label-width="78px"
        label-position="right"
      >
        <template v-slot:manageTeacher>
          <el-select
            v-model="form_data.manageTeacher"
            multiple
            filterable
            reserve-keyword
            placeholder="请选择"
          >
            <el-option
              v-for="v in form_manage_teacher.model.options"
              :key="v.id"
              :label="v.name"
              :value="v.id"
            />
          </el-select>
        </template>
        <template v-slot:photo>
          <div
            class="_photo"
            @click="toUploadPhoto"
            data-hint="推荐像素1200*768"
          >
            <img
              v-if="form_data.photoResource"
              :src="form_data.photoResource.fileLinkTransfer()"
            />
            <i v-else class="_icon el-icon-plus" />
          </div>
        </template>
        <template v-slot:sex>
          <el-radio-group v-model="form_data.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </template>
      </FormLayout>
    </DialogLayout>
  </div>
</template>

<script>
import { QueryInput } from '@/components/widget'
import { TableLayout, FormLayout, DialogLayout } from '@/components/layout'
import { createUserApi, deleteUsersApi, findAllUserApi, findAllTeacherApi, updateUserApi, resetPasswordApi } from '@/api/system/user'
import { findAllOrgApi } from '@/api/system/org'
import { findAllRoleApi } from '@/api/system/role'
import { uploadApi } from '@/api/system'
import { getDistFile } from '@/utils'

export default {
  components: { QueryInput, TableLayout, FormLayout, DialogLayout },

  data: () => ({
    find_user_params: { likeName: '', org: [], role: [] },
    form_data: null,
    form_items: null,
    form_manage_teacher: { prop: 'manageTeacher', label: '管辖老师', model: { loading: false, options: null } },
    user_list: [],
    org_options: [],
    role_options: [],
    pageInfo: { current: 1, size: 10, total: 0 }
  }),

  watch: {
    'form_data.role' (data) {
      const i = this.form_items.indexOf(this.form_manage_teacher)
      if (i !== -1) this.form_items.splice(i, 1)

      if (data && this.role_options.find(v => v.id === data[0])?.base === 3) {
        this.form_items.splice(4, 0, this.form_manage_teacher)
        if (!this.form_manage_teacher.model.options) this.findAllTeacher()
      }
    }
  },

  created () {
    this.column = [
      { prop: 'username', label: '用户名' },
      { prop: 'name', label: '姓名' },
      { prop: 'photo', label: '照片' },
      { prop: 'sex', label: '性别' },
      { prop: 'birthday', width: '90px', label: '出生年月' },
      { prop: 'idcard', label: '身份证号' },
      { prop: 'identity', label: '职位' },
      { prop: 'phone', label: '电话' },
      { prop: 'email', label: '邮箱' },
      { prop: 'action', width: '200px', label: '操作' }
    ]

    this.cascaderProps = { clearable: true, props: { label: 'name', value: 'id', checkStrictly: true } }
    this.form_items = [
      { prop: 'username', label: '用户名', model: { tag: 'el-input', attrs: { placeholder: '请输入字母、数字、下划线', maxlength: 16 } } },
      { prop: 'name', label: '姓名', model: { tag: 'el-input', attrs: { placeholder: '不可输入空白字符', maxlength: 16 } } },
      { prop: 'org', label: '组织', model: { tag: 'el-cascader', options: this.org_options, ...this.cascaderProps } },
      { prop: 'role', label: '角色', model: { tag: 'el-cascader', options: this.role_options, ...this.cascaderProps } },
      { prop: 'photo', label: '照片' },
      { prop: 'sex', label: '性别' },
      { prop: 'birthday', label: '出生年月', model: { tag: 'el-date-picker' } },
      { prop: 'idcard', label: '身份证号', model: { tag: 'el-input', attrs: { maxlength: 18 } } },
      { prop: 'identity', label: '职位', model: { tag: 'el-input', attrs: { maxlength: 16 } } },
      { prop: 'phone', label: '电话', model: { tag: 'el-input', attrs: { maxlength: 11 } } },
      { prop: 'email', label: '邮箱', model: { tag: 'el-input', attrs: { maxlength: 30 } } }
    ]

    this.rules = {
      username: { required: true, message: '用户名输入不合法', trigger: 'blur', validator: (r, v, c) => c(v && /^\w+$/.test(v) ? undefined : 1) },
      name: { required: true, message: '姓名输入不合法', trigger: 'blur', validator: (r, v, c) => c(v && /^\S+$/.test(v) ? undefined : 1) },
      org: { required: true, message: '请选择组织', trigger: 'change' },
      role: { required: true, message: '请选择角色', trigger: 'change' },
      idcard: { message: '身份证号输入不合法', trigger: 'blur', validator: (r, v, c) => c(v && !/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/.test(v) ? 1 : undefined) },
      phone: { message: '电话输入不合法', trigger: 'blur', validator: (r, v, c) => c(v && !/^1[3456789]\d{9}$/.test(v) ? 1 : undefined) },
      email: { message: '邮箱输入不合法', trigger: 'blur', validator: (r, v, c) => c(v && !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/.test(v) ? 1 : undefined) }
    }

    this.findAllUser()
  },

  activated () {
    this.findAllOrg()
    this.findAllRole()
  },

  methods: {
    async findAllTeacher () {
      const { data } = await findAllTeacherApi()
      this.form_manage_teacher.model.options = data
    },
    toBatchAdd () {
      this.$router.push('/system/user/batch-add')
    },
    async findAllUser () {
      const { data: { list, total } } = await findAllUserApi({
        ...this.find_user_params,
        org: [...this.find_user_params.org].pop(),
        role: [...this.find_user_params.role].pop(),
        ...this.pageInfo
      })
      this.user_list = list
      this.pageInfo.total = total
    },

    async findAllOrg () {
      const { data } = await findAllOrgApi()
      const { tree } = data.toTree()
      this.org_options.splice(0, this.org_options.length, ...tree)
    },

    async findAllRole () {
      const { data } = await findAllRoleApi()
      const { tree } = data.toTree()
      this.role_options.splice(0, this.role_options.length, ...tree)
    },

    toCreateUser () {
      const form = { photoResource: null }
      for (const { prop } of this.form_items) {
        form[prop] = undefined
      }
      form.manageTeacher = undefined
      form.sex = 1
      this.form_data = form
    },

    onTableSelectionChange (selection) {
      this.activeUsers = selection.map(v => v.id)
    },

    async toResetPassword (row) {
      await this.$confirm(`将重置【${row.name}】的密码，是否继续？`, '操作提示', {
        type: 'warning'
      })
      await resetPasswordApi(row.id)
      this.$message.success('密码重置成功')
    },

    toUpdate (row) {
      this.form_data = {
        ...row,
        photoResource: row.photoResource?.diskname,
        manageTeacher: row.manageTeacher.map(v => v.teacher),
        role: [row.roleId],
        org: row.orgIds.split(',').map(Number)
      }
    },

    async toDeletes (userId) {
      const userIds = [].concat(userId || this.activeUsers || [])
      if (!userIds.length) return this.$message.error('请选择要删除的用户')

      await this.$store.inputCheckAdminPassword(`删除用户：${userIds.length}个`)

      await deleteUsersApi(userIds)
      this.findAllUser()
    },

    async toUploadPhoto () {
      const [file] = await getDistFile({ accepts: ['image'] })
      this.form_data.photoResource = file
    },

    async onConfirm () {
      await this.$refs.formLayoutRef.validate()

      const { role, org, photoResource, ...form } = this.form_data
      form.roleId = role[0]
      form.orgId = org[org.length - 1]
      form.orgIds = org.join(',')

      if (photoResource instanceof File) {
        const { data } = await uploadApi(photoResource, { data: { type: 'avatar' } })
        form.photo = data.id
      }

      await (!this.form_data.id ? createUserApi : updateUserApi)(form)

      if (this.role_options.find(v => v.id === form.roleId)?.base !== 3) this.form_manage_teacher.model.options = null
      this.form_data = null
      this.findAllUser()
    }
  }
}
</script>

<style lang="scss" scoped>
._photo {
  width: 120px;
  height: 90px;
  padding: 3px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #dcdfe6;
  cursor: pointer;
  position: relative;

  &::after {
    content: attr(data-hint);
    position: absolute;
    left: 110%;
    top: 50px;
    margin-top: -16%;
    white-space: nowrap;
    color: #333;
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  ._icon {
    font-size: 20px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  &:hover {
    color: $--color-primary;
    border-color: $--color-primary;
  }
}
</style>
