<template>
  <div class="withdraw-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>
    <Table
      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
        ref="formRef" 
        :formItems="formItems"
        :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: 'WithdrawChanl'
})
//组件
import Table 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 {
  getChannelWithdrawList,
  createChannelWithdraw,
  editChannelWithdraw,
  delChannelWithdraw,
  getChannelList,
} from '@/api/modules/capital/withdrawChanl'
import { ElMessageBox } from 'element-plus'

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

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

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

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

const dialogVisible = ref(false)
const dialogTitleType = ref(1)
const formData = ref<any>({
  name: '',
  channel_fee: null,
  currency_id: null,
  api_url: '',
  api_appid: '',
  api_key: '',
  channel_code: '',
  status: 1,
})
const formItems = ref<any>(formItemsData)
const formRules = ref(formRulesData)
const optionsMap = ref(optionsMapData)
const submitDetail = async () => {
  await formRef.value.validate()
  startSubmitLoading();
  try {
    dialogVisible.value = false
    if (dialogTitleType.value === 1) {
      await createChannelWithdraw(formData.value)
    } else {
      await editChannelWithdraw(formData.value)
    }
    await initData()
  } finally {
    stopSubmitLoading();
  }
}

let currentRow: any = {}

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

const resetFormData = () => {
  formData.value = {
    name: '',
    channel_fee: null,
    currency_id: null,
    api_url: '',
    api_appid: '',
    api_key: '',
    channel_code: '',
    status: 1,
  }
}

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 delChannelWithdraw({ id: currentRow.id })
      await initData()
    })
    .catch(() => {
      console.log('取消删除')
    })
}

const clearSelection = () => {
  currentRow = {}
  nextTick(() => {
    tableRef.value?.clearCurrentRow()
  })
}

onMounted(() => {
  initData()
  // 获取货币列表用于下拉框
  getChannelList().then((data:any) => {
    console.log(data)
    optionsMap.value.currency_id = (data || []).map((item: any) => ({
      value: item.id,
      label: item.name,
    }))
    console.log('optionsMap.value:', optionsMap.value);
  })
})
</script>
<style scoped>
.withdraw-channel {
  .bar {
    margin-bottom: 10px;
    display: flex;
    align-items: center;

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