<template>
  <!-- 操作工具栏 -->
  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-button type="primary" plain @click="handleAdd"><Icon icon="ep:plus" />发起订单</el-button>
    </el-col>
  </el-row>

  <!-- 列表 -->
  <el-table v-loading="loading" :data="list">
    <el-table-column label="订单编号" align="center" prop="id" />
    <el-table-column label="用户编号" align="center" prop="userId" />
    <el-table-column label="商品名字" align="center" prop="spuName" />
    <el-table-column label="支付价格" align="center" prop="price">
      <template #default="scope">
        <span>￥{{ (scope.row.price / 100.0).toFixed(2) }}</span>
      </template>
    </el-table-column>
    <el-table-column label="退款金额" align="center" prop="refundPrice">
      <template #default="scope">
        <span>￥{{ (scope.row.refundPrice / 100.0).toFixed(2) }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="创建时间"
      align="center"
      prop="createTime"
      width="180"
      :formatter="dateFormatter"
    />
    <el-table-column label="支付单号" align="center" prop="payOrderId" />
    <el-table-column label="是否支付" align="center" prop="payStatus">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.payStatus" />
      </template>
    </el-table-column>
    <el-table-column
      label="支付时间"
      align="center"
      prop="payTime"
      width="180"
      :formatter="dateFormatter"
    />
    <el-table-column label="退款时间" align="center" prop="refundTime" width="180">
      <template #default="scope">
        <span v-if="scope.row.refundTime">{{ formatDate(scope.row.refundTime) }}</span>
        <span v-else-if="scope.row.payRefundId">退款中，等待退款结果</span>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
      <template #default="scope">
        <el-button
          size="small"
          type="text"
          icon="el-icon-edit"
          @click="handlePay(scope.row)"
          v-if="!scope.row.payStatus"
          >前往支付</el-button
        >
        <el-button
          size="small"
          type="text"
          icon="el-icon-delete"
          @click="handleRefund(scope.row)"
          v-if="scope.row.payStatus && !scope.row.payRefundId"
          >发起退款</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页组件 -->
  <pagination
    v-show="total > 0"
    :total="total"
    v-model:page="queryParams.pageNo"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />

  <!-- 对话框(添加 / 修改) -->
  <el-dialog :title="title" v-model="open" width="500px" append-to-body destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="商品" prop="spuId">
        <el-select
          v-model="form.spuId"
          placeholder="请输入下单商品"
          clearable
          size="small"
          style="width: 380px"
        >
          <el-option v-for="item in spus" :key="item.id" :label="item.name" :value="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px"
              >￥{{ (item.price / 100.0).toFixed(2) }}</span
            >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="PayDemoOrder">
import { createDemoOrder, getDemoOrderPage, refundDemoOrder } from '@/api/pay/demo'
import { ref, onMounted } from 'vue'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'

const router = useRouter() // 路由对象
const message = useMessage() // 消息弹窗

// 遮罩层
const loading = ref(true)
// 总条数
const total = ref(0)
// 示例订单列表
const list = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParams = ref({
  pageNo: 1,
  pageSize: 10
})

// 表单参数
const form = ref({})
// 表单校验
const rules = {
  spuId: [{ required: true, message: '商品编号不能为空', trigger: 'blur' }]
}

// 商品数组
const spus = ref([
  {
    id: 1,
    name: '华为手机',
    price: 1
  },
  {
    id: 2,
    name: '小米电视',
    price: 10
  },
  {
    id: 3,
    name: '苹果手表',
    price: 100
  },
  {
    id: 4,
    name: '华硕笔记本',
    price: 1000
  },
  {
    id: 5,
    name: '蔚来汽车',
    price: 200000
  }
])

const formRef = ref()

/** 查询列表 */
const getList = () => {
  loading.value = true
  // 执行查询
  getDemoOrderPage(queryParams.value).then((data) => {
    list.value = data.list
    total.value = data.total
    loading.value = false
  })
}

/** 取消按钮 */
const cancel = () => {
  open.value = false
  reset()
}

/** 表单重置 */
const reset = () => {
  form.value = {
    spuId: undefined
  }
  formRef.value?.resetFields()
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '发起订单'
}

/** 提交按钮 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) {
    return
  }
  // 添加的提交
  createDemoOrder(form.value).then(() => {
    message.success('新增成功')
    open.value = false
    getList()
  })
}

/** 支付按钮操作 */
const handlePay = (row) => {
  router.push({
    name: 'PayCashier',
    query: {
      id: row.payOrderId,
      returnUrl: encodeURIComponent('/pay/demo-order?id=' + row.id)
    }
  })
}

/** 退款按钮操作 */
const handleRefund = async (row: any) => {
  const id = row.id

  try {
    await message.confirm('是否确认退款编号为"' + id + '"的示例订单?')
    await refundDemoOrder(id)
    getList()
    message.success('发起退款成功！')
  } catch {}
}

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