<script setup lang="ts">
import obj from '@/utils/obj'
import { storeToRefs } from 'pinia'
import MjTable from '@/components/mj/mj-table'
import type { MjGridEventProps, MjGridProps } from '@/components/mj/mj-table'
import { coinTransactionService } from '@/api/service/coin-transaction'
import { sleepNotInWeb } from '@/utils'
import dayjs from '@/plugins/dayjs'
import router from '@/router'
import str from '@/utils/str'
import { userStore } from '@/stores'
import { useStudentManageStore } from '../store'
import num from '@/utils/num'

defineOptions({ name: 'CoinDetail' })

const stuMgrStore = storeToRefs(useStudentManageStore())
const schoolId = ref('' as any)
const { schoolOptions, schoolMap } = storeToRefs(userStore())
// 乐贝余额
const amount = computed(() => schoolMap.value[schoolId.value]?.schoolCurrency)

// 增加
const operation_add = 1
// 减少
// const operation_sub = 2

// 类型
// 充值
const type_charge = 1
// 发放奖励
const type_reward = 2
// 回收
const type_punish = 3
// 用户开户
const type_create_account = 4
// 转让
const type_transfer = 5
// 开户未激活退回
const coin_type_refund = 6
// 购买礼物
const coin_type_buy_gift = 7
const typeMap = {
  0: '所有类型',
  [type_charge]: '充值',
  [type_reward]: '奖励',
  [type_punish]: '回收',
  [type_create_account]: '开户续费',
  [type_transfer]: '转让',
  [coin_type_refund]: '开户未激活退回',
  [coin_type_buy_gift]: '购买礼物',
} as any
const typeList = obj.map2options(typeMap)
const typeCode = ref(0)
const finalSchoolOptions = ref([] as any)
// 时间
const time = ref(null as any)

function getTypeClass(row: any) {
  const type = Number(row.typeCode)
  if (type === type_punish) {
    return 'type-punish'
  }
  return row.operation === operation_add ? 'type-charge' : 'type-reward'
  // if (type === coin_type_charge) {
  //   return 'type-charge'
  // }
  // if (type === coin_type_reward) {
  //   return 'type-reward'
  // }
  // if (type === coin_type_create_account) {
  //   return 'type-reward'
  // }
  // return 'type-charge'
}

function getAmount(row: any) {
  const val = num.formatMoney(row.amount)
  return row.operation === operation_add ? `+${val}` : `-${val}`
}

const OSS_URL = import.meta.env.VITE_OSS_URL
const coinBg = `url(${OSS_URL}/urm/border_coin.svg) 100%/contain no-repeat`
const gridRef = ref()

watch([() => schoolId.value, () => typeCode.value, () => time.value], async () => {
  gridRef.value?.reload()
})

const grid = {
  proxyConfig: {
    autoLoad: false,
  },
  columns: [
    {
      title: '名称',
      fixed: 'left',
      formatter(params) {
        const row = params.row
        if (schoolId.value < 1) {
          return row.schoolName
        }
        if (!row.userName) {
          return row.schoolName || ''
        }
        if (row.className) {
          return row.className + ' - ' + str.redaction(row.userName)
        }
        return row.userName
      },
    },
    {
      title: '变化',
      slots: {
        default: 'amount',
      },
    },
    {
      title: '余量',
      field: 'balance',
      formatter: 'money',
    },
    {
      title: '类型',
      slots: {
        default: 'typeCode',
      },
    },
    {
      field: 'remark',
      title: '备注',
      formatter({ cellValue, row }) {
        if (row.userId !== row.operatorId && row.operatorName) {
          return `[${row.operatorName}]${cellValue}`
        }
        return cellValue
      },
    },
    {
      field: 'bizDate',
      title: '时间',
    },
  ],
  beforeLoadData(params: any) {
    if (schoolId.value) {
      params.schoolId = schoolId.value
    } else {
      params.schoolId = Object.keys(schoolMap.value)
    }
    params.typeCode = Number(typeCode.value) || undefined
    if (time.value?.length) {
      const fmt = 'YYYY-MM-DD HH:mm:ss'
      params.startTime = dayjs(time.value[0]).format(fmt)
      params.endTime = dayjs(time.value[1]).format(fmt)
    }
    return params
  },
} as MjGridProps

const gridEvents = {
  cellClick: ({ row }: any) => {
    if (!schoolId.value) return
    let userName = `${row.schoolName}-${row.userName}`
    if (row.className) {
      userName = `${row.schoolName}-${row.className}-${row.userName}`
    }
    router.push({
      path: '/self-coin-detail',
      query: {
        userId: row.userId,
        userName,
      },
    })
  },
} as MjGridEventProps

onMounted(async () => {
  await sleepNotInWeb()

  if (schoolOptions.value.length > 1) {
    finalSchoolOptions.value = [
      {
        label: '所有学校',
        value: 0,
      },
      ...schoolOptions.value,
    ] as any
  } else {
    finalSchoolOptions.value = schoolOptions.value
  }
  schoolId.value = stuMgrStore.schoolId.value
})
</script>

<template>
  <div class="coin-detail">
    <div class="top">
      <BackBar />
      <Select v-model="schoolId" width="350" :selectList="finalSchoolOptions as any" @click.stop />
      <Select v-model="typeCode" width="220" :selectList="typeList as any" @click.stop />
      <mj-date-picker v-model="time" clear-icon="none" />
    </div>
    <div v-if="schoolId" class="assets-box">
      <user-asset-item
        icon="coin"
        :amount="amount"
        :bg="coinBg"
        :icon-size="80"
        :popover="{
          title: '乐贝',
          icon: 'reward_coin',
        }"
      />
    </div>
    <div class="content">
      <mj-table
        ref="gridRef"
        class="coin-table"
        :grid="grid"
        :grid-events="gridEvents"
        :service="coinTransactionService"
        hide-remove
        hide-search
        hide-toolbar
      >
        <template #amount="{ row }">
          <span :class="`amount ${getTypeClass(row)}`">{{ getAmount(row) }}</span>
        </template>

        <template #typeCode="{ row }">
          {{ typeMap[row.typeCode] }}
        </template>
      </mj-table>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@use '../index.scss' as *;

.coin-detail {
  @include main_bg;

  width: 100%;
  height: 100%;
  padding: $space-4_h $space-6;
  position: relative;

  .top {
    display: flex;
    align-items: center;
    gap: 2vh;

    :deep(.mj-date-picker) {
      width: 780px;
      flex-grow: initial;
    }
  }

  .assets-box {
    position: absolute;
    top: $space-5;
    right: $space-6;
    display: flex;
  }

  .content {
    padding-top: 2.08vh;
    height: 88.33vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .pager-box {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 1vh 0;
    }

    .coin-table {
      border-top-left-radius: $raduis;
      border-top-right-radius: $raduis;
      border-bottom-left-radius: $raduis;
      border-bottom-right-radius: $raduis;

      .amount {
        &.type-charge {
          color: $success-color;
        }

        &.type-reward {
          color: $error-color;
        }

        &.type-punish {
          color: #3894ff;
          // color: $success-color;
        }
      }
    }
  }
}
</style>
