<template>
  <div>
    <a-card class="general-card" style="min-height: 75vh">
      <template #title>
        <a-row>
          <a-col :flex="1">
            <a-form
              :model="filterForm"
              :label-col-props="{ span: 6 }"
              :wrapper-col-props="{ span: 18 }"
              label-align="left"
              auto-label-width
            >
              <a-row :gutter="8">
                <a-col :span="18">
                  <a-form-item field="keyword" label="模糊匹配" :no-style="true"
                    ><a-input-search
                      v-model="filterForm.keyword"
                      placeholder="根据角色名称模糊匹配"
                      allow-clear
                      @search="filterRole()"
                      @clear="filterRole()"
                      @keyup.enter="filterRole()"
                    />
                  </a-form-item>
                </a-col>

                <a-col :span="6">
                  <a-button
                    v-permission="[Api.SYSTEM_ROLE_ADD]"
                    type="outline"
                    @click="showRoleModal(0)"
                  >
                    <template #icon>
                      <icon-plus />
                    </template>
                    添加角色
                  </a-button>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
      </template>
      <a-divider style="margin-top: 0; margin-bottom: 0" />
      <a-table
        :columns="tableColumns"
        :data="roleList"
        :bordered="{
          cell: false,
          headerCell: true,
          wrapper: false
        }"
        :row-class="selectRowClass"
        :hoverable="false"
        table-layout-fixed
        @row-click="selectCurrentRole"
      >
        <template #operate="{ record }">
          <!-- <a-button
            v-permission="[Api.SYSTEM_ROLE_GET_GROUP_TREE]"
            type="primary"
            class="info"
            title="设置权限"
            @click="showSetFuncDialog(record)"
          >
            <template #icon>
              <icon-settings />
            </template>
          </a-button> -->
          <a-button
            v-permission="[Api.SYSTEM_ROLE_MODIFY]"
            type="primary"
            status="success"
            title="修改信息"
            @click="showRoleModal(1, record)"
          >
            <template #icon>
              <icon-edit />
            </template>
          </a-button>
          <a-button
            v-permission="[Api.SYSTEM_ROLE_REMOVE]"
            type="primary"
            status="danger"
            title="删除角色"
            @click="handleRemoveRole(record)"
          >
            <template #icon>
              <icon-delete />
            </template>
          </a-button>
        </template>
      </a-table>
    </a-card>
    <!-- </a-col> -->
    <!-- </a-row> -->
    <vModal
      v-model:visible="visibleRoleModal"
      :title="modalTitle"
      @modal-handle-ok="roleHandleOk"
      @modal-handle-cancel="roleHandleCancel"
    >
      <div style="padding: 10px 15px">
        <a-form
          ref="roleFormRef"
          :model="roleForm"
          :auto-label-width="true"
          label-align="right"
          :rules="roleFormRules"
        >
          <a-form-item field="id" label="角色ID" show-colon>
            <a-input
              v-model="roleForm.id"
              placeholder="请输入角色ID"
              :disabled="modalType === 1"
            />
          </a-form-item>
          <a-form-item field="name" label="角色名称" show-colon>
            <a-input v-model="roleForm.name" placeholder="请输入角色名称" />
          </a-form-item>
        </a-form>
      </div>
    </vModal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, h } from 'vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import {
  Modal,
  Message,
  TableData,
  TableColumnData
} from '@arco-design/web-vue'
import { Role, RoleListResParams } from '@/types/role'
import { addRole, getRoleList, modifyRole, removeRole } from '@/api/acs/role'
import { Role as Api } from '@/enums/api'
import vModal from '@/components/modal/index.vue'
import { useEmitt } from '@/logics/mitt/useEmitt'

const roleFormRef = ref<FormInstance>()
const visibleRoleModal = ref(false) // 是否显示role对话框
const modalType = ref(0) // 对话框类型，0：添加，1：修改
const modalTitle = ref('') // 对话框标题
const selectRoleId = ref<string>()
const selectRoleName = ref<string>()
const { emitter } = useEmitt()

/**
 * 条件筛选表单
 */
const filterForm = reactive<{
  keyword?: string
}>({
  keyword: undefined
})

const roleForm = reactive<{
  id: string
  name: string
}>({
  id: '',
  name: ''
})

const roleFormRules = {
  id: [
    { required: true, message: '角色ID不能未空', trigger: 'blur' },
    {
      minLength: 2,
      maxLength: 20,
      message: '标记长度大于2个字节，且小于20个字节',
      validateTrigger: ['blur', 'change']
    }
  ],
  name: [
    { required: true, message: '名称不能未空', trigger: 'blur' },
    {
      minLength: 2,
      maxLength: 20,
      message: '名称长度大于2个字节，且小于20个字节',
      validateTrigger: ['blur', 'change']
    }
  ]
}

const tableColumns: TableColumnData[] = [
  {
    title: '角色ID',
    dataIndex: 'id',
    align: 'left'
  },
  {
    title: '角色名称',
    dataIndex: 'name',
    align: 'left'
  },
  {
    title: '操作',
    slotName: 'operate',
    align: 'right'
  }
]
const roleList = ref<Role[]>([]) // 角色列表
/**
 * 根据表单按条件筛选角色列表
 */
