<!-- eslint-disable unicorn/prefer-ternary -->
<script setup lang="ts">
import type { FormRules } from 'element-plus'

import { Plus } from '@vben/icons'
import { useUserStore } from '@vben/stores'

import { orderService } from '#/api/service/order'
import { spLearnOfflineChargeService } from '#/api/service/sp/learn-offline-charge'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

defineOptions({ name: 'TopUp' })
const props = withDefaults(
  defineProps<{
    modelValue?: boolean
  }>(),
  {
    modelValue: false,
  },
)

const emits = defineEmits(['update:modelValue', 'refresh'])

const { userInfo } = storeToRefs(useUserStore())

const show = computed({
  get() {
    return props.modelValue
  },
  async set(newVal) {
    emits('update:modelValue', newVal)
    topUpRef.value?.reset()
  },
})

const moneyOptions = obj.joinObjs(
  !userInfo.value.isSelf || { label: '1元', value: 1 },
  {
    label: '100元',
    value: 100,
  },
  {
    label: '500元',
    value: 500,
  },
  {
    label: '1000元',
    value: 1000,
  },
  {
    label: '自定义',
    value: 0,
  },
)

// 表单
const formRef = ref()
const form = reactive({
  // 线下充值金额
  amount: '',
  // 线下充值时间
  bizDate: '',
  // 文件列表
  fileList: [] as any[],
})
const rules = reactive<FormRules<typeof form>>({
  amount: [
    {
      validator: validateAmount,
      required: true,
      trigger: 'blur',
    },
  ],
  bizDate: [{ required: true, message: '请选择转账时间', trigger: 'blur' }],
  fileList: [{ required: true, message: '请上传转账截图', trigger: 'blur' }],
})

const topUpRef = ref()

// 充值成功
function topUpSuccess() {
  emits('refresh')
}

// 充值
async function pay(money: any) {
  return await orderService.createSpLearnMoneyTopUpOrder({
    money,
    type: 1,
    typeId: userInfo.value.providerId,
  })
}

function validateAmount(_: any, value: any, callback: any) {
  const val = Number(value)
  if (!val || val < 0) {
    callback(new Error('请输入正确的金额'))
  } else {
    callback()
  }
}

// 提交线下充值
function submitOffline() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return
    hud.load({
      task: async () => {
        await spLearnOfflineChargeService.register({
          amount: form.amount,
          bizDate: form.bizDate,
          files: form.fileList.map((item: any) => item.raw),
        })
        emits('update:modelValue', false)
      },
      option: '提交',
      hideSuccess: false,
    })
  })
}
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title: '乐学金充值',
      width: 600,
      height: '80%',
    }"
  >
    <div class="container">
      <el-tabs>
        <el-tab-pane label="线上充值">
          <wx-top-up
            ref="topUpRef"
            title="请选择充值金额(1元=1乐学金)"
            :money-options="moneyOptions"
            @success="topUpSuccess"
            :pay="pay"
          />
        </el-tab-pane>
        <el-tab-pane label="线下充值">
          <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item label="收款账户">
              <div class="flex flex-col">
                <div>【账户名】广州小码哥教育科技有限公司</div>
                <div>【账号】120915416810588</div>
                <div>【开户行】招商银行广州分行科技园支行</div>
              </div>
            </el-form-item>
            <el-form-item label="转账金额" prop="amount" required>
              <mj-form-money
                class="w-full"
                v-model="form.amount"
                placeholder="请输入转账金额"
              />
            </el-form-item>
            <el-form-item label="转账时间" prop="bizDate" required>
              <el-date-picker
                v-model="form.bizDate"
                type="datetime"
                placeholder="请选择转账时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="转账截图" prop="fileList" required>
              <div class="flex flex-col">
                <div class="mb-2">最多传3张</div>
                <el-upload
                  v-model:file-list="form.fileList"
                  list-type="picture-card"
                  :limit="3"
                  :auto-upload="false"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </div>
            </el-form-item>
          </el-form>
          <el-button
            class="mt-2 h-10 w-full text-base font-bold"
            type="primary"
            @click="submitOffline"
          >
            提交
          </el-button>
        </el-tab-pane>
      </el-tabs>
    </div>
  </mj-modal>
</template>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  gap: 20px;

  :deep(.el-date-editor--datetime) {
    width: 100%;
  }

  :deep(.el-tabs) {
    .el-tabs__item {
      font-size: 18px;
    }

    .el-form-item {
      margin-bottom: 30px;
    }

    .el-form-item__content,
    .el-form-item__label {
      font-size: 16px;
    }
  }
}
</style>
