<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getMenuListApi, newMenuApi, setMenuApi, delMenuApi } from '@/api/system/menu'
import { addRoleData } from '@/api/system/menu/types'
import { roluData } from '@/utils/analysis'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElTag, ElMessageBox, ElDivider } from 'element-plus'
import { Icon } from '@/components/Icon'
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 { BaseButton } from '@/components/Button'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    try {
      const res = await getMenuListApi(searchParams.value)
      const list = await roluData(res.data.list)
      return {
        list: list || [],
        total: res.data.count || 0
      }
    } catch (e) {
      // console.log(e, 'err')
      return {
        list: [],
        total: 0
      }
    }
  }
})
const { dataList, loading } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID'
  },
  {
    field: 'meta.title',
    label: t('menu.menuName'),
    minWidth: 120,
    slots: {
      default: (data: any) => {
        const title = data.row.meta.title
        return <>{title}</>
      }
    }
  },
  {
    field: 'meta.icon',
    label: t('menu.icon'),
    align: 'center',
    headerAlign: 'center',
    width: 60,
    slots: {
      default: (data: any) => {
        const icon = data.row.meta.icon
        if (icon) {
          return (
            <>
              <Icon icon={icon} />
            </>
          )
        } else {
          return null
        }
      }
    }
  },
  {
    field: 'type',
    label: '类型',
    align: 'center',
    headerAlign: 'center',
    width: 60,
    slots: {
      default: (data: any) => {
        return <>{data.row.type == 1 ? '菜单' : '接口'}</>
      }
    }
  },
  {
    field: 'apiUrl',
    label: '接口地址',
    minWidth: 120,
    slots: {
      default: (data: any) => {
        return <>{data.row.apiUrl}</>
      }
    }
  },
  {
    field: 'unique_auth',
    label: '权限标识',
    width: 200
  },
  {
    field: 'path',
    label: t('menu.path'),
    minWidth: 200
  },
  {
    field: 'status',
    label: t('menu.status'),
    align: 'center',
    headerAlign: 'center',
    width: 80,
    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: 'sort',
    label: '排序',
    align: 'center',
    headerAlign: 'center',
    minWidth: 60
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 150,
    fixed: 'right',
    align: 'center',
    headerAlign: 'center',
    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="success" onClick={() => action(row, 'detail')}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'is_show',
    label: t('menu.status'),
    component: 'Select',
    componentProps: {
      options: [
        {
          label: t('userDemo.disable'),
          value: 0
        },
        {
          label: t('userDemo.enable'),
          value: 1
        }
      ]
    }
  },
  {
    field: 'type',
    label: '类型',
    value: 2, //1总后台2门店
    component: 'Input',
    hidden: true
  },
  {
    field: 'keyword',
    label: t('menu.menuName'),
    component: 'Input'
  }
])

const searchParams = ref({ type: 2 })
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) => {
  // console.log(row, 'rowdate')
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

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

const delAction = async (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delMenuApi({ id: row.id })
      await getList()

      ElMessage({
        showClose: true,
        message: '删除',
        type: 'success'
      })
    })
    .catch(() => {})
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const data: addRoleData = {
      id: formData.id,
      menu_name: formData.meta.title, //名称
      icon: formData.meta.icon, //图标
      params: '', //参数
      menu_path: formData.path, //路由地址
      api_url: formData.apiUrl, //接口地址
      methods: formData.methods, //请求方式 post get delete
      unique_auth: formData.unique_auth, //唯一标识
      pid: formData.parentId, //父id
      sort: formData.sort, //排序
      auth_type: formData.type === 2 ? 2 : 1, //权限类型 1 菜单，2功能
      is_show: formData.status, //是否禁用1启用0禁用
      is_show_path: formData.meta.hidden ? 1 : 0, //是否显示路由0显示1隐藏
      extend: formData,
      type: 2
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        res = await setMenuApi(data)
      } else if (actionType.value === '') {
        res = await newMenuApi(data)
      }
      if (res.status == 200) {
        ElMessage({
          showClose: true,
          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
      :columns="tableColumns"
      node-key="id"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
    />
  </ContentWrap>

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

    <Detail v-if="actionType === 'detail'" :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>
