<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="" prop="userIds">
              <el-input v-model="queryParams.userIds" placeholder="请输入用户名/手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单号" prop="outTradeNo">
              <el-input v-model="queryParams.outTradeNo" placeholder="请输入商户订单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="商品标题" prop="subject">
              <el-input v-model="queryParams.subject" placeholder="请输入商品标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="支付宝交易号" prop="tradeNo">
              <el-input v-model="queryParams.tradeNo" placeholder="请输入支付宝交易号" clearable @keyup.enter="handleQuery" />
            </el-form-item>-->
            <el-form-item label="支付时间">
              <el-date-picker
                v-model="data.queryParams.loginTimeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:order:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:order:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:order:remove']"
              >删除</el-button
            >
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:order:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="orderList" @selection-change="handleSelectionChange">
        <!-- 序号列 -->
        <el-table-column label="序号" width="60" align="center">
          <template #default="{ $index }">
            {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <!--        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />-->
        <el-table-column label="订单号" align="center" prop="outTradeNo" />
        <el-table-column label="商品" align="center" prop="subject" />
        <el-table-column label="描述" align="center" prop="body" />
        <el-table-column label="订单金额" align="center" prop="totalAmount" />
        <el-table-column label="用户名" align="center" prop="nickName" />
        <el-table-column label="手机号" align="center" prop="phone" />
        <el-table-column label="订单状态" align="center" width="120">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'success' ? 'success' : row.status === 'pending' ? 'warning' : row.status === 'close' ? 'danger' : 'info'"
              size="small"
            >
              {{ row.status === 'success' ? '成功' : row.status === 'pending' ? '已关闭' : row.status === 'close' ? '已关闭' : '未知状态' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付时间" align="center" prop="payTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.payTime ? parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:order:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:order:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改支付订单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商户订单号" prop="outTradeNo">
          <el-input v-model="form.outTradeNo" placeholder="请输入商户订单号" />
        </el-form-item>
        <el-form-item label="商品标题" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入商品标题" />
        </el-form-item>
        <el-form-item label="商品描述" prop="body">
          <el-input v-model="form.body" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="订单金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item label="币种" prop="currency">
          <el-input v-model="form.currency" placeholder="请输入币种" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="业务ID" prop="bizId">
          <el-input v-model="form.bizId" placeholder="请输入业务ID" />
        </el-form-item>
        <el-form-item label="支付宝交易号" prop="tradeNo">
          <el-input v-model="form.tradeNo" placeholder="请输入支付宝交易号" />
        </el-form-item>
        <el-form-item label="支付宝APPID" prop="appId">
          <el-input v-model="form.appId" placeholder="请输入支付宝APPID" />
        </el-form-item>
        <el-form-item label="卖家支付宝用户ID" prop="sellerId">
          <el-input v-model="form.sellerId" placeholder="请输入卖家支付宝用户ID" />
        </el-form-item>
        <el-form-item label="支付成功时间" prop="payTime">
          <el-date-picker clearable v-model="form.payTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择支付成功时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="支付宝通知时间" prop="notifyTime">
          <el-date-picker clearable v-model="form.notifyTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择支付宝通知时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="道具ID" prop="relatedItemId">
          <el-input v-model="form.relatedItemId" placeholder="请输入道具ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order" lang="ts">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from '@/api/system/business/order';
import { OrderVO, OrderQuery, OrderForm } from '@/api/system/business/order/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const orderList = ref<OrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderForm = {
  id: undefined,
  outTradeNo: undefined,
  subject: undefined,
  body: undefined,
  totalAmount: undefined,
  currency: undefined,
  userId: undefined,
  bizType: undefined,
  bizId: undefined,
  tradeNo: undefined,
  appId: undefined,
  sellerId: undefined,
  status: undefined,
  payTime: undefined,
  notifyTime: undefined,
  notifyType: undefined,
  tradeStatus: undefined,
  productId: undefined,
  relatedItemId: undefined
};
const data = reactive<PageData<OrderForm, OrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    outTradeNo: undefined,
    subject: undefined,
    body: undefined,
    totalAmount: undefined,
    currency: undefined,
    userId: undefined,
    bizType: undefined,
    bizId: undefined,
    tradeNo: undefined,
    appId: undefined,
    sellerId: undefined,
    status: undefined,
    payTime: undefined,
    notifyTime: undefined,
    notifyType: undefined,
    tradeStatus: undefined,
    productId: undefined,
    relatedItemId: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    outTradeNo: [{ required: true, message: '商户订单号不能为空', trigger: 'blur' }],
    subject: [{ required: true, message: '商品标题不能为空', trigger: 'blur' }],
    totalAmount: [{ required: true, message: '订单金额不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
    bizType: [{ required: true, message: '业务类型不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询支付订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrder(queryParams.value);
  orderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  orderFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  const timeRange = data.queryParams.loginTimeRange;
  if (timeRange && timeRange.length === 2) {
    data.queryParams.beginTime = timeRange[0];
    data.queryParams.endTime = timeRange[1];
  } else {
    data.queryParams.beginTime = null;
    data.queryParams.endTime = null;
  }
  getList();
};

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加支付订单';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改支付订单';
};

/** 提交按钮 */
const submitForm = () => {
  orderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateOrder(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addOrder(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: OrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除支付订单编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delOrder(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

import { parseTime } from '@/utils/dateUtils';
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/order/export',
    {
      ...queryParams.value
    },
    `充值订单${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
