<template>
  <div class="deposit-channel table_form-container">
    <div class="bar">
      <el-button type="primary" @click="handleAdd" v-auth="'channel_createChannel'">添加</el-button>
      <el-button type="primary" @click="handleEdit" v-auth="'channel_editChannel'">编辑</el-button>
      <el-button type="danger" @click="handleDelete" v-auth="'channel_delChannel'">删除</el-button>
    </div>
    <DepositChannelTable ref="tableRef" :table-data="tableData" :columns="tableColumnsOptions" row-key="id"
      :loading="loading" @rowClick="handleRowClick" />
    <el-dialog v-model="dialogVisible" :title="dialogTitleType === 1 ? '添加充值渠道' : '编辑充值渠道'" width="700">
      <Form :formItems="formItems" ref="formRef" :formRules="formRules" :formData="formData" :optionsMap="optionsMap" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitDetail">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">

defineOptions({
  name: 'RechangeChanl'
})
//组件
import DepositChannelTable from '@/components/common/Table.vue'
import Form from '@/components/common/Form.vue'
import { usePageLoading, useButtonLoading } from '@/composables/useLoading'
import { tableColumns, formItemsData, formRulesData, optionsMapData } from './options'
import {
  getChannelList,
  createChannel,
  editChannel,
  delChannel,
} from '@/api/modules/capital/rechangeChanl.ts'
import { getCurrencyList } from '@/api/modules/capital/currency.ts'
import { ElMessageBox } from 'element-plus'

type ChannelType = {
  id?: number
  name: string
  channel_fee: number | null
  type: number | null
  api_url: string
  api_appid: string
  api_key: string
  status: number
}

const getStatusText = (status: number | string) => {
  return ['', '正常', '禁用'][status]
}

const formRef = ref()
const { loading, startLoading, stopLoading } = usePageLoading()
const { buttonLoading: submitLoading, startButtonLoading: startSubmitLoading, stopButtonLoading: stopSubmitLoading } = useButtonLoading()
const initData = async () => {
  try {
    startLoading()
    const res = await getChannelList()
    console.log(res)
    tableData.value = res.map((item: ChannelType) => ({
      ...item,
      statusStr: getStatusText(item.status),
    })) as ChannelType[]
    clearSelection()
  } finally {
    stopLoading()
  }
}

//表格数据
const tableColumnsOptions = ref(tableColumns)
const tableData = ref([])
const tableRef = ref()

const dialogVisible = ref(false)
const dialogTitleType = ref(1)
const formData = ref({
  name: '',
  channel_fee: null,
  type: null,
  api_url: '',
  api_appid: '',
  api_key: '',
  beneficiary_name: '',
  beneficiary_bank_name: '',
  swift_bic_code: '',
  beneficiary_bank_account: '',
  beneficiary_bank_address: '',
  address: '',
  channel_code: '',
  status: 1,
})
const formItems = ref(formItemsData)
const formRules = ref(formRulesData)
const optionsMap = ref(optionsMapData)
const submitDetail = async () => {
  await formRef.value.validate()
  startSubmitLoading();
  try {
    if (dialogTitleType.value === 1) {
      await createChannel(formData.value)
    } else {
      await editChannel(formData.value)
    }
  } finally {
    dialogVisible.value = false
    stopSubmitLoading();
  }
  await initData()
}

let currentRow: any = {}

const handleRowClick = (row: any) => {
  console.log('handleRowClick', row)
  currentRow = row
}

const resetFormData = () => {
  formData.value = {
    name: '',
    channel_fee: null,
    type: null,
    api_url: '',
    api_appid: '',
    api_key: '',
    status: 1,
    beneficiary_name: '',
    beneficiary_bank_name: '',
    swift_bic_code: '',
    bank_account: '',
    beneficiary_bank_address: '',
    address: '',
    channel_code: '',
  }
}

const handleAdd = () => {
  dialogVisible.value = true
  dialogTitleType.value = 1
  resetFormData()
}

const handleEdit = () => {
  if (!currentRow.id) return ElMessage.warning('请先选择要编辑的记录')

  dialogVisible.value = true
  dialogTitleType.value = 2
  formData.value = currentRow
}

const handleDelete = () => {
  console.log('handleDisable')
  if (!currentRow.id) return ElMessage.warning('请先选择要删除的记录')
  ElMessageBox.confirm('确认删除吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(async () => {
      await delChannel({ id: currentRow.id })
      await initData()
    })
    .catch(() => {
      console.log('取消删除')
    })
}

const clearSelection = () => {
  currentRow = {}
  nextTick(() => {
    tableRef.value?.clearCurrentRow() // 调用子组件方法取消高亮
  })
}

onMounted(() => {
  initData()
  getCurrencyList().then((data) => {
    console.log(data)
    optionsMap.value.type = (data || []).map((item: any) => ({
      value: item.id,
      label: item.symbol,
    }))
  })
})
</script>
<style scoped>
.deposit-channel {
  .bar {
    margin-bottom: 10px;
    display: flex;
    align-items: center;

    span {
      margin-right: 10px;
    }
  }
}
</style>
