<template>
  <MySplitPanes>
    <pane size="55" min-size="35" max-size="65">
      <div class="my-flex-column w100 h100">
        <el-card class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" @submit.stop.prevent>
            <el-form-item label="看板名称">
              <el-input v-model="state.filter.name" placeholder="看板名称" @keyup.enter="onQuery" />
            </el-form-item>
            <el-form-item label="关键词">
              <el-input v-model="state.filter.keywords" placeholder="关键词" @keyup.enter="onQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
              <el-button v-auth="'api:admin:board:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增 </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="my-fill mt8" shadow="never">
          <el-table
            ref="boardTableRef"
            v-loading="state.loading"
            :data="state.boardListData"
            default-expand-all
            highlight-current-row
            style="width: 100%"
            @current-change="onTableCurrentChange"
            border
          >
            <el-table-column prop="name" label="看板名称" min-width="120" show-overflow-tooltip />
            <el-table-column prop="description" label="功能简介" min-width="150" show-overflow-tooltip />
            <el-table-column prop="keywords" label="关键词" min-width="120" show-overflow-tooltip />
            <el-table-column prop="url" label="网址" min-width="150" show-overflow-tooltip>
              <template #default="{ row }">
                <el-link v-if="row.url" :href="row.url" target="_blank" type="primary">{{ row.url }}</el-link>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="90" align="center" sortable="custom" show-overflow-tooltip />
            <el-table-column label="状态" width="82" align="center">
              <template #default="{ row }">
                <el-tag type="success" v-if="row.enabled">启用</el-tag>
                <el-tag type="danger" v-else>禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" width="160" align="center" show-overflow-tooltip />
            <el-table-column label="操作" width="140" fixed="right" header-align="center" align="center">
              <template #default="{ row }">
                <el-button v-auth="'api:admin:board:update'" icon="ele-EditPen" text type="primary" @click="onEdit(row)">编辑</el-button>
                <el-button v-auth="'api:admin:board:delete'" icon="ele-Delete" text type="danger" @click="onDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 10px">
            <el-pagination
              v-model:currentPage="state.pageInput.currentPage"
              v-model:page-size="state.pageInput.pageSize"
              :total="state.total"
              :page-sizes="[10, 20, 50, 100]"
              background
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </div>
    </pane>
    <pane>
      <div class="my-flex-column w100 h100">
        <el-card class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" @submit.stop.prevent>
            <el-form-item label="姓名">
              <el-input v-model="state.userFilter.name" placeholder="姓名" @keyup.enter="onGetBoardUserList" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onGetBoardUserList"> 查询 </el-button>
              <el-button v-auth="'api:admin:board:add-board-user'" type="primary" icon="ele-Plus" @click="onAddUser"> 添加 </el-button>
              <el-button v-auth="'api:admin:board:remove-board-user'" type="danger" icon="ele-Delete" @click="onRemoveUser"> 移除 </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="my-fill mt8" shadow="never">
          <el-table
            ref="userTableRef"
            v-loading="state.userListLoading"
            :data="state.userListData"
            :row-key="getRowKey"
            style="width: 100%"
            border
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="姓名" min-width="120" show-overflow-tooltip />
            <el-table-column prop="mobile" label="手机号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
           </el-table>
        </el-card>
      </div>
    </pane>

    <board-form ref="boardFormRef" :title="state.boardFormTitle"></board-form>
    <user-select
      ref="userSelectRef"
      :title="`添加【${state.boardName}】人员`"
      multiple
      :sure-loading="state.sureLoading"
      @sure="onSureUser"
    ></user-select>
  </MySplitPanes>
</template>

<script lang="ts" setup name="admin/board">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { BoardGetPageOutput, PageInputBoardGetPageInput, SortInput, BoardGetBoardUserListOutput, BoardAddBoardUserListInput, BoardRemoveBoardUserInput, UserGetPageOutput } from '/@/api/admin/data-contracts'
import { BoardApi } from '/@/api/admin/Board'
import eventBus from '/@/utils/mitt'
import { Pane } from 'splitpanes'
import { ElTable } from 'element-plus'
import dayjs from 'dayjs'

// 引入组件
const BoardForm = defineAsyncComponent(() => import('./components/board-form.vue'))
const UserSelect = defineAsyncComponent(() => import('/@/views/admin/user/components/user-select.vue'))
const MySplitPanes = defineAsyncComponent(() => import('/@/components/my-layout/split-panes.vue'))

const { proxy } = getCurrentInstance() as any

const boardTableRef = ref()
const boardFormRef = ref()
const userTableRef = ref<InstanceType<typeof ElTable>>()
const userSelectRef = ref()

const defalutSort = { prop: 'sort', order: 'ascending' }

