<script setup lang="tsx">
import { onMounted, reactive, ref, unref } from 'vue'
import {
  getSysMenuListApi,
  saveSysMenuApi,
  delSysMenuListApi,
  delSysMenuApi,
  querySysMenuApi
} from '@/api/system/SysMenu'
import { TableData } from '@/api/role/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  ElButton,
  ElLink,
  ElLoading,
  ElPopconfirm,
  ElMessage,
  ElRow,
  ElCol,
  ElTree
} 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 Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { TYPE_DICT_LIST, COMMON_DICT_LIST, STATUS_DICT_LIST } from './constants'
import { getMenuTreeApi } from '@/api/common'

defineOptions({
  name: 'SysMenu'
})

const { t } = useI18n()

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getSysMenuListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.body.list,
      total: res.body.total
    }
  },
  fetchDelApi: async () => {
    const res = await delSysMenuListApi(unref(ids))
    return !!res
  }
})

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

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'name',
    label: '菜单名称'
  },
  {
    field: 'parentId',
    label: '上级菜单'
  },
  {
    field: 'type',
    label: '菜单类型',
    minWidth: 120,
    formatter: (row: Recordable, __: TableColumn) => {
      const type = TYPE_DICT_LIST.find((item) => item.value === row.type)
      if (type) {
        return type.label
      }
      return '-'
    }
  },
  {
    field: 'common',
    label: '权限类型',
    minWidth: 120,
    formatter: (row: Recordable, __: TableColumn) => {
      const common = COMMON_DICT_LIST.find((item) => item.value === row.common)
      if (common) {
        return common.label
      }
      return '-'
    }
  },
  {
    field: 'systemCode',
    label: '归属系统'
  },
  {
    field: 'sort',
    label: '排序'
  },
  {
    field: 'status',
    label: '状态',
    minWidth: 80,
    formatter: (row: Recordable, __: TableColumn) => {
      const status = STATUS_DICT_LIST.find((item) => item.value === row.status)
      if (status) {
        return status.label
      }
      return '-'
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 160,
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
              {t('tableDemo.edit')}
            </ElLink>
            <ElPopconfirm
              title={t('common.delTableMsg')}
              width={200}
              v-slots={{
                reference: () => {
                  return (
                    <>
                      <ElLink type="primary" underline={false}>
                        {t('tableDemo.del')}
                      </ElLink>
                    </>
                  )
                }
              }}
              onConfirm={() => delData(data.row)}
            ></ElPopconfirm>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
              {t('tableDemo.detail')}
            </ElLink>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '菜单名称',
    component: 'Input'
  }
])

const searchParams = ref({})
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 action = async (row: any, type: string) => {
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await querySysMenuApi(row.id)
    .catch(() => {})
    .finally(() => {
      detailLoading.close()
    })
  detailLoading.close()
  if (res) {
    const data = res.body.result
    dialogTitle.value = t(type === 'edit' ? 'tableDemo.edit' : 'tableDemo.detail')
    actionType.value = type
    currentRow.value = data
    dialogVisible.value = true
  }
}

const AddAction = (e: MouseEvent, node?: TableData) => {
  e.preventDefault()
  e.stopPropagation()
  dialogTitle.value = t('tableDemo.add')
  currentRow.value = node ? { parentId: node.id, type: '1' } : undefined
  dialogVisible.value = true
  actionType.value = ''
}

const saveLoading = ref(false)

/** 保存 **/
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveSysMenuApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
      getMenuTreeApi().then((res) => (treeData.value = res))
    }
  }
}

/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delSysMenuApi(row.id)
  if (res) {
    const { code, errMsg } = res.head
    if (code === '0') {
      ElMessage.success('删除成功!')
      getList()
    } else {
      ElMessage.error(errMsg || '删除失败!')
    }
  }
}

const disabled = ref(true)

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0
}

const treeData = ref<any>([])

onMounted(() => {
  getMenuTreeApi().then((res) => (treeData.value = res))
})

const defaultProps = { children: 'childs', label: 'nodeName' }
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <ElRow>
      <ElCol :span="6" style="padding: 10px"
      ><ElTree :data="treeData" :props="defaultProps" nodeKey="id">
        <template #default="{ node, data }">
          <span class="r-tree-title">
            <span class="r-plain-tree-title">{{ node.label }}</span>
            <span>
              <ElLink :underline="false" @click="(e) => AddAction(e, data)">
                <Icon icon="ep:circle-plus" :size="14" />
              </ElLink>
              <ElLink :underline="false" @click="() => action(data, 'edit')">
                <Icon icon="ep:edit" :size="14" />
              </ElLink>
              <ElPopconfirm
                @confirm="() => delData(data)"
                :title="t('common.delTableMsg')"
                :width="200"
              >
                <template #reference>
                  <ElLink :underline="false">
                    <Icon icon="ep:remove" :size="14" />
                  </ElLink>
                </template>
              </ElPopconfirm>
            </span>
          </span>
        </template>
      </ElTree>
      </ElCol>
      <ElCol :span="18">
        <Table
          :columns="tableColumns"
          v-model:pageSize="pageSize"
          v-model:currentPage="currentPage"
          default-expand-all
          node-key="id"
          :data="dataList"
          :loading="loading"
          :pagination="{
            total
          }"
          @selection-change="onSelectionChange"
          @register="tableRegister"
          @refresh="refresh"
        >
          <template #buttons>
            <ElButton type="primary" @click="(e) => AddAction(e)">{{
              t('tableDemo.add')
            }}</ElButton>
          </template>
        </Table>
      </ElCol>
    </ElRow>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :action-type="actionType"
    />
    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('dialogDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
.el-tree-node {
  .el-link {
    opacity: 0;
    margin-left: 6px;
  }
}

.el-tree-node__content:hover .el-link {
  opacity: 1;
}
</style>
