import {
  NButton,
  NModal,
  NSpace,
  NDataTable,
  useDialog,
  useMessage,
  NTag,
  NFormItem,
  NCascader
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { sysApplicationPage, sysMenuPage, sysMenuRemove } from '../api'
import MenuOperation from './menu-operation'
import SaveForm from '@/components/save-form'
import { formatDataList } from '@/utils/urlUtils'

/* 
parentId 要结点
path 路径
name 名称
component 组件名
icon 图标
type 菜单 | 按钮
permission 权限
parentPermission 高亮路径
sort 菜单排序
hidden 是否隐藏
 */

export default defineComponent({
  name: 'menu-manage',
  setup() {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      applyList: [] as any,
      dataList: [] as any,
      visiableMenu: false,
      menuType: 'add',
      applyData: {} as any,
      expandedRowKeys: [],
      searchForm: {
        appId: null
      }
    })

    const columns = (): any => [
      {
        title: '菜单名称',
        key: 'name',
        width: 330,
        render(row: any) {
          return `${row.name} - ${row.id}`
        }
      },
      {
        title: '应用名称',
        key: 'appName'
      },
      {
        title: '组件名',
        key: 'component'
      },
      {
        title: '路由路径',
        key: 'path'
      },
      {
        title: '权限标识',
        key: 'permission'
      },
      {
        title: '排序',
        key: 'sort'
      },
      {
        title: '类型',
        key: 'type',
        render(row: any) {
          return row.type === '0' ? (
            <NTag type="primary">菜单</NTag>
          ) : (
            <NTag type="default">按钮</NTag>
          )
        }
      },
      {
        title: '操作',
        key: 'operation',
        render(row: any) {
          return (
            <NSpace>
              <NButton
                type="primary"
                text
                size="small"
                //v-auth="sysMenu/update1597877909171064833"
                onClick={() => {
                  state.visiableMenu = true
                  state.menuType = 'edit'
                  state.applyData = row
                }}
              >
                编辑
              </NButton>
              <NButton
                type="primary"
                text
                size="small"
                //v-auth="sysMenu/remove1597878074728632322"
                onClick={() => onRmove(row)}
              >
                删除
              </NButton>
            </NSpace>
          )
        }
      }
    ]

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

    const getList = async () => {
      try {
        state.loading = true
        state.expandedRowKeys = []
        const { data } = await sysMenuPage({
          ...state.searchForm,
          parentId: 0,
          delFlag: false
        })
        state.loading = false
        const tempList = [] as any
        ;(data || []).forEach((item: any) => {
          item.isLeaf = item.children ? false : true
          tempList.push(item)
        })

        state.dataList = formatDataList(tempList)
      } catch {}
    }

    const getApplyList = async (parentId = 0) => {
      try {
        const { data } = await sysApplicationPage({
          page: 1,
          rows: 999,
          leafQuery: true,
          parentId
        })
        state.applyList = formatDataList(data.rows || [], 'bizApps')
      } catch {}
    }

    const saveForm = ref()
    const onSubmit = () => {
      getList()
    }

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    onMounted(() => {
      getList()
      getApplyList()
    })
    return () => (
      <div class="system-menu-container">
        <h2>菜单管理</h2>

        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem label="应用" path="name">
            <NCascader
              v-model:value={state.searchForm.appId}
              options={state.applyList}
              showPath={true}
              allowCheckingNotLoaded={false}
              checkStrategy="child"
              valueField="id"
              labelField="appName"
              childrenField="bizApps"
              placeholder="请选择应用"
              expandTrigger="hover"
              clearable
            ></NCascader>
          </NFormItem>
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={onSearch}>
                搜索
              </NButton>
              <NButton type="default" onClick={onBtnReset}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>

        <div class={['section-container']}>
          <NSpace style={{ paddingBottom: '12px' }} justify="space-between">
            <NButton
              type="primary"
              //v-auth="sysMenu/save1597877997041733633"
              onClick={() => {
                state.menuType = 'add'
                state.applyData = []
                state.visiableMenu = true
              }}
            >
              添加菜单
            </NButton>
          </NSpace>
          <NDataTable
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
            allowCheckingNotLoaded
            cascade={false}
            virtualScroll
            maxHeight={400}
            expandedRowKeys={state.expandedRowKeys}
            onUpdateExpandedRowKeys={(keys: any) => {
              state.expandedRowKeys = keys
            }}
            rowKey={(row: any) => row.id}
          ></NDataTable>
        </div>

        <NModal
          v-model:show={state.visiableMenu}
          preset="dialog"
          showIcon={false}
          title={state.menuType === 'add' ? '添加菜单' : '修改菜单'}
          style={{ width: '700px' }}
        >
          <MenuOperation
            type={state.menuType}
            data={state.applyData}
            menuList={state.dataList}
            applyList={state.applyList}
            onClose={() => (state.visiableMenu = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