const getSortList = (data: { prop: string; order: any }) => {
  return [
    {
      propName: data.prop,
      order: data.order === 'ascending' ? 0 : data.order === 'descending' ? 1 : undefined,
    },
  ] as [SortInput]
}

const state = reactive({
  loading: false,
  userListLoading: false,
  sureLoading: false,
  boardFormTitle: '',
  filter: {
    name: '',
    keywords: '',
  },
  defalutSort: defalutSort,
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    sortList: getSortList(defalutSort),
  } as PageInputBoardGetPageInput,
  boardListData: [] as Array<BoardGetPageOutput>,
  userFilter: {
    name: ''
  },
  userListData: [] as BoardGetBoardUserListOutput[],
  boardId: undefined as number | undefined,
  boardName: '' as string | null | undefined,
})

onMounted(async () => {
  await onQuery()
  eventBus.off('refreshBoard')
  eventBus.on('refreshBoard', () => {
    onQuery()
  })
})

onBeforeMount(() => {
  eventBus.off('refreshBoard')
})

const formatterTime = (row: any, column: any, cellValue: any) => {
  return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : ''
}

// 生成唯一的行键，使用数组索引确保唯一性
const getRowKey = (row: BoardGetBoardUserListOutput, index: number) => {
  return `user_${state.boardId}_${row.userId}_${index}`
}

const onQuery = async () => {
  state.loading = true
  state.pageInput.filter = state.filter
  const res = await new BoardApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })

  state.boardListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0

  if (state.boardListData?.length > 0) {
    window.setTimeout(() => {
      boardTableRef.value?.setCurrentRow(state.boardListData[0])
    }, 100)
  }

  state.loading = false
}

const onAdd = () => {
  state.boardFormTitle = '新增看板'
  boardFormRef.value.open()
}

const onEdit = (row: BoardGetPageOutput) => {
  state.boardFormTitle = '编辑看板'
  boardFormRef.value.open(row)
}

const onDelete = (row: BoardGetPageOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除【${row.name}】?`)
    .then(async () => {
      await new BoardApi().softDelete({ id: row.id }, { loading: true, showSuccessMessage: true })
      onQuery()
    })
    .catch(() => {})
}

const onSizeChange = (val: number) => {
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}

const onSortChange = (data: { column: any; prop: string; order: any }) => {
  state.pageInput.sortList = getSortList(data)
  onQuery()
}

const onTableCurrentChange = (currentRow: BoardGetPageOutput) => {
  if (!currentRow) {
    return
  }

  state.boardId = currentRow.id
  state.boardName = currentRow.name
  onGetBoardUserList()
}

const onGetBoardUserList = async () => {
  state.userListLoading = true
  // 清空之前的选择
  userTableRef.value?.clearSelection()
  
  const res = await new BoardApi().getBoardUserList({ BoardId: state.boardId, Name: state.userFilter.name }).catch(() => {
    state.userListLoading = false
  })
  state.userListLoading = false
  if (res?.success) {
    if (res.data && res.data.length > 0) {
      state.userListData = res.data
    } else {
      state.userListData = []
    }
  }
}



const onAddUser = () => {
  if (!((state.boardId as number) > 0)) {
    proxy.$modal.msgWarning('请选择看板')
    return
  }
  userSelectRef.value.open({ boardId: state.boardId })
}

const onRemoveUser = () => {
  if (!((state.boardId as number) > 0)) {
    proxy.$modal.msgWarning('请选择看板')
    return
  }

  const selectionRows = userTableRef.value!.getSelectionRows() as BoardGetBoardUserListOutput[]
  console.log("🔍 ~  ~ src/views/admin/board/index.vue:286 ~ selectionRows:", selectionRows)

  if (!((selectionRows.length as number) > 0)) {
    proxy.$modal.msgWarning('请选择人员')
    return
  }

  proxy.$modal
    .confirm(`确定要移除吗?`)
    .then(async () => {
      const userIds = selectionRows?.map((a) => a.userId)
      const input = { boardId: state.boardId, userIds } as BoardRemoveBoardUserInput
      await new BoardApi().removeBoardUser(input, { loading: true })
      onGetBoardUserList()
    })
    .catch(() => {})
}

const onSureUser = async (users: UserGetPageOutput[]) => {
  if (!(users?.length > 0)) {
    userSelectRef.value.close()
    return
  }

  state.sureLoading = true
  const userIds = users?.map((a) => a.id)
  const input = { boardId: state.boardId, userIds } as BoardAddBoardUserListInput
  await new BoardApi().addBoardUser(input, { showSuccessMessage: true }).catch(() => {
    state.sureLoading = false
  })
  state.sureLoading = false
  userSelectRef.value.close()
  onGetBoardUserList()
}


</script>

<style scoped lang="scss"></style> 