<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <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="withdrawalType">
        <el-select
          v-model="queryParams.withdrawalType"
          placeholder="请选择提现方式"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MEMBER_WITHDRAWAL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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.MEMBER_WITHDRAWAL_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请日期" prop="requestDate">
        <el-date-picker
          v-model="queryParams.requestDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          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="['member:withdrawal:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['member:withdrawal: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="userId" width="150px" hidden />
      <el-table-column label="手机号码" align="center" prop="username" width="150px" />
      <el-table-column label="虚拟会员" align="center" prop="userType" width="150px">
        <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="withdrawalType" width="150px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MEMBER_WITHDRAWAL_TYPE" :value="scope.row.withdrawalType" />
        </template>
      </el-table-column>
      <el-table-column label="提现金额" align="center" prop="amount" width="150px">
        <template #default="{ row }">
          <span class="text-red-500 font-semibold text-base">{{ row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提现地址" align="center" prop="accountNumber" width="350px" />
      <el-table-column label="提现状态" align="center" prop="status" width="150px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MEMBER_WITHDRAWAL_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="申请日期"
        align="center"
        prop="requestDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="审批日期"
        align="center"
        prop="processedDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="350px">
        <template #default="scope">
          <el-button
            type="success"
            v-if="scope.row.status == 1"
            v-hasPermi="['member:withdrawal:update']"
            @click="handleLock(scope.row.id, 3)"
            >锁定</el-button
          >
          <el-button
            type="warning"
            v-if="scope.row.status == 3"
            v-hasPermi="['member:withdrawal:update']"
            @click="handleLock(scope.row.id, 1)"
            >取消锁定</el-button
          >
          <el-button
            type="success"
            v-if="scope.row.status == 3"
            v-hasPermi="['member:withdrawal:update']"
            @click="handleApproveWithdrawal(scope.row)"
            >通过</el-button
          >
          <el-button
            type="danger"
            v-if="scope.row.status == 3"
            v-hasPermi="['member:withdrawal:update']"
            @click="handleRejectWithdrawal(scope.row)"
            >拒绝</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

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

<script setup lang="ts" name="Withdrawal">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as WithdrawalApi from '@/api/member/withdrawal'
import WithdrawalForm from './WithdrawalForm.vue'
import WithdrawalApproveForm from './WithdrawalApproveForm.vue'
import { ElDialog, ElMessageBox } from "element-plus";

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

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  username: null,
  withdrawalType: null,
  amount: null,
  currency: null,
  status: null,
  requestDate: [],
  processedDate: [],
  remark: null,
  fee: null,
  netAmount: null
})
const queryFormRef = ref() // 搜索的表单
const approveFormRef = ref()
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WithdrawalApi.getWithdrawalPage(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,status: number) => {
  approveFormRef.value.open(type, id,status)
}
// 审批通过
const handleApproveWithdrawal = async (row) => {
  ElMessageBox({
    title: '审批提现',
    message: h('p', null, [
      h('span', null, '是否通过用户'),
      h('span', { style: 'color: teal; margin-left: 3px; margin-right: 3px' }, row.username),
      h('span', null, '金额为'),
      h('span', { style: 'color: red; margin-left: 3px; margin-right: 3px;font-size: 16px;font-weight: 600' }, row.amount),
      h('span', null, '的提现申请')
    ]),
    confirmButtonText: t('common.ok'),
    showCancelButton: true,
    cancelButtonText: t('common.cancel'),
    center: true
  }).then(async () => {
    const data = { ...row }
    data.status = 0
    try {
      const res = await WithdrawalApi.approveWithdrawal(data)
      if (res) {
        message.success('操作成功')
        getList()
      }
    } catch (error) {
      message.error('更新失败')
    }
  })
}

const handleRejectWithdrawal = async (row) => {
  ElMessageBox({
    title: '拒绝提现',
    message: h('p', null, [
      h('span', null, '是否拒绝用户'),
      h('span', { style: 'color: teal; margin-left: 3px; margin-right: 3px' }, row.username),
      h('span', null, '金额为'),
      h('span', { style: 'color: red; margin-left: 3px; margin-right: 3px;font-size: 16px;font-weight: 600' }, row.amount),
      h('span', null, '的提现申请, 拒绝后，金额将原路反还到客户余额'),
    ]),
    confirmButtonText: t('common.ok'),
    showCancelButton: true,
    cancelButtonText: t('common.cancel'),
    center: true
  }).then(async () => {
    const data = { ...row }
    data.status = 2
    try {
      const res = await WithdrawalApi.approveWithdrawal(data)
      if (res) {
        message.success('操作成功')
        getList()
      }
    } catch (error) {
      message.error('更新失败')
    }
  })
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await WithdrawalApi.exportWithdrawal(queryParams)
    download.excel(data, '提现记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleLock = async (id: number, status: number) => {
  const res = await WithdrawalApi.approveWithdrawal({
    id: id,
    status: status
  })
  ElMessage.success('操作成功')
  getList()
}

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