<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="140px"
    >
      <el-form-item label="用户编号" prop="userId" v-hasPermi="['menduner:system:trade-order:query']">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="type">
        <el-select v-model="queryParams.type" clearable placeholder="请选择订单类型" class="!w-240px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MENDUNER_TRADE_ORDER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品编号" prop="spuId" v-hasPermi="['menduner:system:trade-order:query']">
        <el-input
          v-model="queryParams.spuId"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="商品名字" prop="spuName" v-hasPermi="['menduner:system:trade-order:query']">
        <el-input
          v-model="queryParams.spuName"
          placeholder="请输入商品名字"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否已支付" prop="payStatus">
        <el-select
          v-model="queryParams.payStatus"
          placeholder="请选择是否已支付"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="(val, i) in payStatus"
            :key="i"
            :label="val.label"
            :value="val.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付订单编号" prop="payOrderId" v-hasPermi="['menduner:system:trade-order:query']">
        <el-input
          v-model="queryParams.payOrderId"
          placeholder="请输入支付订单编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="订单支付时间" prop="payTime">
        <el-date-picker
          v-model="queryParams.payTime"
          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 v-hasPermi="['menduner:system:trade-order:query']" @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button v-hasPermi="['menduner:system:trade-order:query']" @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!-- <el-button v-hasPermi="['menduner:system:trade-order:create']" type="primary" plain @click="openForm('create')"><Icon icon="ep:plus" />发起订单</el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true">
      <el-table-column label="购买方" align="center" prop="userType" fixed="left">
        <template #default="scope">
          <span style="color: #409EFF; cursor: pointer;" @click="handleToDetail(scope.row)">
            {{ scope.row?.userType === '0' ? scope.row?.person?.name : scope.row?.enterprise ? formatName(scope.row?.enterprise.name) : scope.row?.person?.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="商品名字" align="center" prop="spuName" fixed="left" width="180">
        <template #default="scope">{{ formatName(scope.row.spuName) }}</template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" fixed="left">
        <template #default="scope">
          {{ (scope.row.price / 100.0).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="是否已支付" align="center" prop="payStatus">
        <template #default="scope">
          <span :style="{'color': scope.row.payStatus ? '#67C23A' : '#F56C6C'}">{{ scope.row.payStatus ? '已支付' : '未支付' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付订单编号" align="center" prop="payOrderId" width="180" />
      <el-table-column label="支付渠道" align="center" prop="payChannelCode" width="130">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PAY_CHANNEL_CODE" :value="scope.row.payChannelCode" />
        </template>
      </el-table-column>
      <el-table-column label="订单支付时间" align="center" prop="payTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="是否退款" align="center" prop="payRefundId">
        <template #default="scope">{{ scope.row.payRefundId ? '已退款' : '' }}</template>
      </el-table-column>
      <el-table-column label="订单是否取消" align="center" prop="cancelType">
        <template #default="scope">
          {{ scope.row.cancelType ? '订单取消': '' }}
          <!-- <dict-tag :type="DICT_TYPE.MENDUNER_TRADE_ORDER_CANCEL_TYPE" :value="scope.row.cancelType" /> -->
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" align="center" fixed="right" min-width="140">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
          <el-button
            v-if="!scope.row.payStatus && ['1', '2'].includes(scope.row.type)"
            link
            type="success"
            @click="handleUpdateOrder(scope.row)"
            v-hasPermi="['menduner:system:job-advertised:manual:submit']"
          >
            职位发布
          </el-button>
          <el-button
            link
            type="primary"
            @click="handlePay(scope.row)"
            v-if="!scope.row.payStatus && scope.row.cancelType !== '10'"
            v-hasPermi="['menduner:system:trade-order:update']"
          >
            前往支付
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleRefund(scope.row)"
            v-hasPermi="['menduner:system:trade-order:update']"
            v-if="scope.row.payStatus && !scope.row.payRefundId"
          >
            发起退款
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

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

  <!-- 详情 -->
  <TradeDetail ref="detailRef" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { TradeOrderApi, TradeOrderVO } from '@/api/menduner/system/order'
import TradeOrderForm from './TradeOrderForm.vue'
import TradeDetail from './TradeDetail.vue'
import { formatName } from '@/utils'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'

/** 交易订单	 列表 */
defineOptions({ name: 'TradeOrder' })

const message = useMessage() // 消息弹窗
const router = useRouter()
const loading = ref(true) // 列表的加载中
const list = ref<TradeOrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  type: undefined,
  terminal: undefined,
  userIp: undefined,
  status: undefined,
  spuId: undefined,
  spuName: undefined,
  price: undefined,
  payStatus: undefined,
  payOrderId: undefined,
  payChannelCode: undefined,
  payTime: [],
  refundStatus: undefined,
  payRefundId: undefined,
  refundPrice: undefined,
  refundTime: [],
  createTime: []
})
const payStatus = ref([
  { label: '已支付', value: true },
  { label: '未支付', value: false }
])
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TradeOrderApi.getTradeOrderPage(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 detailRef = ref()
const handleDetail = (row: object) => {
  console.log(row, 'detail');
  detailRef.value.open(row)
}

// 跳转购买方详情
const { push } = useRouter()
const handleToDetail = (row: object) => {
	if (row?.userType === '1' && row.enterprise) push({ name: 'EnterpriseDetail', params: { id: row?.enterpriseId } })
	else push({ name: 'PersonDetail', query: { id: row?.person?.id, userId: row?.userId } })
}

// 职位发布
const handleUpdateOrder = async ({ spuId }) => {
  try {
    await message.confirm('是否确认发布此职位？')
    await TradeOrderApi.updateOrderStatusToPublish(spuId)
    await getList()
    message.success('职位发布成功！')
  } catch {}
}

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

/** 退款按钮操作 */
const handleRefund = async (row: any) => {
  const id = row.id
  try {
    await message.confirm('是否确认退款编号为"' + id + '"的示例订单?')
    await TradeOrderApi.updateTradeOrder(id)
    await getList()
    message.success('发起退款成功！')
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  queryParams.payStatus = true
  getList()
})
</script>