<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="900px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="92px" v-loading="formLoading">
      <el-collapse v-model="activeNames">
        <!-- 1) 基础信息 -->
        <el-collapse-item title="基础信息" name="base">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="提现单号" prop="withdrawNo">
                <el-input disabled v-model="formData.withdrawNo" placeholder="业务唯一单号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="幂等号" prop="bizNo">
                <el-input disabled v-model="formData.bizNo" placeholder="防重复提交，可选" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="币种" prop="currency">
                <el-input disabled v-model="formData.currency" placeholder="默认 CNY" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="打款渠道" prop="payChannel">
                <el-input disabled v-model="formData.payChannel" placeholder="BANK/ALIPAY/WECHAT..." />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="申请金额(元)" prop="amount">
                <el-input-number disabled v-model="formData.amount" :min="0" :precision="0" class="!w-full" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手续费(元)" prop="feeAmount">
                <el-input-number disabled v-model="formData.feeAmount" :min="0" :precision="0" class="!w-full" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="到账(元)" prop="actualAmount">
                <el-input-number disabled v-model="formData.actualAmount" :min="0" :precision="0" class="!w-full" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 2) 收款信息 -->
        <el-collapse-item title="收款信息" name="payee">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="收款方类型" prop="payeeType">
                <el-select disabled v-model="formData.payeeType" placeholder="请选择" class="!w-full">
                  <el-option label="个人" value="PERSON" />
                  <el-option label="企业" value="COMPANY" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收款人" prop="payeeName">
                <el-input disabled v-model="formData.payeeName" placeholder="姓名/公司名称" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="收款账号" prop="payeeAccount">
                <el-input disabled v-model="formData.payeeAccount" placeholder="银行卡/支付宝/微信等" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户行" prop="payeeBankName">
                <el-input disabled v-model="formData.payeeBankName" placeholder="可选" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="银行编码" prop="payeeBankCode">
                <el-input disabled v-model="formData.payeeBankCode" placeholder="可选" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="支行" prop="payeeBankBranch">
                <el-input disabled v-model="formData.payeeBankBranch" placeholder="可选" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 3) 状态与时间 -->
        <el-collapse-item title="状态与时间" name="statusTime">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="提现状态" prop="status">
                <el-select v-model="formData.status" placeholder="请选择" class="!w-full">
                  <el-option label="申请中" value="APPLIED" />
                  <el-option label="已审核" value="APPROVED" />
                  <el-option label="已拒绝" value="REJECTED" />
                  <el-option label="提现中" value="PAYING" />
                  <el-option label="已打款" value="PAID" />
                  <el-option label="打款失败" value="FAILED" />
                  <el-option label="已取消" value="CANCELED" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="审核状态" prop="auditStatus">
                <el-select v-model="formData.auditStatus" placeholder="请选择" class="!w-full">
                  <el-option label="待审核" value="PENDING" />
                  <el-option label="已通过" value="PASSED" />
                  <el-option label="已拒绝" value="REJECTED" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="申请时间" prop="applyTime">
                <el-date-picker v-model="formData.applyTime" type="datetime" value-format="x" placeholder="选择时间"
                  class="!w-full" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="审核时间" prop="auditTime">
                <el-date-picker v-model="formData.auditTime" type="datetime" value-format="x" placeholder="选择时间"
                  class="!w-full" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="发起打款" prop="payTime">
                <el-date-picker v-model="formData.payTime" type="datetime" value-format="x" placeholder="选择时间"
                  class="!w-full" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="打款成功" prop="paidTime">
                <el-date-picker v-model="formData.paidTime" type="datetime" value-format="x" placeholder="选择时间"
                  class="!w-full" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="终态时间" prop="finishTime">
                <el-date-picker v-model="formData.finishTime" type="datetime" value-format="x" placeholder="选择时间"
                  class="!w-full" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="原因" prop="reason">
                <el-input v-model="formData.reason" placeholder="拒绝/失败原因" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 4) 对账与扩展（默认折叠） -->
        <el-collapse-item title="对账与扩展" name="extra">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="批次号" prop="payerBatchNo">
                <el-input v-model="formData.payerBatchNo" placeholder="内部批次号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="交易号" prop="channelTradeNo">
                <el-input v-model="formData.channelTradeNo" placeholder="第三方流水号" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="原始报文" prop="channelRaw">
                <el-input v-model="formData.channelRaw" type="textarea" :rows="3" placeholder="用于排查，可选" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="余额流水" prop="balanceTxnId">
                <el-input v-model="formData.balanceTxnId" placeholder="冻结/扣减/返还" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本号" prop="version">
                <el-input v-model="formData.version" placeholder="乐观锁版本" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="申请人ID" prop="creatorId">
                <el-input v-model="formData.creatorId" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="审核人ID" prop="auditorId">
                <el-input v-model="formData.auditorId" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="打款人ID" prop="payerId">
                <el-input v-model="formData.payerId" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="创建时间" prop="createdAt">
                <el-date-picker v-model="formData.createdAt" type="datetime" value-format="x" placeholder="选择时间"
                  class="!w-full" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新时间" prop="updatedAt">
                <el-date-picker v-model="formData.updatedAt" type="datetime" value-format="x" placeholder="选择时间"
                  class="!w-full" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { TenantWithdrawOrderApi, TenantWithdrawOrder } from '@/api/keyboard/tenantwithdraworder'
