<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item label="当前积分余额" prop="balance">
        <el-input v-model="queryParams.balance" placeholder="请输入当前积分余额" clearable @keyup.enter="handleQuery"
          class="!w-240px" />当前积分余额
      </el-form-item>
      <!-- <el-form-item label="乐观锁版本号" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入乐观锁版本号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker v-model="queryParams.updatedAt" value-format="YYYY-MM-DD" type="date" placeholder="选择更新时间"
          clearable class="!w-240px" />
      </el-form-item>
      <el-form-item label="测试账户数量" prop="testAccountNum">
        <el-input v-model="queryParams.testAccountNum" placeholder="请输入测试账户数量" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <!-- <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['keyboard:tenant-balance:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['keyboard:tenant-balance:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['keyboard:tenant-balance:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      highlight-current-row @current-change="handleCurrentChange" @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="租户 Id" align="center" prop="id" />
      <el-table-column label="不可提现余额" align="center" prop="balance" />
      <el-table-column label="冻结金额" align="center" prop="frozenAmt" />
      <el-table-column label="可提现金额" align="center" prop="withdrawableBalance" />
      <el-table-column label="更新时间" align="center" prop="updatedAt" :formatter="dateFormatter" width="180px" />
      <el-table-column label="测试账户数量" align="center" prop="testAccountNum" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button link type="primary" @click="openRecharge(scope.row)"
            v-hasPermi="['keyboard:tenant-balance:update']" v-if="userStore.getUser.id === 1">
            充值
          </el-button>
          <el-button link type="warning" @click="openWithdraw" v-hasPermi="['keyboard:tenant-balance:update']">
            提现
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-hasPermi="['keyboard:tenant-balance:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TenantBalanceForm ref="formRef" @success="getList" />
  <Dialog v-model="rechargeDialogVisible" title="充值" width="500px">
    <el-form ref="rechargeFormRef" v-loading="rechargeLoading" :model="rechargeFormData" :rules="rechargeFormRules"
      label-width="100px">
      <el-form-item label="租户 Id" prop="id">
        <el-input v-model="rechargeFormData.id" class="!w-240px" disabled />
      </el-form-item>
      <el-form-item label="充值金额" prop="amount">
        <el-input-number v-model="rechargeFormData.amount" :min="1" :precision="0" class="!w-240px"
          controls-position="right" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="rechargeFormData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="rechargeLoading" @click="submitRecharge">充值确认</el-button>
      <el-button @click="rechargeDialogVisible = false">取消</el-button>
    </template>
  </Dialog>
  <Dialog v-model="withdrawDialogVisible" title="提现" width="600px">
    <el-form ref="withdrawFormRef" v-loading="withdrawLoading" :model="withdrawFormData" :rules="withdrawFormRules"
      label-width="120px">
      <el-form-item label="提现金额" prop="amount">
        <el-input-number v-model="withdrawFormData.amount" :min="1" :precision="0" class="!w-240px"
          controls-position="right" />
      </el-form-item>
      <el-form-item label="打款渠道" prop="payChannel">
        <el-select v-model="withdrawFormData.payChannel" placeholder="请选择打款渠道" class="!w-240px">
          <el-option v-for="item in payChannelOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="收款方类型" prop="payeeType">
        <el-select v-model="withdrawFormData.payeeType" placeholder="请选择收款方类型" class="!w-240px">
          <el-option v-for="item in payeeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="收款人名称" prop="payeeName">
        <el-input v-model="withdrawFormData.payeeName" placeholder="请输入收款人名称" />
      </el-form-item>
      <el-form-item label="收款账号" prop="payeeAccount">
        <el-input v-model="withdrawFormData.payeeAccount" placeholder="请输入收款账号" />
      </el-form-item>
      <el-form-item label="收款银行名称" prop="payeeBankName">
        <el-input v-model="withdrawFormData.payeeBankName" placeholder="请输入收款银行名称" />
      </el-form-item>
      <el-form-item label="银行编码" prop="payeeBankCode">
        <el-input v-model="withdrawFormData.payeeBankCode" placeholder="请输入银行编码" />
      </el-form-item>
      <el-form-item label="银行支行名称" prop="payeeBankBranch">
        <el-input v-model="withdrawFormData.payeeBankBranch" placeholder="请输入银行支行名称" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="withdrawFormData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="withdrawLoading" @click="submitWithdraw">提现确认</el-button>
      <el-button @click="withdrawDialogVisible = false">取消</el-button>
    </template>
  </Dialog>
  <!-- 子表的列表 -->
  <ContentWrap>
    <el-tabs model-value="tenantBalanceTransaction">
      <el-tab-pane label="租户积分记录" name="tenantBalanceTransaction">
        <TenantBalanceTransactionList ref="transactionListRef" :tenant-id="currentRow.id" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { TenantBalanceApi, TenantBalance } from '@/api/keyboard/tenantbalance'
import { TenantWithdrawOrderApi } from '@/api/keyboard/tenantwithdraworder'
import TenantBalanceForm from './TenantBalanceForm.vue'
import TenantBalanceTransactionList from './components/TenantBalanceTransactionList.vue'
import { useUserStore } from '@/store/modules/user'
/** 租户余额 列表 */
defineOptions({ name: 'KeyboardTenantBalance' })
const userStore = useUserStore()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<TenantBalance[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  balance: undefined,
  version: undefined,
  updatedAt: undefined,
  updatedAt: [],
  testAccountNum: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TenantBalanceApi.getTenantBalancePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const rechargeDialogVisible = ref(false)
const rechargeLoading = ref(false)
const rechargeFormRef = ref()
const rechargeFormData = ref({
  id: undefined,
  amount: undefined,
  remark: ''
})
const rechargeFormRules = reactive({
  amount: [{ required: true, message: '充值金额不能为空', trigger: 'blur' }],
  remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
})

const payChannelOptions = [
  { label: '银行', value: 'BANK' },
  { label: '支付宝', value: 'ALIPAY' },
  { label: '微信', value: 'WECHAT' },
  { label: 'PAYPAL', value: 'PAYPAL' }
]
const payeeTypeOptions = [
  { label: '个人', value: 'PERSON' },
  { label: '企业', value: 'COMPANY' }
]

const withdrawDialogVisible = ref(false)
const withdrawLoading = ref(false)
const withdrawFormRef = ref()
const withdrawFormData = ref({
  amount: undefined,
  payChannel: undefined,
  payeeType: undefined,
  payeeName: '',
  payeeAccount: '',
  payeeBankName: '',
  payeeBankCode: '',
  payeeBankBranch: '',
  remark: ''
})
const withdrawFormRules = reactive({
  amount: [{ required: true, message: '提现金额不能为空', trigger: 'blur' }],
  payChannel: [{ required: true, message: '打款渠道不能为空', trigger: 'change' }],
  payeeType: [{ required: true, message: '收款方类型不能为空', trigger: 'change' }],
  payeeName: [{ required: true, message: '收款人名称不能为空', trigger: 'blur' }],
  payeeAccount: [{ required: true, message: '收款账号不能为空', trigger: 'blur' }],
  payeeBankName: [{ required: true, message: '收款银行名称不能为空', trigger: 'blur' }]
})

const openRecharge = (row: TenantBalance) => {
  rechargeDialogVisible.value = true
  resetRechargeForm()
  rechargeFormData.value.id = row.id
}

const submitRecharge = async () => {
  const valid = await rechargeFormRef.value?.validate()
  if (!valid) return
  rechargeLoading.value = true
  try {
    await TenantBalanceApi.addAmountBalance({
      id: rechargeFormData.value.id,
      amount: rechargeFormData.value.amount,
      remark: rechargeFormData.value.remark
    })
    message.success('充值成功')

    rechargeDialogVisible.value = false
    await getList()
    transactionListRef.value?.refresh?.()
  } finally {
    rechargeLoading.value = false
  }
}

const resetRechargeForm = () => {
  rechargeFormData.value = {
    id: undefined,
    amount: undefined,
    remark: ''
  }
  rechargeFormRef.value?.resetFields()
}

const openWithdraw = () => {
  withdrawDialogVisible.value = true
  resetWithdrawForm()
}

const submitWithdraw = async () => {
  const valid = await withdrawFormRef.value?.validate()
  if (!valid) return
  withdrawLoading.value = true
  try {
    await TenantWithdrawOrderApi.withdrawTenantBalance({
      amount: withdrawFormData.value.amount,
      payChannel: withdrawFormData.value.payChannel,
      payeeType: withdrawFormData.value.payeeType,
      payeeName: withdrawFormData.value.payeeName,
      payeeAccount: withdrawFormData.value.payeeAccount,
      payeeBankName: withdrawFormData.value.payeeBankName,
      payeeBankCode: withdrawFormData.value.payeeBankCode,
      payeeBankBranch: withdrawFormData.value.payeeBankBranch,
      remark: withdrawFormData.value.remark
    })
    message.success('提现成功')
    withdrawDialogVisible.value = false
    await getList()
    transactionListRef.value?.refresh?.()
  } finally {
    withdrawLoading.value = false
  }
}

const resetWithdrawForm = () => {
  withdrawFormData.value = {
    amount: undefined,
    payChannel: undefined,
    payeeType: undefined,
    payeeName: '',
    payeeAccount: '',
    payeeBankName: '',
    payeeBankCode: '',
    payeeBankBranch: '',
    remark: ''
  }
  withdrawFormRef.value?.resetFields()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TenantBalanceApi.deleteTenantBalance(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除租户余额 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await TenantBalanceApi.deleteTenantBalanceList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: TenantBalance[]) => {
  checkedIds.value = records.map((item) => item.id!);
}

const transactionListRef = ref()

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TenantBalanceApi.exportTenantBalance(queryParams)
    download.excel(data, '租户余额.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中行操作 */
const currentRow = ref({}) // 选中行
const handleCurrentChange = (row) => {
  currentRow.value = row
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
