<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getRoleListApi, addRoleApi, setRoleApi, delRoleApi } from '@/api/system/role'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElTag, ElMessage, ElMessageBox, ElDivider } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getRoleListApi({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
      type: 3,
      role_name: searchParams.value.role_name || '',
      status:
        searchParams.value.status !== undefined
          ? (searchParams.value.status as string | number)
          : ''
    })
    return {
      list: res.data.list || [],
      total: res.data.total
    }
  }
})

const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    width: '80px',
    label: 'ID'
  },
  {
    field: 'role_name',
    label: t('role.roleName'),
    minWidth: '100px'
  },
  {
    field: 'status',
    label: t('menu.status'),
    align: 'center',
    headerAlign: 'center',
    width: 100,
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElTag type={data.row.status === 0 ? 'danger' : 'success'}>
              {data.row.status === 1 ? t('userDemo.enable') : t('userDemo.disable')}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'rules',
    label: '权限',
    minWidth: '150px'
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    align: 'center',
    headerAlign: 'center',
    width: 120,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'role_name',
    label: t('role.roleName'),
    component: 'Input'
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '启用',
          value: 1
        },
        {
          label: '禁用',
          value: 0
        }
      ]
    }
  }
])

const searchParams = ref({
  status: '',
  role_name: ''
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', '删除', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delRoleApi({ id: row.id }).then(() => {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        getList()
      })
    })
    .catch(() => {})
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const deepMenu = (data: Array<any>) => {
  const menu: any[] = []
  data.forEach((item) => {
    menu.push(item.id)
    if (item.children) {
      menu.push(...deepMenu(item.children))
    }
  })
  return menu
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  // console.log(formData, 'data')
  if (formData) {
    saveLoading.value = true
    try {
      let res: any = {}
      const data = {
        type: 3,
        checked_menus: deepMenu(formData.menu),
        role_name: formData.role_name,
        status: formData.status,
        id: currentRow.value ? currentRow.value.id : ''
      }
      if (actionType.value == 'edit') {
        res = await setRoleApi(data)
      } else {
        res = await addRoleApi(data)
      }

      if (res?.status === 200) {
        ElMessage({
          message: '添加成功',
          type: 'success'
        })
        dialogVisible.value = false
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      stripe
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