const activeNames = ref<string[]>(['base', 'payee', 'statusTime']) // 默认展开三块，extra 默认折叠

/** 租户提现订单表（申请-审核-打款-完成/失败） 表单 */
defineOptions({ name: 'TenantWithdrawOrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  withdrawNo: undefined,
  bizNo: undefined,
  currency: undefined,
  amount: undefined,
  feeAmount: undefined,
  actualAmount: undefined,
  payChannel: undefined,
  payeeType: undefined,
  payeeName: undefined,
  payeeAccount: undefined,
  payeeBankName: undefined,
  payeeBankCode: undefined,
  payeeBankBranch: undefined,
  status: undefined,
  auditStatus: undefined,
  reason: undefined,
  applyTime: undefined,
  auditTime: undefined,
  payTime: undefined,
  paidTime: undefined,
  finishTime: undefined,
  payerBatchNo: undefined,
  channelTradeNo: undefined,
  channelRaw: undefined,
  balanceTxnId: undefined,
  version: undefined,
  creatorId: undefined,
  auditorId: undefined,
  payerId: undefined,
  createdAt: undefined,
  updatedAt: undefined
})
const formRules = reactive({
  withdrawNo: [{ required: true, message: '提现单号（业务唯一）不能为空', trigger: 'blur' }],
  currency: [{ required: true, message: '币种（默认 CNY）不能为空', trigger: 'blur' }],
  amount: [{ required: true, message: '提现申请金额（单位：分）不能为空', trigger: 'blur' }],
  feeAmount: [{ required: true, message: '手续费金额（单位：分）不能为空', trigger: 'blur' }],
  actualAmount: [{ required: true, message: '实际到账金额（单位：分 = amount - fee_amount）不能为空', trigger: 'blur' }],
  payChannel: [{ required: true, message: '打款渠道：BANK/ALIPAY/WECHAT/PAYPAL 等不能为空', trigger: 'blur' }],
  payeeType: [{ required: true, message: '收款方类型：PERSON（个人）/COMPANY（企业）不能为空', trigger: 'change' }],
  status: [{ required: true, message: '提现状态：APPLIED/APPROVED/REJECTED/PAYING/PAID/FAILED/CANCELED不能为空', trigger: 'blur' }],
  auditStatus: [{ required: true, message: '审核状态：PENDING/PASSED/REJECTED不能为空', trigger: 'blur' }],
  applyTime: [{ required: true, message: '提现申请时间不能为空', trigger: 'blur' }],
  version: [{ required: true, message: '乐观锁版本号不能为空', trigger: 'blur' }],
  createdAt: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
  updatedAt: [{ required: true, message: '更新时间不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TenantWithdrawOrderApi.getTenantWithdrawOrder(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TenantWithdrawOrder
    if (formType.value === 'create') {
      await TenantWithdrawOrderApi.createTenantWithdrawOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await TenantWithdrawOrderApi.updateTenantWithdrawOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    withdrawNo: undefined,
    bizNo: undefined,
    currency: undefined,
    amount: undefined,
    feeAmount: undefined,
    actualAmount: undefined,
    payChannel: undefined,
    payeeType: undefined,
    payeeName: undefined,
    payeeAccount: undefined,
    payeeBankName: undefined,
    payeeBankCode: undefined,
    payeeBankBranch: undefined,
    status: undefined,
    auditStatus: undefined,
    reason: undefined,
    applyTime: undefined,
    auditTime: undefined,
    payTime: undefined,
    paidTime: undefined,
    finishTime: undefined,
    payerBatchNo: undefined,
    channelTradeNo: undefined,
    channelRaw: undefined,
    balanceTxnId: undefined,
    version: undefined,
    creatorId: undefined,
    auditorId: undefined,
    payerId: undefined,
    createdAt: undefined,
    updatedAt: undefined
  }
  formRef.value?.resetFields()
}
</script>