<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { fetchQueryBusinessUsersList, fetchQueryChannelList } from '@/service/api';
import { objectClean } from '@/utils';
import {
  PAGINATION_PAGE_SIZES,
} from '@/const';
import { Icon } from '@iconify/vue';

const userLevelOptions = [
  { label: '游客', value: 0 },
  { label: '用户', value: 1 }
]

// 用户状态(01:正常，02:停用,03:注销)，02:停用)
const userStatusOptions = [
  { label: '正常', value: '01' },
  { label: '停用', value: '02' },
  { label: '注销', value: '03' }
]

// 应用类型 01:h5 02:公众号 3:微信小程序 04:支付宝-h5 05:支付宝小程序	
const appTypeOptions = [
  { label: 'h5', value: '01' },
  { label: '公众号', value: '02' },
  { label: '微信小程序', value: '03' },
  { label: '支付宝-h5', value: '04' },
  { label: '支付宝小程序', value: '05' },
]
const channelOptions = ref([])

async function getChannelList() {
  const res = await fetchQueryChannelList({
    pageNum: 1,
    pageSize: 100
  })
  console.log(res)
  if(res.data) {
    channelOptions.value = res.data?.data?.records || []
  }
}
const pagination = ref({
  pageSize: 10,
  itemCount: 0,
  pageNum: 1
});
function handlePageUpdate(page: number) {
  pagination.value.pageNum = page;
  getUserList();
}
function handlePageSizeUpdate(pageSize: number) {
  pagination.value.pageNum = 1;
  pagination.value.pageSize = pageSize;
  getUserList();
}

function createQueryParams() {
  return {
    userId: '',
    registerTime: null,
    startRegisterTime: '',
    endRegisterTime: '',
    mobile: '',
    userLevel: null,
    appType: null,
    channelCode: null
  };
}

/** 检索 */
function handleQuery() {
  getUserList();
}
/** 重置检索 */
function handleResetQuery() {
  queryParams.value = { ...createQueryParams() };
  getUserList();
}
const userData = ref([]);

const queryParams = ref(createQueryParams());

/** 获取用户列表 */
const loading = ref(false);
async function getUserList() {
  loading.value = true;
  const { pageNum, pageSize } = pagination.value;
  const { userId, userLevel, registerTime, mobile,  appType, channelCode } = queryParams.value;
  const params = {
    userId,
    userLevel,
    mobile,
    appType, channelCode,
    startRegisterTime: registerTime ? `${registerTime[0]} 00:00:00` : '',
    endRegisterTime: registerTime ? `${registerTime[1]} 23:59:59` : '',
    pageNum,
    pageSize
  };
  const { data } = await fetchQueryBusinessUsersList(objectClean(params));
  if (data?.ok) {
    userData.value = data.data.records;
    pagination.value.itemCount = data.data.total;
  }
  loading.value = false;
}

const showModal = ref(false)
const currentRow = ref<any>({})
function handleShowModal(row: any, type: string) {
  showModal.value = true
  currentRow.value = row
}

function filterUserStatus(value: string) {
  const item = userStatusOptions.find((item) => item.value === value);
  return item ? item.label : '-';
}

function filterAppType(value: string) {
  const item = appTypeOptions.find((item) => item.value === value);
  return item ? item.label : '';
}

