<template>
  <el-row>
    <el-col :span="23" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-col>
            <el-form-item label="ID" prop="id" :span="20">
              <el-input
                v-model="queryParams.id"
                placeholder="会员ID"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>
            <el-form-item label="账号" prop="username">
              <el-input
                v-model="queryParams.username"
                placeholder="会员编号"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>
            <el-form-item label="上级编号" prop="parentId">
              <el-input
                v-model="queryParams.parentId"
                placeholder="上级的ID字段"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>
            <el-form-item label="推广码" prop="invitationCode">
              <el-input
                v-model="queryParams.invitationCode"
                placeholder="推广码"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item>
              <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
              <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
              <el-button
                type="primary"
                plain
                @click="openForm('create')"
                v-hasPermi="['member:user:create']"
              >
                <Icon icon="ep:plus" /> 新增
              </el-button>
              <el-button
                type="warning"
                plain
                @click="handleImport"
                v-hasPermi="['member:user:import']"
              >
                <Icon icon="ep:upload" /> 导入
              </el-button>
              <el-button
                type="success"
                plain
                @click="handleExport"
                :loading="exportLoading"
                v-hasPermi="['member:user:export']"
              >
                <Icon icon="ep:download" />导出
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="list" @sort-change="sortChange" size="small">
          <el-table-column fixed label="账号" align="left" key="id" width="150">
            <template #default="scope">
              <div>
                <el-col> ID： {{ scope.row.id }} </el-col>
                <el-col>
                  编号： {{ scope.row.username }}
                  <el-icon color="#409EFC" @click="copy(scope.row.username)"
                    ><CopyDocument
                  /></el-icon>
                </el-col>
                <el-col> 国家： {{ scope.row.countryCode }}</el-col>
                <el-col>
                  推广码： {{ scope.row.invitationCode }}
                  <el-icon color="#409EFC" @click="copy(scope.row.invitationCode)"
                    ><CopyDocument /></el-icon
                ></el-col>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            fixed
            label="推荐人"
            align="left"
            prop="parentUser"
            :show-overflow-tooltip="true"
            key="parentUser"
            width="150"
          >
            <template #default="scope">
              <el-col> ID： {{ scope.row.parentUser.id }}</el-col>
              <el-col> 编号： {{ scope.row.parentUser.username }}</el-col>
              <el-col> 推广码： {{ scope.row.parentUser.invitationCode }}</el-col>
            </template>
          </el-table-column>
          <el-table-column label="是否虚拟会员" align="center" prop="userType" width="60">
            <template #default="scope">
              <div>
                <el-tag class="ml-2" type="danger" color="#f14b4b" v-if="scope.row.userType == 1"
                  ><span class="text-white">是</span></el-tag
                >
                <el-tag class="ml-2" v-if="scope.row.userType == 0" color="#409eff"
                  ><span class="text-white">否</span></el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="当前级别"
            align="center"
            prop="memberLevel"
            sortable="custom"
            width="100"
          >
            <template #default="scope">
              <div>
                <el-tag class="ml-2" color="#409eff"
                  ><span class="text-white">VIP{{ scope.row.memberLevel }}</span></el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="账户金额" align="left" prop="balanceAccountDetails" width="120">
            <template #default="scope">
              <el-col> 剩余：{{ scope.row.balanceAccountDetails.balance }}</el-col>
              <el-col> 冻结金额： {{ scope.row.balanceAccountDetails.freezeBalance }}</el-col>
              <el-col> 累计充值： {{ scope.row.balanceAccountDetails.rechargeAmount }}</el-col>
              <el-col> 累计提现： {{ scope.row.balanceAccountDetails.withdrawAmount }}</el-col>
              <el-col> 任务奖金： {{ scope.row.balanceAccountDetails.taskCommission }}</el-col>
              <el-col> 团队奖金： {{ scope.row.balanceAccountDetails.teamCommission }}</el-col>
            </template>
          </el-table-column>
          <el-table-column label="今日订单数" align="left" prop="taskDetails" width="90">
            <template #default="scope">
              <el-col>
                {{ scope.row.taskDetails.completedTask }} /
                {{ scope.row.taskDetails.totalTask }}</el-col
              >
              <el-col> {{ scope.row.taskDetails.status === 1 ? '已完成' : '未完成' }}</el-col>
              <el-col>
                {{
                  formatDate(new Date(scope.row.taskDetails.localDateTime), 'YYYY-MM-DD')
                }}</el-col
              >
            </template>
          </el-table-column>
          <el-table-column label="信誉分" align="center" prop="creditScore" width="60" />
          <el-table-column label="最后登录" align="left" prop="loginDetails" width="145">
            <template #default="scope">
              <el-col> 最后访问IP： {{ scope.row.loginIp }}</el-col>
              <el-col> 最后访问：{{ formatDate(scope.row.loginDate) }}</el-col>
              <el-col> 登录次数：{{ scope.row.loginDetails.count }}</el-col>
              <el-col>
                注册时间：{{
                  formatDate(new Date(scope.row.createTime), 'YYYY-MM-DD HH:mm:ss')
                }}</el-col
              >
            </template>
          </el-table-column>
          <el-table-column label="记录操作" width="120" align="center">
            <template #default="scope">
              <el-col>
                <el-button
                  type="primary"
                  size="small"
                  plain
                  color="#626aef"
                  @click="openDialog('taskRecordTableRef', scope.row.id)"
                  >任务记录</el-button
                >
              </el-col>
              <el-col>
                <div style="height: 20px"></div>
              </el-col>
              <el-col>
                <el-button
                  type="primary"
                  size="small"
                  plain
                  color="#626aef"
                  @click="openDialog('balanceRecordTableRef', scope.row.id)"
                  >账户明细</el-button
                >
              </el-col>
            </template>
          </el-table-column>
          <el-table-column label="订单操作" width="120" align="center">
            <template #default="scope">
              <el-col>
                <el-button
                  type="danger"
                  size="small"
                  plain
                  @click="openDialog('combinationConfigTableRef', scope.row.id)"
                  >连单设置</el-button
                >
              </el-col>
              <el-col>
                <div style="height: 20px"></div>
              </el-col>
              <el-col>
                <el-button
                  type="warning"
                  size="small"
                  plain
                  @click="openDialog('customTaskTableRef', scope.row.id)"
                  >修改单数</el-button
                >
              </el-col>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="账号操作" width="360" align="center">
            <template #default="scope">
              <el-row>
                <el-col :span="8">
                  <el-button
                    type="primary"
                    size="small"
                    plain
                    @click="openDialog('userPasswordTableRef', scope.row.id)"
                    >账号密码</el-button
                  >
                </el-col>
                <el-col :span="8">
                  <el-button
                    type="success"
                    size="small"
                    plain
                    @click="openDialog('userLevelTableRef', scope.row.id)"
                    >修改等级</el-button
                  >
                </el-col>
                <el-col :span="8">
                  <el-button
                    type="info"
                    size="small"
                    plain
                    @click="openDialog('userCreditScoreTableRef', scope.row.id)"
                    >修改信誉分</el-button
                  >
                </el-col>
              </el-row>
              <el-col>
                <div style="height: 20px"></div>
              </el-col>
              <el-row>
                <el-col :span="8">
                  <el-button
                    type="danger"
                    size="small"
                    plain
                    @click="openDialog('balanceAccountTableRef', scope.row.id)"
                    >加扣款</el-button
                  >
                </el-col>
                <el-col :span="8">
                  <el-button
                    type="primary"
                    plain
                    @click="openForm('record', scope.row.id)"
                    size="small"
                    >编辑</el-button
                  >
                </el-col>
                <el-col :span="8">
                  <el-button
                    type="primary"
                    plain
                    @click="openDialog('userWithdrawalPasswordTable', scope.row.id)"
                    size="small"
                    >取款密码</el-button
                  >
                </el-col>
                <el-col :span="8">
                  <el-button
                    type="danger"
                    size="small"
                    plain
                    @click="openForm('record', scope.row.id)"
                    :icon="Delete"
                    v-hasPermi="['member:member-user:delete']"
                    >删除</el-button
                  >
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 添加或修改用户对话框 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 任务列表 -->
  <TaskRecordTable ref="taskRecordTableRef" />
  <!-- 余额列表 -->
  <BalanceRecordTable ref="balanceRecordTableRef" />
  <!-- 连单设置 -->
  <CombinationConfigTable ref="combinationConfigTableRef" />
  <!-- 任务单数 -->
  <CustomTaskTable ref="customTaskTableRef" @success="getList" />
  <!-- 修改密码 -->
  <UserPasswordTable ref="userPasswordTableRef" />
  <!-- 修改等级 -->
  <UserLevelTable ref="userLevelTableRef" @success="getList" />
  <!-- 修改信誉分 -->
  <UserCreditScoreTable ref="userCreditScoreTableRef" @success="getList" />
  <!-- 加扣款 -->
  <BalanceAccountTable ref="balanceAccountTableRef" @success="getList" />
  <!-- 取款密码 -->
  <UserWithdrawalPasswordTable ref="userWithdrawalPasswordTable" />
