<template>
  <div class="collection-config" v-loading="loading">
    <el-table height="100%" class="sa-table" :data="tableData" stripe>
      <template #empty>
        <sa-empty />
      </template>

      <el-table-column :label="t('modules.payment.collectionMethod')" min-width="150" align="center">
        <template #default="scope">
          <div class="method-cell">
            <div class="method-name">{{ scope.row.methodName }}</div>
            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
              @change="handleMethodStatusChange(scope.row)" />
            <div>
              <el-button type="text" size="small" @click="openPaymentLimitModal(scope.row)">
                {{ t('modules.payment.paymentLimit') }}
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column :label="t('modules.payment.collectionChannel')" min-width="200" align="center">
        <template #default="scope">
          <div class="channel-list">
            <div v-for="channel in scope.row.midChannelMethodBOList" :key="channel.id" class="channel-item">
              {{ channel.paymentChannel.channelName }}
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column :label="t('modules.payment.weight')" min-width="200" align="center">
        <template #default="scope">
          <div class="weight-list">
            <div v-for="channel in scope.row.midChannelMethodBOList" :key="channel.id" class="weight-item">
              <el-input v-model="channel.weight" type="number" :min="0" size="small" style="width: 80px" />
              <span class="weight-percent ml-10px">
                {{ calculateWeightPercent(scope.row, channel.weight) }}%
              </span>
              <el-button size="small" type="primary" @click="handleWeightSave(scope.row, channel)"
                style="margin-left: 8px">
                {{ t('common.save') }}
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column :label="t('modules.payment.channelStatus')" min-width="150" align="center">
        <template #default="scope">
          <div class="status-list">
            <div v-for="channel in scope.row.midChannelMethodBOList" :key="channel.id" class="status-item">
              <el-switch v-model="channel.status" :active-value="1" :inactive-value="0"
                @change="handleChannelStatusChange(channel)" />
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useModal } from '@/sheep/hooks';
import api from '../../../api';
import PaymentLimitModal from './PaymentLimitModal.vue';

const { t } = useI18n();

const loading = ref(false);
const tableData = ref([]);

// 获取代收配置数据
async function getData() {
  loading.value = true;
  try {
    const { code, data } = await api.payment.method.list({
      agencyService: 1, // 代收
    });

    if (code == 200) {
      tableData.value = data || [];
    }
  } catch (error) {
    console.error('获取代收配置失败:', error);
    ElMessage.error(t('message.fetchDataFailed'));
  } finally {
    loading.value = false;
  }
}

// 计算权重百分比
function calculateWeightPercent(method, currentWeight) {
  const totalWeight = method.midChannelMethodBOList.reduce((sum, channel) => {
    return sum + (parseInt(channel.weight) || 0);
  }, 0);

  if (totalWeight === 0) return 0;
  return (((parseInt(currentWeight) || 0) / totalWeight) * 100).toFixed(1);
}

// 处理支付方式状态变更
async function handleMethodStatusChange(method) {
  try {
    const { code } = await api.payment.method.update({
      id: method.id,
      status: method.status,
    });

    if (code == 200) {
      ElMessage.success(t('modules.payment.statusUpdateSuccess'));
    }
  } catch (error) {
    console.error('更新支付方式状态失败:', error);
    ElMessage.error(t('modules.payment.statusUpdateFailed'));
    // 回滚状态
    method.status = method.status === 1 ? 0 : 1;
  }
}

// 处理通道状态变更
async function handleChannelStatusChange(channel) {
  try {
    const { code } = await api.payment.method.midUpdate({
      id: channel.id,
      status: channel.status,
    });

    if (code == 200) {
      ElMessage.success(t('modules.payment.channelStatusUpdateSuccess'));
    }
  } catch (error) {
    console.error('更新通道状态失败:', error);
    ElMessage.error(t('modules.payment.channelStatusUpdateFailed'));
    // 回滚状态
    channel.status = channel.status === 1 ? 0 : 1;
  }
}

// 处理权重保存
async function handleWeightSave(method, channel) {
  try {
    const { code } = await api.payment.method.midUpdate({
      id: channel.id,
      weight: parseInt(channel.weight) || 0,
    });

    if (code == 200) {
      ElMessage.success(t('modules.payment.weightSaveSuccess'));
      // 重新获取数据以更新百分比显示
      getData();
    }
  } catch (error) {
    console.error('保存权重失败:', error);
    ElMessage.error(t('modules.payment.weightSaveFailed'));
    // 重新获取数据以恢复原始值
    getData();
  }
}

// 暴露方法给父组件调用
defineExpose({
  getData,
});

// 打开支付限额配置弹窗
function openPaymentLimitModal(paymentMethod) {
  useModal(
    PaymentLimitModal,
    {
      title: t('modules.payment.paymentLimitConfig'),
      paymentId: paymentMethod.id,
      paymentName: paymentMethod.methodName,
    },
    {
      confirm: () => {
        // 配置成功后可以选择是否刷新数据
        // getData();
      },
    },
  );
}

onMounted(() => {
  getData();
});
</script>

<style lang="scss" scoped>
.collection-config {
  height: 100%;

  .method-cell {
    align-items: center;
    gap: 12px;

    .method-name {
      font-weight: 500;
    }
  }

  .channel-list,
  .weight-list,
  .status-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0;
    padding: 8px;
  }

  .channel-item,
  .weight-item,
  .status-item {
    display: flex;
    align-items: center;
    min-height: 60px;
    padding: 8px 12px;
    width: 100%;
    justify-content: center;

    &:not(:last-child) {
      border-bottom: 1px solid var(--el-border-color-light);
      margin-bottom: 8px;
      padding-bottom: 12px;
    }
  }

  .weight-item {
    gap: 8px;
    flex-wrap: wrap;
    justify-content: center;

    .weight-percent {
      color: var(--el-color-primary);
      font-weight: 500;
      min-width: 50px;
    }
  }
}
</style>
