<template>
  <div class="mediaList">
    <Search :onClickSearch="onClickSearch" :onClickReset="onClickReset" />
    <div class="mediaList-table">
      <a-table :scroll="{ x: '100%', y: 500 }" rowKey="user_id" :loading="state.listLoading" :columns="columns"
        @change="refreshData" :rowClassName="rowClassName" :dataSource="state.list" :pagination="paginationConfig">
        <template v-for="col in ['mqtt_username', 'mqtt_password']" #[col]="{ text, record }" :key="col">
          <div>
            <a-input v-if="state.editableData[record.user_id]" v-model:value="state.editableData[record.user_id][col]"
              style="margin: -5px 0" />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template #action="{ record }">
          <div class="editable-row-operations">
            <span v-if="state.editableData[record.user_id]">
              <a-tooltip title="确定">
                <span @click="save(record)" style="color: #28d445;">
                  <CheckOutlined />
                </span>
              </a-tooltip>
              <a-tooltip title="取消">
                <span @click="() => delete state.editableData[record.user_id]" class="ml15" style="color: #e70102;">
                  <CloseOutlined />
                </span>
              </a-tooltip>
            </span>
            <span v-else class="fz18 flex-align-center flex-row" style="color: #2d8cf0">
              <a-tooltip title="编辑">
                <EditOutlined @click="edit(record)" />
              </a-tooltip>
            </span>
          </div>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { message } from 'ant-design-vue'
import { onMounted, reactive, UnwrapRef } from 'vue'
import Search from './components/Search.vue';
import { getAllUsersInfo, updateUserInfo } from '/@/api/manage'
import { ELocalStorageKey } from '/@/types'
import { EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons-vue'

export interface Member {
  user_id: string
  username: string
  user_type: string
  workspace_name: string
  create_time: string
  mqtt_username: string
  mqtt_password: string
}

interface State {
  listLoading: boolean,
  list: Member[],
  editableData: {
    [key: string]: any,
  },
}

const state: State = reactive({
  listLoading: false,
  list: [],
  editableData: {},
})

const paginationConfig = reactive({
  pageSizeOptions: ['20', '50', '100'],
  showQuickJumper: true,
  showSizeChanger: true,
  pageSize: 20,
  current: 1,
  total: 0
})

const workspaceId: string = localStorage.getItem(ELocalStorageKey.WorkspaceId)!

const fetchList = async (query?: any) => {
  state.listLoading = true;
  try {
    const res = await getAllUsersInfo(workspaceId, {
      ...query,
      page: paginationConfig.current,
      page_size: paginationConfig.pageSize,
    });
    state.list = res.data.list;
    paginationConfig.total = res.data.pagination.total
    paginationConfig.current = res.data.pagination.page
  } catch (e) {
    console.error(e);
  } finally {
    state.listLoading = false;
  }
}

onMounted(async () => {
  await fetchList()
})

const columns = [
  {
    title: '用户名称',
    dataIndex: 'username',
    width: 150,
    sorter: (a: Member, b: Member) => a.username.localeCompare(b.username),
  },
  {
    title: '用户类型',
    dataIndex: 'user_type',
    width: 150,
  },
  {
    title: '项目名称',
    dataIndex: 'workspace_name',
    width: 150,
  },
  {
    title: 'Mqtt 用户',
    dataIndex: 'mqtt_username',
    width: 150,
    slots: { customRender: 'mqtt_username' },
  },
  {
    title: 'Mqtt 密码',
    dataIndex: 'mqtt_password',
    width: 150,
    slots: { customRender: 'mqtt_password' },
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    width: 150,
    sorter: (a: Member, b: Member) => a.create_time.localeCompare(b.create_time),
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 80,
    slots: { customRender: 'action' },
  }
]

const rowClassName = (record: any, index: number) => {
  const className = []
  if ((index & 1) === 0) {
    className.push('table-striped')
  }
  return className.toString().replaceAll(',', ' ')
}

const refreshData = async (page: any) => {
  paginationConfig.current = page?.current!
  paginationConfig.pageSize = page?.pageSize!
  await fetchList();
}
// 点击编辑
const edit = (record: Member) => {
  state.editableData[record.user_id] = record;
}

// 点击保存
const save = (record: Member) => {
  delete state.editableData[record.user_id]
  updateUserInfo(workspaceId, record.user_id, record).then(res => {
    if (res.code !== 0) {
      message.error(res.message)
    }
  })
}

// 点击搜索
const onClickSearch = async (query: any) => {
  await fetchList(query);
}

// 点击重置
const onClickReset = async (query: any) => {
  await fetchList(query);
}
</script>

<style lang="scss">
.mediaList {
  padding: 20px;
}

.ant-table {
  border-top: 1px solid rgb(0, 0, 0, 0.06);
  border-bottom: 1px solid rgb(0, 0, 0, 0.06);
}

.ant-table-tbody tr td {
  border: 0;
}

.table-striped {
  background-color: #f7f9fa;
}
</style>