<template>
  <CommonPage show-footer :title="$route.title">
    <n-button v-perms="['/admin/manage/set']" type="primary" @click="openModal(1)">
      添加管理员
    </n-button>
    <n-data-table
      class="mt-5"
      :loading="loading"
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :bordered="false"
      remote
    />
    <n-modal v-model:show="showModal">
      <n-card
        style="width: 600px"
        title="添加/编辑角色"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <n-form ref="formRef" :model="model" :rules="rules" label-placement="left">
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="16" label="名称:" path="Name">
              <n-input v-model:value="model.Name" placeholder="请输入管理员名称" />
            </n-form-item-gi>
            <n-form-item-gi :span="16" label="账号:" path="Phone">
              <n-input v-model:value="model.Phone" placeholder="请输入管理员账号（手机号码）" />
            </n-form-item-gi>
            <n-form-item-gi v-if="nowType === 1" :span="16" label="密码:" path="Password">
              <n-input v-model:value="model.Password" placeholder="请输入管理员密码" />
            </n-form-item-gi>
            <n-form-item-gi v-else :span="16" label="新密码:">
              <n-input v-model:value="model.Password" placeholder="不修改请留空" />
            </n-form-item-gi>
            <n-form-item-gi :span="16" label="角色:" path="AuthId">
              <n-select
                v-model:value="model.AuthId"
                multiple
                :options="roles"
                label-field="name"
                value-field="ID"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="16" label="角色状态:" path="Status">
              <n-switch v-model:value="model.Status" :unchecked-value="2" :checked-value="1" />
            </n-form-item-gi>
            <n-form-item-gi :span="18">
              <div m-auto>
                <n-button type="primary" @click="handleValidateClick">保存</n-button>
                <n-button ml-10 @click="clear">取消</n-button>
              </div>
            </n-form-item-gi>
          </n-grid>
        </n-form>
      </n-card>
    </n-modal>
  </CommonPage>
</template>

<script setup>
import { h, withDirectives, resolveDirective } from 'vue'
import api from '../api'
import { NTag, NButton } from 'naive-ui'
const vPerms = resolveDirective('perms')

const loading = ref(false)

const columns = ref([
  {
    title: '管理员名称',
    key: 'name',
    align: 'center',
  },
  {
    title: '账号',
    key: 'phone',
    align: 'center',
  },
  {
    title: '角色',
    slot: 'auth_id',
    align: 'center',
    render: (row) => {
      const nowRow = { ...row, auth_id: JSON.parse(row.auth_id) }
      const roleName = []
      roles.value.forEach((item) => {
        nowRow.auth_id.forEach((itm) => {
          if (item.ID === itm) {
            roleName.push(item.name)
          }
        })
      })
      return h(
        'span',
        {},
        {
          default: () => roleName.join(' | '),
        }
      )
    },
  },
  {
    title: '角色状态',
    slot: 'status',
    align: 'center',
    render: (row) => {
      return h(
        NTag,
        {
          type: row.status === 1 ? 'success' : 'warning',
        },
        {
          default: () => (row.status === 1 ? '启用' : '禁用'),
        }
      )
    },
  },
  {
    title: '操作',
    slot: 'action',
    align: 'center',
    render: (row) => {
      return [
        withDirectives(
          h(
            NButton,
            {
              text: true,
              onClick: () => {
                openModal(2, row)
              },
            },
            {
              default: () => '编辑',
            }
          ),
          [[vPerms, ['/admin/manage/set']]]
        ),
        withDirectives(
          h(
            NButton,
            {
              class: 'ml-10',
              type: 'error',
              text: true,
              onClick: () => {
                delVerifyUser(row)
              },
            },
            {
              default: () => '删除',
            }
          ),
          [[vPerms, ['/admin/manage/delete']]]
        ),
      ]
    },
  },
])

const data = ref([])

const showModal = ref(false)

const model = ref({
  Name: '',
  AuthId: null,
  Phone: '',
  Password: '',
  Status: 2,
})

const rules = {
  Name: {
    required: true,
    message: '请输入角色名称',
    trigger: 'blur',
  },
  AuthId: {
    required: true,
    type: 'array',
    message: '请选择分配权限',
    trigger: ['blur'],
  },
  Phone: {
    required: true,
    message: '请输入管理员账号（手机号码）',
    trigger: 'blur',
  },
  Password: {
    required: true,
    message: '请输入管理员密码',
    trigger: 'blur',
  },
}

const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  onChange: (page) => {
    pagination.value.page = page
    getList()
  },
})

onMounted(() => {
  getList()
  get_role_list()
})

const getList = async () => {
  loading.value = true
  try {
    const res = await api.getAdminList({
      pageNum: 1,
      pageSize: 10,
    })
    data.value = res.data.data || []
    pagination.value.itemCount = res.data.total
  } catch (error) {
    $message.error(error.msg)
    throw error
  }
  loading.value = false
}

const roles = ref([])

const get_role_list = async () => {
  const res = await api.getRoleList()
  roles.value = res.data.data || []
}

const nowType = ref(1)

const openModal = (type, row = {}) => {
  nowType.value = type
  get_role_list()
  if (type === 2) {
    model.value = {
      ID: row.ID,
      Name: row.name,
      AuthId: JSON.parse(row.auth_id),
      Status: row.status,
      Phone: row.phone,
    }
  }
  showModal.value = true
}

const clear = () => {
  formRef.value?.restoreValidation()
  model.value = {
    Name: '',
    AuthId: null,
    Phone: '',
    Password: '',
    Status: 2,
  }
  showModal.value = false
  getList()
}

const formRef = ref(null)

const handleValidateClick = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) {
      const res = await api.addAdmin(model.value)
      $message.success(res.msg)
      clear()
    }
  })
}

const delVerifyUser = async (row) => {
  $dialog.error({
    title: '提示',
    content: '删除无法撤销，请谨慎！',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const res = await api.delVerifyUser({
        uid: row.uid,
      })
      $message.success(res.msg)
      getList()
    },
  })
}
</script>

<style lang="scss" scoped></style>
