<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="邀请码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入邀请码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="指定手机号" prop="onlyPhone">
        <el-input
          v-model="queryParams.onlyPhone"
          placeholder="请输入指定手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="绑定角色" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入绑定角色"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="使用用户" prop="useUserName">
        <el-input
          v-model="queryParams.useUserName"
          placeholder="请输入使用用户"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户租户" prop="useUserTenantName">
        <el-input
          v-model="queryParams.useUserTenantName"
          placeholder="请输入使用用户租户"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_INVITE_CODE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="通知状态" prop="notifyStatus">
        <el-select
          v-model="queryParams.notifyStatus"
          placeholder="请选择通知状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions('system_sms_send_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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="['system:invite-code:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:invite-code: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="邀请码" align="center" prop="code" fixed="left" width="160px" />
      <el-table-column label="绑定角色" align="center" prop="roleNames" fixed="left" >
        <template #default="scope">
          <div style="display: flex; flex-direction: column; gap: 5px;">
            <el-tag type="primary"
                    v-for="roleName in scope.row.roleNames"
                    :key="roleName"
            >{{ roleName }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="有效期（天）" align="center" prop="validTime" fixed="left" />
      <el-table-column label="状态" align="center" prop="status" fixed="left" width="90px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_INVITE_CODE_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="指定手机号" align="center" prop="onlyPhone" fixed="left" width="120px" />
      <el-table-column
        label="过期时间"
        align="center"
        prop="expireTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="使用用户" align="center" prop="useUserName" width="120px"/>
      <el-table-column label="用户租户" align="center" prop="useUserTenantName" width="180px" />
      <el-table-column
        label="使用时间"
        align="center"
        prop="useTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="通知状态" align="center" prop="notifyStatus" width="120px">
        <template #default="scope">
          <dict-tag :type="'system_sms_send_status'" :value="scope.row.notifyStatus" />
        </template>
      </el-table-column>
      <el-table-column label="通知时间" align="center" prop="notifyTime" :formatter="dateFormatter" width="180px" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="180px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:invite-code:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            :disabled="true"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:invite-code:delete']"
          >
            删除
          </el-button>

          <!--通知条件：指定手机号、状态为正常、通知状态为待通知-->
          <el-button
            v-if="scope.row.onlyPhone && scope.row.status === '0' &&scope.row.notifyStatus !== '10'"
            link
            type="warning"
            @click="handleSendSms(scope.row.id)"
            v-hasPermi="['system:invite-code:update']"
          >
            通知
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

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

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { InviteCodeApi, InviteCodeVO } from '@/api/system/invitecode'
import InviteCodeForm from './InviteCodeForm.vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 邀请码 列表 */
defineOptions({ name: 'InviteCode' })

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

const loading = ref(true) // 列表的加载中
const list = ref<InviteCodeVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  onlyPhone: undefined,
  roleName: undefined,
  validTime: undefined,
  expireTime: [],
  useUserName: undefined,
  useUserTenantName: undefined,
  status: undefined,
  notifyStatus: undefined,
  createTime: [],
  tenantId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InviteCodeApi.getInviteCodePage(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 handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InviteCodeApi.deleteInviteCode(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InviteCodeApi.exportInviteCode(queryParams)
    download.excel(data, '邀请码.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 发送短信通知 */
const handleSendSms = async (id: number) => {
  try {
    // 确认对话框
    await message.confirm('确定要发送短信通知吗？')
    // 发起发送短信请求
    await InviteCodeApi.sendSms(id)
    message.success('短信发送成功')
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('发送短信失败:', error)
  }
}

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