<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" />
      </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 getIntDictOptions(DICT_TYPE.PAY_ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          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:pay-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['member:pay-order: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="id" width="200px" />
      <el-table-column label="订单金额" align="center" prop="amount" width="100px">
        <template #default="{row}">
          <span class="text-base text-red-400 font-semibold">{{row.amount}}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="status" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PAY_ORDER_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="用户账号" align="center" prop="username" width="180px" />
      <el-table-column
        label="订单失效时间"
        align="center"
        prop="expireTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="审批时间"
        align="center"
        prop="successTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="300px">
        <template #default="scope">
          <el-button
            type="success"
            v-if="scope.row.status == 0"
            v-hasPermi="['member:pay-order:update']"
            @click="handleLock(scope.row.id, 3)"
          >锁定
          </el-button>
          <el-button
            type="warning"
            v-if="scope.row.status == 3"
            v-hasPermi="['member:pay-order:update']"
            @click="handleLock(scope.row.id, 0)">取消锁定
          </el-button>
          <el-button
            type="success"
            v-if="scope.row.status == 3"
            v-hasPermi="['member:pay-order:update']"
            @click="handleApproveRecharge(scope.row)"
          >通过
          </el-button
          >
          <el-button
            type="danger"
            v-if="scope.row.status == 3"
            v-hasPermi="['member:pay-order:update']"
            @click="handleRejectRecharge(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>

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

<script setup lang="ts" name="PayOrder">
import { DICT_TYPE, getIntDictOptions } from "@/utils/dict";
import { dateFormatter } from "@/utils/formatTime";
import download from "@/utils/download";
import * as PayOrderApi from "@/api/member/payOrder";
import PayOrderForm from "./PayOrderForm.vue";
import PayOrderApprove from "./PayOrderApprove.vue";
import { onMounted, reactive, ref } from "vue";
import { ElMessageBox } from "element-plus";
import * as WithdrawalApi from "@/api/member/withdrawal";

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

const loading = ref(true); // 列表的加载中
const total = ref(0); // 列表的总页数
const list = ref([]); // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  amount: null,
  status: null,
  userIp: null,
  username: null,
  expireTime: [],
  successTime: [],
  createTime: []
});
const queryFormRef = ref(); // 搜索的表单
const payOrderAproveRef = ref();
const exportLoading = ref(false); // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PayOrderApi.getPayOrderPage(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 openApproveForm = (type: string, id?: number) => {
  payOrderAproveRef.value.open(type, id);
};

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

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm();
    // 发起导出
    exportLoading.value = true;
    const data = await PayOrderApi.exportPayOrder(queryParams);
    download.excel(data, "支付订单.xls");
  } catch {
  } finally {
    exportLoading.value = false;
  }
};

const handleLock = async (id: number, status: number) => {
  const data = {id,status}
  await PayOrderApi.approvePayOrder(data)
  await getList()
}

const handleApproveRecharge = async (row: any) => {
  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 = {
      id: row.id,
      status: 1
    }
    try {
      const res = await PayOrderApi.approvePayOrder(data)
      if (res) {
        message.success('操作成功')
        await getList()
      }
    } catch (error) {
      message.error('更新失败')
    }
  })
}

const handleRejectRecharge = async (row: any) => {
  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 = {
      id: row.id,
      status: 2
    }
    try {
      const res = await PayOrderApi.approvePayOrder(data)
      if (res) {
        message.success('操作成功')
        await getList()
      }
    } catch (error) {
      message.error('更新失败')
    }
  })
}

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