<template>
  <div class="mediaList">
    <Search :onClickAddUser="onClickAddUser" :onClickSearch="onClickSearch" :onClickReset="onClickReset" />
    <div class="mediaList-table">
      <a-table :scroll="{ x: '100%', y: 500 }" rowKey="user_id" :loading="state.listLoading" :columns="columns"
        :rowClassName="rowClassName" :dataSource="state.list" :pagination="paginationConfig">
        <!-- 操作 -->
        <template #action="{ record }">
          <div style="color: #2d8cf0">
            <a-tooltip title="显示密码" v-if="!record.password">
              <EyeOutlined @click="onClickLookPassword(record.user_id)" />
            </a-tooltip>
            <a-tooltip title="隐藏密码" v-else>
              <EyeInvisibleOutlined @click="onClickClosePassword(record.user_id)" />
            </a-tooltip>
          </div>
        </template>
      </a-table>
    </div>
  </div>
  <AddModal :visible="state.visible" :onClickConfirm="addModalOnClickConfirm" :onClickCancel="addModalOnClickCancel"
    v-if="state.visible" />
</template>

<script lang="ts" setup>
import { onMounted, reactive } from 'vue';
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons-vue';
import Search from './components/Search.vue';
import AddModal from './components/AddModal.vue';
import { getAllUsersInfo } from '/@/api/manage';
import { apis } from '/@/api/custom/index';
import { getWorkspaceId } from '/@/utils/index'

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

interface State {
  query: any,
  listLoading: boolean,
  list: Member[],
  visible: boolean,
}

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

const paginationConfig = reactive({
  pageSizeOptions: ['20', '50', '100'],
  showQuickJumper: true,
  showSizeChanger: true,
  pageSize: 20,
  current: 1,
  total: 0,
  onChange: async (current: number) => {
    paginationConfig.current = current;
    await fetchList();
  },
  onShowSizeChange: async (current: number, pageSize: number) => {
    paginationConfig.pageSize = pageSize;
    await fetchList();
  }
})

const fetchList = async () => {
  state.listLoading = true;
  try {
    const res = await getAllUsersInfo(getWorkspaceId(), {
      ...state.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,
    customRender: ({ text }: any) => {
      if (text === 'Web') {
        return '管理员'
      } else {
        return '飞行员'
      }
    }
  },
  {
    title: '项目名称',
    dataIndex: 'workspace_name',
    width: 150,
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    width: 150,
    sorter: (a: Member, b: Member) => a.create_time.localeCompare(b.create_time),
  },
  {
    title: '密码',
    dataIndex: 'password',
    width: 100,
    customRender: ({ text }: any) => {
      return text || '****';
    }
  },
  {
    title: '操作',
    dataIndex: 'actions',
    fixed: 'right',
    align: 'center',
    width: 60,
    slots: { customRender: 'action' },
  },
]

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

// 点击添加飞行员
const onClickAddUser = () => {
  state.visible = true;
}

// 添加飞行员弹出层-点击确定
const addModalOnClickConfirm = async (data: any) => {
  state.visible = false;
  await apis.AddPilot(data);
  await fetchList()
}

// 添加飞行员弹出层-点击取消
const addModalOnClickCancel = () => {
  state.visible = false;
}

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

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

// 点击查看密码
const onClickLookPassword = async (id: string) => {
  try {
    const res = await apis.fetchPilotPassword({ userId: id });
    const list = state.list.map(item => {
      return {
        ...item,
        password: item.user_id === id ? res.data : '',// 显示当前密码，关闭其他密码
      }
    })
    state.list = list;
  } catch (e) {
    console.error(e);
  }
}

// 点击关闭密码
const onClickClosePassword = (id: string) => {
  const item = state.list.find((item) => item.user_id === id);
  if (!item) {
    return;
  }
  item.password = '';
}
</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>