</template>
<script lang="ts" setup>
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { CommonStatusEnum } from '@/utils/constants'
import * as UserApi from '@/api/member/user'
import UserForm from './UserForm.vue'
import TaskRecordTable from './TaskRecordTable.vue'
import BalanceRecordTable from './BalanceRecordTable.vue'
import CombinationConfigTable from './CombinationConfigTable.vue'
import CustomTaskTable from './CustomTaskTable.vue'
import UserPasswordTable from './UserPasswordTable.vue'
import UserLevelTable from './UserLevelTable.vue'
import UserCreditScoreTable from './UserCreditScoreTable.vue'
import BalanceAccountTable from './BalanceAccountTable.vue'
import UserWithdrawalPasswordTable from './UserWithdrawalPasswordTable.vue'
import { Delete, CopyDocument } from '@element-plus/icons-vue'
import { useClipboard } from '@vueuse/core'
defineOptions({ name: 'MemberUser' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const queryParams = reactive({
  id: undefined,
  pageNo: 1,
  pageSize: 10,
  username: undefined,
  mobile: undefined,
  parentId: undefined,
  countryCode: undefined,
  invitationCode: undefined,
  order: '',
  orderFiled: '',
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const taskRecordTableRef = ref() // 任务列表
const balanceRecordTableRef = ref() // 余额列表
const combinationConfigTableRef = ref() // 连单设置
const customTaskTableRef = ref() // 任务单数
const userPasswordTableRef = ref() // 密码设置
const userLevelTableRef = ref() // 用户等级
const userCreditScoreTableRef = ref() // 信誉分
const balanceAccountTableRef = ref() // 加扣款
const userWithdrawalPasswordTable = ref() // 取款

const tableRefObj = {
  taskRecordTableRef,
  balanceRecordTableRef,
  combinationConfigTableRef,
  customTaskTableRef,
  userPasswordTableRef,
  userLevelTableRef,
  userCreditScoreTableRef,
  balanceAccountTableRef,
  userWithdrawalPasswordTable
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const sortChange = async (column: any) => {
  if (!column.order) {
    queryParams.orderFiled = ''
    queryParams.order = ''
    return
  }
  queryParams.orderFiled = column.prop
  queryParams.order = column.order
  await getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 修改用户状态 */
const handleStatusChange = async (row: UserApi.UserVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.username + '"用户吗?')
    // 发起修改状态
    await UserApi.updateUserStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserApi.exportUser(queryParams)
    download.excel(data, '用户数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleRole':
      handleRole(row)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 重置密码 */
const handleResetPwd = async (row: UserApi.UserVO) => {
  try {
    // 重置的二次确认
    const result = await message.prompt(
      '请输入"' + row.username + '"的新密码',
      t('common.reminder')
    )
    const password = result.value
    // 发起重置
    await UserApi.resetUserPwd(row.id, password)
    message.success('修改成功，新密码是：' + password)
  } catch {}
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row: UserApi.UserVO) => {
  assignRoleFormRef.value.open(row)
}

const openDialog = (name: string, id?: number) => {
  tableRefObj[name].value.open('table', id)
}

const copy = async (text: string) => {
  const { copy, copied, isSupported } = useClipboard({ source: text })
  if (!isSupported) {
    message.error(t('common.copyError'))
    return
  }
  await copy()
  if (unref(copied)) {
    message.success(t('common.copySuccess'))
  }
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.table-row-box {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  flex-direction: column;
}
</style>
