<script setup lang="ts">
import type { MjFormProps, MjGridProps } from '#/components/mj/mj-table'

import { useUserStore } from '@vben/stores'

import { Sell } from '@element-plus/icons-vue'
import Big from 'big.js'

import { spCoinTradeService } from '#/api/service/sp/coin-trade'
import MjTable, { mj_form_select } from '#/components/mj/mj-table'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

import BuyCoin from './buy-coin.vue'
import SellCoin from './sell-coin.vue'

const { userInfo } = storeToRefs(useUserStore())

// 0: 保存 1: 上架 2: 锁定 3:完成 4:下架
const status_on = 1
const status_lock = 2
const status_done = 3
const status_offline = 4
const statusMap = {
  [status_on]: '在售',
  [status_lock]: '交易中',
  [status_done]: '交易成功',
  [status_offline]: '已下架',
} as any
const statusOptions = obj.map2options(statusMap)

// 搜索表单
const searchForm = {
  items: [
    {
      title: '状态',
      field: 'status',
      span: 6,
      itemRender: {
        name: mj_form_select,
        options: statusOptions,
        events: {
          change: () => {
            gridRef.value.reload()
          },
        },
      },
    },
  ],
} as MjFormProps

// 表格
const gridRef = ref()
const grid = {
  columns: [
    { type: 'seq' },
    {
      field: 'sellerName',
      title: '卖方',
      formatter: 'redaction',
    },
    { field: 'amount', title: '乐贝', formatter: 'money' },
    { field: 'price', title: '原价(¥)', formatter: 'money' },
    { field: 'discount', title: '折扣' },
    { field: 'discountedPrice', title: '买家实付(¥)', formatter: 'money' },
    {
      field: 'sellerGet',
      title: '卖家实获(¥)',
      formatter({ row }) {
        return Big(row.discountedPrice).times(0.8)
      },
    },
    {
      field: 'status',
      title: '状态',
      formatter({ cellValue }) {
        return statusMap[cellValue]
      },
    },
    {
      title: '操作',
      fixed: 'right',
      slots: {
        default: 'operation',
      },
    },
  ],
  cellClassName({ column, row }) {
    if (column.field === 'discountedPrice') {
      return 'progress-100'
    }
    if (column.field === 'sellerGet') {
      return 'progress-80'
    }
    if (column.field !== 'status') {
      return
    }
    const status = Number(row.status)
    if (status === status_on) {
      return 'progress-80'
    }
    if (status === status_lock) {
      return 'progress-1'
    }
    if (status === status_done) {
      return 'progress-100'
    }
    if (status === status_offline) {
      return 'progress-0'
    }
  },
} as MjGridProps

// 是否显示取消按钮
function isShowCancel(row: any) {
  // 交易中 && 是自己购买的
  return Number(row.status) === status_lock
}

// 是否显示购买
function isShowBuy(row: any) {
  // 有购买权限 && 不是自己发布的
  return (
    userInfo.value.buyerFlag &&
    row.sellerId !== userInfo.value.providerId &&
    Number(row.status) === status_on
  )
}

// 是否显示下架
function isShowOffline(row: any) {
  // 状态为上架 && 是自己发布的
  const status = Number(row.status)
  return (
    (status === status_on || status === status_lock) &&
    row.sellerId === userInfo.value.providerId
  )
}

// 出售乐贝
const sellVisible = ref(false)
function showSell() {
  sellVisible.value = true
}

// 购买
const buyData = ref({})
const buyVisible = ref(false)
function showBuy(row: any) {
  buyData.value = row
  buyVisible.value = true
}

// 下架
function offline(row: any) {
  hud.confirmLoad('确定要下架么？', {
    task: async () => {
      await spCoinTradeService.offline({
        productId: row.id,
      })
      reload()
    },
    option: '下架',
    hideSuccess: false,
  })
}

// 刷新
function reload() {
  gridRef.value.reload()
}

// 取消购买
function cancel(row: any) {
  hud.confirmLoad('确定要取消购买么？', {
    task: async () => {
      await spCoinTradeService.cancelOrder({
        orderId: row.orderId,
      })
      reload()
    },
    option: '取消购买',
    hideSuccess: false,
  })
}

// 继续支付
const continuePayVisible = ref(false)
function showContinuePay(row: any) {
  buyData.value = row
  continuePayVisible.value = true
}

async function continuePay() {
  // TODO 加载二维码URL
  buyData.value = 'row'
  continuePayVisible.value = true
}

async function getContinueStatus() {
  // TODO 轮询查询支付状态
}
</script>

<template>
  <div class="coin-trade g-container">
    <SellCoin v-model="sellVisible" @refresh="reload" />
    <BuyCoin v-model="buyVisible" @refresh="reload" :data="buyData" />
    <wx-code-pay
      v-model="continuePayVisible"
      title="继续支付"
      :pay="continuePay"
      :get-status="getContinueStatus"
      @success="reload"
    />
    <MjTable
      ref="gridRef"
      :grid="grid"
      :service="spCoinTradeService"
      :search-form="searchForm"
      hide-remove
      :hide-toolbar="!userInfo.sellerFlag"
    >
      <template v-if="userInfo.sellerFlag" #toolbarButtonsExtra>
        <el-button type="primary" @click="showSell" :icon="Sell">
          出售乐贝
        </el-button>
      </template>
      <template #operation="{ row }">
        <el-button v-if="isShowBuy(row)" type="success" @click="showBuy(row)">
          购买
        </el-button>
        <el-button
          v-if="isShowOffline(row)"
          type="danger"
          @click="offline(row)"
        >
          下架
        </el-button>
        <template v-if="isShowCancel(row)">
          <el-button type="danger" @click="cancel(row)">取消购买</el-button>
          <el-button type="success" @click="showContinuePay(row)">
            继续支付
          </el-button>
        </template>
      </template>
    </MjTable>
  </div>
</template>

<style lang="scss" scoped></style>