onMounted(() => {
  getUserList();
  getChannelList()
});
</script>
<template>
  <div>
    <n-card class="h-full shadow-sm rounded-8px">
      <n-grid cols="1 s:2 m:3 l:4 xl:5 2xl:6" responsive="screen" x-gap="12" y-gap="12">
          <n-grid-item>
            <p class="mb-6px f-alir">用户id：</p>
            <n-input clearable v-model:value="queryParams.userId" placeholder="用户ID"></n-input>
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px f-alir">手机号：</p>
            <n-input clearable v-model:value="queryParams.mobile" placeholder="手机号"></n-input>
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px f-alir">用户类型：</p>
            <n-select v-model:value="queryParams.userLevel" clearable placeholder="用户类型" :options="userLevelOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">注册渠道：</p>
            <n-select 
              label-field="channelName"
              value-field="channelCode"
              v-model:value="queryParams.channelCode" clearable placeholder="渠道来源" :options="channelOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">操作平台：</p>
            <n-select v-model:value="queryParams.appType" clearable placeholder="操作平台" :options="appTypeOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px f-alir">注册时间：</p>
            <n-date-picker
              v-model:formatted-value="queryParams.registerTime"
              :actions="[]"
              close-on-select
              value-format="yyyy-MM-dd"
              placeholder="注册时间"
              type="daterange"
              start-placeholder="开始"
              end-placeholder="结束"
              clearable
            />
          </n-grid-item>
          <n-grid-item class="flex items-end">
            <n-space>
              <n-button secondary strong type="primary" @click="handleQuery"> 查 询 </n-button>
              <n-button secondary strong @click="handleResetQuery">重 置</n-button>
            </n-space>
          </n-grid-item>
        </n-grid>
    </n-card>

    <n-card class="shadow-sm rounded-8px mt-12px">
      <n-spin :show="loading">
        <vxe-table
          :column-config="{ resizable: true }"
          :seq-config="{ startIndex: (pagination.pageNum - 1) * pagination.pageSize }"
          auto-resize
          :row-config="{ isHover: true }"
          stripe
          border
          :data="userData"
        >
        <vxe-column type="seq" title="序号" width="60"></vxe-column>
        <vxe-column min-width="200" field="userId" title="用户ID"></vxe-column>
        <vxe-column min-width="120" field="mobile" title="手机号"></vxe-column>
        <vxe-column min-width="120" field="userLevel" title="用户类型">
          <template #default="{ row }">
            <n-tag round :bordered="false" v-if="row.userLevel === 0">
              游客
            </n-tag>
            <n-tag round :bordered="false" type="primary" v-if="row.userLevel === 1">
              用户
            </n-tag>
          </template>
        </vxe-column>
        <vxe-column min-width="200" field="channelName" title="注册渠道"></vxe-column>
        <vxe-column min-width="200" field="appType" title="操作平台">
          <template #default="{row}">
            <span>{{ filterAppType(row.appType || '') }}</span>
          </template>
        </vxe-column>
        <vxe-column min-width="200" field="registerTime" title="注册时间"></vxe-column>
        <vxe-column field="title" title="操作" fixed="right" min-width="80">
          <template #default="{ row }">
            <n-space>
              <n-button
                  strong
                  text
                  type="info"
                  @click="handleShowModal(row, 'view')"
                  >详情</n-button
                >
            </n-space>
          </template>
        </vxe-column>

        <template #empty>
          <icon-custom-empty-data class="text-320px text-primary" />
        </template>
      </vxe-table>
      </n-spin>
      <div v-if="pagination.itemCount !== 0" class="w-full flex justify-end mt-4">
        <n-pagination
          v-model:page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :item-count="pagination.itemCount"
          :page-sizes="PAGINATION_PAGE_SIZES"
          :on-update:page="handlePageUpdate"
          :on-update:page-size="handlePageSizeUpdate"
          show-size-picker
        >
        <template #prefix="{ itemCount, startIndex }">
          <div class="text-[#333]">共 <span class="text-primary">{{ pagination.itemCount }}</span> 条</div>
        </template>
      </n-pagination>
      </div>
    </n-card>

    <n-modal v-model:show="showModal" :mask-closable="false" :bordered="false">
      <n-card title="用户详情" class="w-600px rounded-8px shadow-sm">
        <template #header-extra>
          <Icon icon="ic:sharp-close" class="text-size-22px cursor-pointer" @click="showModal = false" />
        </template>
        <div>
          <n-descriptions label-style="min-width: 120px" size="small" :column="1" bordered label-placement="left">
            <n-descriptions-item label="用户头像">
              <n-avatar
                v-if="currentRow?.headerImg"
                round
                :src="currentRow?.headerImg"
              />
              <span v-else>-</span>
            </n-descriptions-item>
            <n-descriptions-item label="用户ID">
              {{ currentRow?.userId }}
            </n-descriptions-item>
            <n-descriptions-item label="用户名" >
              {{ currentRow?.userName || '-' }}
            </n-descriptions-item>
            <n-descriptions-item label="用户昵称">
              {{ currentRow?.nickName || '-' }}
            </n-descriptions-item>
            <n-descriptions-item label="手机号">
              {{ currentRow?.mobile || '-' }}
            </n-descriptions-item>
            <n-descriptions-item label="用户类型">
              <n-tag round :bordered="false" v-if="currentRow?.userLevel === 0">
                游客
              </n-tag>
              <n-tag round :bordered="false" type="primary" v-if="currentRow?.userLevel === 1">
                用户
              </n-tag>
            </n-descriptions-item>
            <n-descriptions-item label="注册渠道">
              {{ currentRow?.channelName }}
            </n-descriptions-item>
            <n-descriptions-item label="操作平台">
              <span>{{ filterAppType(currentRow.appType || '') }}</span>
            </n-descriptions-item>
            <n-descriptions-item label="会员状态">
              {{ currentRow?.vipDesc }}
            </n-descriptions-item>
            <n-descriptions-item label="注册时间">
              {{ currentRow?.registerTime }}
            </n-descriptions-item>
            <n-descriptions-item label="最后登录时间">
              {{ currentRow?.lastLoginTime }}
            </n-descriptions-item>
            <n-descriptions-item label="用户状态">
              {{ filterUserStatus(currentRow?.userStatus) }}
            </n-descriptions-item>
          </n-descriptions>
        </div>
      </n-card>
    </n-modal>
  </div>
</template>
