<template>
  <el-container>
    <el-main>
      <el-form ref="formRef" :model="formData" :label-width="formLabelWidth" :rules="rules">
        <!-- 审核通过时显示通道选择 -->
        <el-form-item v-if="auditType === 'approve'" :label="t('modules.withdraw.paymentChannel') + '：'"
          prop="channelId">
          <el-select v-model="formData.channelId" :placeholder="t('modules.withdraw.selectPaymentChannel')"
            style="width: 100%" @change="handleChannelChange" :loading="channelLoading">
            <el-option v-for="channel in channelList" :key="channel.id" :label="channel.channelName"
              :value="channel.id" />
          </el-select>
        </el-form-item>

        <!-- 通道代码选择 -->
        <!-- <el-form-item v-if="auditType === 'approve' && formData.channelId"
          :label="t('modules.withdraw.channelCode') + '：'" prop="channelCode">
          <el-radio-group v-model="formData.channelCode">
            <el-radio v-for="code in channelCodeOptions" :key="code.value" :label="code.value">
              {{ code.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item> -->

        <!-- 审核内容 -->
        <el-form-item
          :label="auditType === 'approve' ? t('modules.withdraw.auditRemark') + '：' : t('modules.withdraw.rejectReason') + '：'"
          prop="review">
          <el-input v-model="formData.review" type="textarea" :rows="4" :placeholder="auditType === 'approve' ? t('modules.withdraw.enterAuditRemark') : t('modules.withdraw.enterRejectReason')
            " :maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button @click="handleCancel">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">{{ t('common.submit') }}</el-button>
    </el-footer>
  </el-container>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useFormConfig } from '@/hooks/useFormConfig';
import { api } from '../finance.service';
import adminApi from '@/app/admin/api';

const { t } = useI18n();

const props = defineProps(['modal']);
const emit = defineEmits(['modalCallBack']);

const formRef = ref();
const loading = ref(false);
const channelLoading = ref(false);
const channelList = ref([]);
const channelCodeOptions = ref([]);

// 审核类型：approve(通过) 或 reject(拒绝)
const auditType = computed(() => props.modal?.params?.type || 'approve');

// 表单数据
const formData = reactive({
  review: '', // 审核内容
  channelId: '', // 支付通道ID
  channelCode: '', // 通道代码
});

// 使用表单配置hooks
const { formLabelWidth, formLayout } = useFormConfig();
// 获取支付通道列表
async function getChannelList() {
  if (auditType.value !== 'approve') return;

  channelLoading.value = true;
  try {
    const { code, data } = await adminApi.payment.channel.list({});
    if (code === '200') {
      channelList.value = data || [];
    }
  } catch (error) {
    console.error('获取支付通道失败:', error);
    ElMessage.error(t('message.fetchDataFailed'));
  } finally {
    channelLoading.value = false;
  }
}

// 处理通道变更
function handleChannelChange(channelId) {
  formData.channelCode = ''; // 重置通道代码

  const selectedChannel = channelList.value.find(channel => channel.id === channelId);
  if (selectedChannel) {
    // 构建通道代码选项
    channelCodeOptions.value = [
      {
        label: 'Bkash',
        value: selectedChannel.bkashPayCode
      },
      {
        label: 'Nagad',
        value: selectedChannel.nagadPayCode
      },
      {
        label: 'Rocket',
        value: selectedChannel.rocketPayCode
      }
    ].filter(option => option.value); // 过滤掉空值
  }
}

// 表单验证规则
const rules = computed(() => {
  const baseRules = {};

  if (auditType.value === 'reject') {
    // 拒绝时必须填写原因
    baseRules.review = [
      { required: true, message: t('modules.withdraw.rejectReasonRequired'), trigger: 'blur' },
      { min: 1, max: 200, message: t('modules.withdraw.rejectReasonLength'), trigger: 'blur' },
    ];
  } else if (auditType.value === 'approve') {
    // 审核通过时需要选择通道和通道代码
    baseRules.channelId = [
      { required: true, message: t('modules.withdraw.paymentChannelRequired'), trigger: 'change' }
    ];
    baseRules.channelCode = [
      { required: true, message: t('modules.withdraw.channelCodeRequired'), trigger: 'change' }
    ];
  }

  return baseRules;
});

// 取消操作
function handleCancel() {
  emit('modalCallBack', { action: 'cancel' });
}

// 确认操作
async function handleConfirm() {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;

    // 构建请求参数
    const requestData = {
      id: props.modal?.params?.id,
      type: auditType.value === 'approve' ? 1 : 2, // 1通过 2不通过
      review: formData.review || '', // 审核内容
    };

    // 审核通过时添加通道信息
    if (auditType.value === 'approve') {
      requestData.channelId = formData.channelId;
    }

    // 调用审核API
    const { code, message } = await api.withdraw.review(requestData);

    if (code === '200') {
      const successMessage = auditType.value === 'approve' ? t('modules.withdraw.approveSuccess') : t('modules.withdraw.rejectSuccess');
      ElMessage.success(successMessage);

      // 返回审核结果
      emit('modalCallBack', { event: 'confirm' });
    } else {
      throw new Error(message || t('modules.withdraw.auditFailed'));
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

// 组件挂载时获取支付通道列表
onMounted(() => {
  getChannelList();
});
</script>

<style lang="scss" scoped></style>
