import Pagination from '@/components/pagination'
import { NButton, NModal, NSpace, NDataTable, useDialog, useMessage, NTag } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import { defineComponent, reactive, onMounted } from 'vue'
import { sysApplicationPage, sysApplicationRemove } from '../api'
import ApplyOperation from './apply-operation'

export default defineComponent({
  name: 'system-apply',
  setup() {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      dataList: [] as any,
      visiableApply: false,
      applyType: 'add',
      parentId: 0,
      applyData: {} as any,
      expandedRowKeys: []
    })

    type RowData = {
      id: number
      appName: string
      // parentId: number
      clientIds: string
      permissionFlag: boolean
      remark: string
    }
    const columns = (): DataTableColumns<RowData> => [
      {
        title: '编号',
        key: 'id'
      },
      {
        title: '应用名称',
        key: 'appName'
      },
      // {
      //   title: '应用分类',
      //   key: 'parentId'
      // },
      {
        title: '授权客户端',
        key: 'clientIds'
      },
      {
        title: '授权认证',
        key: 'permissionFlag',
        render(row: any) {
          return row.permissionFlag ? (
            <NTag type="primary">是</NTag>
          ) : (
            <NTag type="default">否</NTag>
          )
        }
      },
      {
        title: '备注',
        key: 'remark'
      },
      {
        title: '操作',
        key: 'operation',
        render(row: any) {
          return (
            <NSpace>
              <NButton
                type="primary"
                text
                size="small"
                //v-auth="sysApplication/update1597882903471443970"
                onClick={() => {
                  state.visiableApply = true
                  state.applyType = 'edit'
                  state.parentId = row.parentId
                  state.applyData = row
                }}
              >
                编辑
              </NButton>
              <NButton
                type="primary"
                text
                size="small"
                onClick={() => onRmove(row)}
                //v-auth="sysApplication/remove1597882985872740353"
              >
                删除
              </NButton>
            </NSpace>
          )
        }
      }
    ]

    const onRmove = (row: any): void => {
      console.log(row, 'row')
      dialog.warning({
        title: '警告',
        content: `删除"${row.appName}"，是否继续？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await sysApplicationRemove({ id: row.id })
            state.pagination.page = 1
            getList()
            message.success('删除成功')
          } catch {}
        }
      })
    }

    const getList = async () => {
      try {
        state.loading = true
        console.log(state.expandedRowKeys, 'expandedRowKeys')
        state.expandedRowKeys = []
        const { data } = await sysApplicationPage({
          ...state.pagination,
          parentId: 0
        })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        const tempList = [] as any
        ;(data.rows || []).forEach((item: any) => {
          item.isLeaf = item.number > 0 ? false : true
          tempList.push(item)
        })
        state.dataList = tempList
      } catch {}
    }

    const onLoad = async (row: any) => {
      try {
        const res = await sysApplicationPage({
          page: 1,
          rows: 999,
          parentId: row.id
        })
        const data = res.data.rows || []

        const tempList = [] as any
        data.forEach((item: any) => {
          tempList.push({ ...item, isLeaf: true })
        })
        row.children = tempList
      } catch {
        //
      }
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div class="system-menu-container">
        <h2>系统应用</h2>

        <div class={['section-container']}>
          <NSpace style={{ paddingBottom: '12px' }} justify="space-between">
            <NButton
              type="primary"
              //v-auth="sysApplication/save1597854675130122242"
              onClick={() => {
                state.applyType = 'add'
                state.parentId = 0
                state.applyData = {}
                state.visiableApply = true
              }}
            >
              添加应用
            </NButton>
          </NSpace>
          <NDataTable
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
            allowCheckingNotLoaded
            cascade={false}
            expandedRowKeys={state.expandedRowKeys}
            onUpdateExpandedRowKeys={(keys: any) => {
              state.expandedRowKeys = keys
            }}
            rowKey={(row: RowData) => row.id}
            onLoad={onLoad}
          ></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          ></Pagination>
        </div>

        <NModal
          v-model:show={state.visiableApply}
          preset="dialog"
          showIcon={false}
          title={state.applyType === 'add' ? '添加应用' : '修改应用'}
          style={{ width: '500px' }}
        >
          <ApplyOperation
            type={state.applyType}
            parentId={state.parentId}
            data={state.applyData}
            onClose={() => (state.visiableApply = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
