import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  NButton,
  NCascader,
  NDataTable,
  NFormItem,
  NInput,
  NModal,
  NSpace,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { sysApplicationPage, sysRolePage, sysRoleRemove } from '../api'
import RoleOperation from './role-operation'
import { formatDataList } from '@/utils/urlUtils'

export default defineComponent({
  name: 'subsidy-list',
  setup() {
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        appId: null,
        roleName: null
      },
      dataList: [] as any,
      applyList: [] as any,
      visiableRole: false,
      roleOperation: 'add',
      roleData: {} as any
    })
    const dialog = useDialog()
    const message = useMessage()

    const columns = () => {
      return [
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '应用名',
          key: 'appName'
        },
        {
          title: '角色名称',
          key: 'roleName'
        },
        {
          title: '角色状态',
          key: 'enable',
          render(row: any) {
            return row.enable ? <NTag type="primary">开启</NTag> : <NTag type="default">关闭</NTag>
          }
        },
        {
          title: '角色描述',
          key: 'roleDesc'
        },
        {
          title: '创建时间',
          key: 'createTime'
        },
        {
          title: '操作',
          key: 'operation',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="sysRole/update1674690192555945985"
                  onClick={() => {
                    state.visiableRole = true
                    state.roleOperation = 'edit'
                    state.roleData = row
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => onRemove(row)}
                  v-auth="sysRole/remove1674690265977237505"
                >
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

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

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await sysRolePage({ ...state.pagination, ...state.searchForm })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    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 = () => {
      state.pagination.page = 1
      getList()
    }

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

    onMounted(() => {
      getList()
      getApplyList()
    })
    return () => (
      <div class="system-menu-container">
        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem label="应用分类" path="appId">
            <NCascader
              v-model:value={state.searchForm.appId}
              options={state.applyList}
              showPath={true}
              allowCheckingNotLoaded={false}
              checkStrategy="child"
              valueField="id"
              labelField="appName"
              childrenField="bizApps"
              expandTrigger="hover"
              placeholder="请选择应用分类"
              clearable
            ></NCascader>
          </NFormItem>
          <NFormItem label="角色名称" path="roleName">
            <NInput v-model:value={state.searchForm.roleName} placeholder="请输入角色名称" />
          </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' }}>
            <NButton
              type="primary"
              v-auth="sysRole/save1674690114734829569"
              onClick={() => {
                state.visiableRole = true
                state.roleData = {}
                state.roleOperation = 'add'
              }}
            >
              添加角色
            </NButton>
          </NSpace>

          <NDataTable
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
          ></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.visiableRole}
          preset="dialog"
          showIcon={false}
          title={state.roleOperation === 'add' ? '新增角色' : '修改角色'}
          style={{ width: '600px' }}
        >
          <RoleOperation
            type={state.roleOperation}
            data={state.roleData}
            applyList={state.applyList}
            onClose={() => (state.visiableRole = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
