<!-- eslint-disable unicorn/prefer-ternary -->
<script setup lang="ts" name="replace-mgr">
import type { MjGridProps } from '#/components/mj/mj-table'

import { parentLearnAmountService } from '#/api/service/parent/learn-amount'
import MjTable, {
  mj_form_date_range,
  mj_form_select,
} from '#/components/mj/mj-table'
import { useCoin } from '#/hooks/coin'
import obj from '#/utils/obj'

const { getTypeClass, getAmount } = useCoin()

const searchEvents = {
  change() {
    gridRef.value.reload()
  },
}

// 搜索表单
const searchForm = {
  items: obj.joinObjs<any>(
    {
      title: '类型',
      field: 'type',
      span: 12,
      itemRender: {
        name: mj_form_select,
        props: { clearable: true },
        options: learn_amount_type_options,
        events: searchEvents,
      },
    },
    {
      title: '时间',
      field: 'timeRange',
      span: 12,
      itemRender: {
        name: mj_form_date_range,
        props: { clearable: true, type: 'datetime' },
      },
    },
  ),
} as any

// 表格
const gridRef = ref()
const grid = {
  columns: [
    { type: 'seq' },
    {
      title: '名称',
      field: 'user.nickname',
      formatter: 'redaction',
    },
    {
      title: '手机',
      field: 'user.phone',
      formatter: 'redactionPhone',
    },
    {
      title: '头像',
      slots: {
        default: 'userAvatar',
      },
    },
    {
      title: '金额',
      field: 'amount',
      formatter: 'money',
    },
    {
      title: '余额',
      field: 'balance',
      formatter: 'money',
    },
    {
      field: 'type',
      title: '类型',
      formatter({ cellValue }) {
        return learn_amount_type_map[cellValue]
      },
    },
    { field: 'remark', title: '备注', formatter: 'redactionRemark' },
    { field: 'bizDate', title: '时间' },
  ],
  beforeLoadData(params) {
    // 拆分时间参数
    if (params.timeRange) {
      const times = params.timeRange.split(',')
      params.startTime = times[0]
      params.endTime = times[1]
      delete params.timeRange
    }
    return params
  },
} as MjGridProps
</script>

<template>
  <div class="learn-amount g-container">
    <MjTable
      ref="gridRef"
      hide-toolbar
      hide-remove
      :grid="grid"
      :service="parentLearnAmountService"
      :search-form="searchForm"
    >
      <template #type="{ row }">
        <span :class="getTypeClass(row)">{{
          learn_amount_type_map[row.type]
        }}</span>
      </template>
      <template #userAvatar="{ row }">
        <div class="avatar">
          <img v-if="row.user?.avatar" :src="row.user?.avatar" />
        </div>
      </template>
      <template #amount="{ row }">
        <span :class="getTypeClass(row)">{{ getAmount(row) }}</span>
      </template>
    </MjTable>
  </div>
</template>

<style lang="scss" scoped>
.learn-amount {
  height: 100% !important;

  .avatar {
    display: flex;
    justify-content: center;

    img {
      width: 40px;
      height: 40px;
    }
  }
}
</style>