const filterRole = (): void => {
  getList().then(() => console.log('获取角色列表'))
}

/**
 * 获取用户列表
 */
const getList = async () => {
  const { keyword } = filterForm
  const { roles }: RoleListResParams = await getRoleList(keyword)
  roleList.value = roles
  if (roles.length > 0) {
    selectRoleId.value = roles[0].id
    selectRoleName.value = roles[0].name
    emitter.emit('changeRole', { id: roles[0].id, name: roles[0].name })
  }
}

/**
 * 隐藏role 对话框，重置表单
 */
const roleHandleCancel = () => {
  roleFormRef.value!.resetFields() // 初始化表单值
}

/**
 * 显示角色modal
 * @param type modal 类型
 * @param role
 */
const showRoleModal = (type: number, role?: Role) => {
  const isAdd = type === 0
  modalType.value = type
  if (isAdd) {
    modalTitle.value = `添加角色`
    visibleRoleModal.value = true
  } else {
    modalTitle.value = `修改 ${role!.name} 角色信息`
    const { id, name } = role!
    visibleRoleModal.value = true
    nextTick(() => {
      roleForm.id = role!.id
      roleForm.name = name
    })
  }
}

const selectRowClass = (record: TableData, rowIndex: number) => {
  if (selectRoleId.value === record.id) {
    return 'row-select-bg'
  }
  return 'row-initial'
}

/**
 * 点击表格行数据响应
 */
const selectCurrentRole = (record: TableData, ev?: Event) => {
  selectRoleId.value = record.id
  selectRoleName.value = record.name
  emitter.emit('changeRole', { id: record.id, name: record.name })
}

// /**
//  * 显示设置角色功能项对话框
//  * @param role 选中设置功能项对应行
//  */
// const showSetFuncDialog = async (role: Role) => {
//   roleForm.id = role.id
//   modalTitle.value = `设置 ${role.name} 角色功能项`
//   await getTree()
//   visibleAuthModal.value = true
// }

/**
 * 点击确认按钮时，cb(false)时不会继续后续操作
 * @param cb 回调函数，
 */
const roleHandleOk = async (cb: (closed: boolean) => void) => {
  const isValid = await roleFormRef.value?.validate()
  if (isValid) {
    return cb(false)
  }
  const isAdd = modalType.value === 0
  const { id, name } = roleForm
  if (isAdd) {
    await addRole(id, name)
    roleList.value.push({ id, name })
    Message.success('添加成功')
  } else {
    await modifyRole(id!, name)
    const index = roleList.value.findIndex((item: Role) => item.id === id)
    const item = roleList.value[index]
    item.name = name
    Message.success('修改成功')
  }
  return cb(true)
}

/**
 * 删除角色
 * @param role
 */
const handleRemoveRole = async (role: Role) => {
  const { id, name } = role
  const title = {
    setup() {
      return () => h('strong', '警告')
    }
  }
  const ModalContent = {
    setup() {
      return () =>
        h('span', { style: 'margin-left: 10px;' }, [
          h('span', `确认删除 `),
          h('strong', `${name}`),
          h('span', ` 角色吗？`)
        ])
    }
  }
  Modal.warning({
    title: () => h(title),
    content: () => h(ModalContent),
    alignCenter: true,
    titleAlign: 'start',
    draggable: true,
    escToClose: true,
    width: 300,
    simple: true,
    hideCancel: false,
    onOk: async () => {
      await removeRole(id)
      const index = roleList.value.findIndex(
        (item: { id: string }) => item.id === role.id
      )
      roleList.value.splice(index, 1)
      const leng = roleList.value.length
      if (leng > 0) {
        const currentRole = roleList.value[leng - 1]
        selectCurrentRole(currentRole)
      }
      Message.success('删除成功')
    }
  })
}

onMounted(async () => {
  try {
    getList().then(() => console.log('获取角色列表'))
  } catch (e) {
    console.log(e)
  }
})
</script>

<script lang="ts">
export default {
  name: 'RoleList'
}
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}
.dtree {
  padding: 0 10px;
  // max-height: 350px;
  :deep(.arco-tree-node-selected) {
    background-color: rgb(var(--gray-2));
  }
  :deep(.arco-tree-node:hover) {
    background-color: rgb(var(--gray-2));
  }
  :deep(.arco-tree-node-title:hover) {
    background-color: transparent;
  }
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
:deep(.row-select-bg) {
  .arco-table-td {
    cursor: pointer;
    background-color: rgb(var(--primary-2));
  }
}
:deep(.row-initial) {
  .arco-table-td {
    cursor: pointer;
  }
}
</style>

<style lang="less">
.dtree::-webkit-scrollbar {
  width: 12px !important;
  height: 4px !important;
}
.dtree::-webkit-scrollbar-thumb {
  border: 4px solid transparent;
  background-clip: padding-box;
  border-radius: 7px;
  background-color: var(--color-text-4);
}
</style>
