<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户信息" prop="userInformation">
        <el-input
          v-model="queryParams.userInformation"
          placeholder="请输入姓名，昵称，电话号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
<!--      <el-form-item label="分销等级" prop="distributeLevel">-->
<!--        <el-input-->
<!--          v-model="queryParams.distributeLevel"-->
<!--          placeholder="请输入分销等级"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="推广用户数量" prop="marketinguserNumber">-->
<!--        <el-input-->
<!--          v-model="queryParams.marketinguserNumber"-->
<!--          placeholder="请输入推广用户数量"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="推广订单数量" prop="marketingorderNumber">-->
<!--        <el-input-->
<!--          v-model="queryParams.marketingorderNumber"-->
<!--          placeholder="请输入推广订单数量"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="推广订单金额" prop="marketingorderMoney">-->
<!--        <el-input-->
<!--          v-model="queryParams.marketingorderMoney"-->
<!--          placeholder="请输入推广订单金额"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="佣兵总金额" prop="mercenarieMoney">-->
<!--        <el-input-->
<!--          v-model="queryParams.mercenarieMoney"-->
<!--          placeholder="请输入佣兵总金额"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="已提现金额" prop="alreadytokenMoney">-->
<!--        <el-input-->
<!--          v-model="queryParams.alreadytokenMoney"-->
<!--          placeholder="请输入已提现金额"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="未提现金额" prop="untokenMoney">-->
<!--        <el-input-->
<!--          v-model="queryParams.untokenMoney"-->
<!--          placeholder="请输入未提现金额"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="上级推广人" prop="superiorPromoter">-->
<!--        <el-input-->
<!--          v-model="queryParams.superiorPromoter"-->
<!--          placeholder="请输入上级推广人"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="提现次数" prop="takeTimes">-->
<!--        <el-input-->
<!--          v-model="queryParams.takeTimes"-->
<!--          placeholder="请输入提现次数"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['trade:distribute-manage:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['trade:distribute-manage:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="id" align="center" prop="id" />
<!--      <el-table-column label="商品图片" align="center" prop="goodImage" />-->
      <el-table-column label="商品图片" align="center">
        <template #default="scope">
          <el-image
            :src="scope.row.goodImage"
            alt="商品图片"
            style="width: 100px; height: auto; cursor: pointer;"
            :preview-src-list="[scope.row.goodImage]"
            :initial-index="0"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            fit="cover"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="用户信息" align="center" prop="userInformation" />
      <el-table-column label="分销等级" align="center" prop="distributeLevel" />
      <el-table-column label="推广用户数量" align="center" prop="marketinguserNumber" />
      <el-table-column label="推广订单数量" align="center" prop="marketingorderNumber" />
      <el-table-column label="推广订单金额" align="center" prop="marketingorderMoney" />
      <el-table-column label="佣兵总金额" align="center" prop="mercenarieMoney" />
      <el-table-column label="已提现金额" align="center" prop="alreadytokenMoney" />
      <el-table-column label="未提现金额" align="center" prop="untokenMoney" />
      <el-table-column label="上级推广人" align="center" prop="superiorPromoter" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="提现次数" align="center" prop="takeTimes" />
      <!-- 操作列 -->
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openPromoterDialog(scope.row.id)"
            v-hasPermi="['trade:distribute-manage:update']"
          >
            推广员
          </el-button>
          <el-dropdown
            trigger="click"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['trade:distribute-manage:delete', 'trade:distribute-manage:update']"
          >
            <el-button link type="danger">
              更多<icon icon="ep:arrow-down" class="el-icon--right" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  command="promoteQR"
                  v-hasPermi="['trade:distribute-manage:qr']"
                >
                  推广二维码
                </el-dropdown-item>
                <el-dropdown-item
                  command="update"
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['trade:distribute-manage:update']"
                >
                  编辑分销员内容
                </el-dropdown-item>
                <el-dropdown-item
                  command="cancelPromote"
                  v-hasPermi="['trade:distribute-manage:delete']"
                >
                  取消推广资格
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>


    <!-- 推广员弹窗组件 -->
    <el-dialog
      v-model="promoterDialogVisible"
      title="推广员详情"
      width="80%"
      :close-on-click-modal="false"
    >
      <PromoterIndex v-if="promoterDialogVisible" :promoter-id="currentPromoterId" />
    </el-dialog>
    <!-- 推广二维码弹窗组件 -->
    <el-dialog
      v-model="qrDialogVisible"
      title="公众号二维码"
      width="400px"
      :close-on-click-modal="false"
    >
      <div style="text-align: center;">
        <el-image :src="qrCodeUrl" alt="公众号二维码" style="width: 200px; height: 200px;" />
        <p style="margin-top: 10px;">扫码关注公众号</p>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DistributeManageForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DistributeManageApi, DistributeManageVO } from '@/api/mall/trade/distributemanage'
import DistributeManageForm from './DistributeManageForm.vue'
import { ref } from 'vue'
import PromoterIndex from '@/views/mall/trade/brokerage/user/index.vue'
import {ElMessage} from "element-plus";

/** 分销员管理 列表 */
defineOptions({ name: 'DistributeManage' })

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

const loading = ref(true) // 列表的加载中
const list = ref<DistributeManageVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  goodImage: undefined,
  userInformation: undefined,
  distributeLevel: undefined,
  marketinguserNumber: undefined,
  marketingorderNumber: undefined,
  marketingorderMoney: undefined,
  mercenarieMoney: undefined,
  alreadytokenMoney: undefined,
  untokenMoney: undefined,
  superiorPromoter: undefined,
  takeTimes: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

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

/** 搜索按钮操作 */
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 handleCommand = async (command: string, row: DistributeManageVO) => {
  switch (command) {
    case 'promoteQR':
      handlePromoteQRCode(row.id)
      break
    case 'updateLevel':
      handleUpdateLevel(row.id)
      break
    case 'cancelPromote':
      handleDelete(row.id)
      break
  }
}
/** 二维码弹窗相关状态 */
const qrDialogVisible = ref(false)
const qrCodeUrl = ref('') // 二维码地址

/** 处理推广二维码 */
const handlePromoteQRCode = (id: number) => {
  // 模拟未找到二维码的情况
  const qrCodeFound = false // 如果找不到对应的二维码

  if (!qrCodeFound) {
    ElMessage.error('暂未找到对应的推广二维码') // 显示错误信息
    qrCodeUrl.value = '/.image/测试二维码.jpg' // 本地二维码路径
    qrDialogVisible.value = true // 打开弹窗
  } else {
    // 如果找到二维码，可以调用 API 获取二维码地址
    // const response = await DistributeManageApi.getPromoteQRCode(id)
    // qrCodeUrl.value = response.data.qrCodeUrl
    // qrDialogVisible.value = true
  }
}
/** 处理修改分销等级 */
const handleUpdateLevel = (id: number) => {
}

/** 推广员弹窗相关状态 */
const promoterDialogVisible = ref(false)
const currentPromoterId = ref<number | null>(null)

/** 打开推广员弹窗 */
const openPromoterDialog = (id: number) => {
  currentPromoterId.value = id
  promoterDialogVisible.value = true
}

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

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DistributeManageApi.exportDistributeManage(queryParams)
    download.excel(data, '分销员管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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