<script lang="ts">
export default {
  name: 'withdrawChainConfig'
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import {
  queryWithdrawChainConfig,
  addWithdrawChainConfig,
  updateWithdrawChainConfig,
  deleteWithdrawChainConfig,
  getAllChainNames,
  getCoinUnitsByChain
} from '@/api/system/withdrawChainConfig';
import {
  WithdrawChainConfigQueryParam,
  WithdrawChainConfigItem,
  WithdrawChainConfigFormData
} from '@/types/api/system/withdrawChainConfig';

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const state = reactive({
  loading: true,
  queryParams: {
    pageNo: 1,
    pageSize: 15
  } as WithdrawChainConfigQueryParam,
  list: [] as WithdrawChainConfigItem[],
  total: 0,
  isCreate: false,
  // 新增/编辑弹窗用的链名称下拉列表
  allChainNames: [] as { id: number; name: string }[],
  // 选中链后联动的币种单位列表
  availableCoinUnits: [] as string[],
  dialog: {
    title: '',
    visible: false,
    loading: false
  },
  formData: {
    coinUnit: '',
    chainName: '',
    rpcUrl: '',
    contractAddress: '',
    payoutAddress: '',
    currency: 3,
    keyType: 0,
    signKey: '',
    derivePath: '',
    testMode: 0,
    enabled: 1,
    remark: ''
  } as WithdrawChainConfigFormData,
  rules: {
    chainName: [{ required: true, message: '请选择链名称', trigger: 'change' }],
    coinUnit: [{ required: true, message: '请选择币种单位', trigger: 'change' }],
    rpcUrl: [{ required: true, message: '请输入 RPC 地址', trigger: 'blur' }],
    signKey: [{ required: true, message: '请输入签名私钥或助记词', trigger: 'blur' }]
  }
});

const {
  loading, queryParams, list, total, dialog, formData, rules,
  allChainNames, availableCoinUnits
} = toRefs(state);

function handleQuery() {
  state.loading = true;
  queryWithdrawChainConfig(state.queryParams).then(({ data }) => {
    state.list = data.content;
    state.total = data.totalElements;
    state.loading = false;
  });
}

/** 加载所有链名称（弹窗打开时调用） */
function fetchChainNames() {
  getAllChainNames().then(({ data }) => {
    state.allChainNames = data || [];
  });
}

/** 选中链后加载对应币种单位 */
function onChainChange(chainName: string | undefined) {
  state.formData.coinUnit = '';
  state.availableCoinUnits = [];
  if (!chainName) {
    return;
  }
  const includeCoinUnit = state.isCreate ? undefined : state.formData.coinUnit || undefined;
  getCoinUnitsByChain(chainName, includeCoinUnit).then(({ data }) => {
    state.availableCoinUnits = data || [];
  });
}

/** 编辑时：链已确定，直接加载该链下币种列表（含当前 coinUnit） */
function loadCoinUnitsForEdit(chainName: string, currentCoinUnit: string) {
  getCoinUnitsByChain(chainName, currentCoinUnit).then(({ data }) => {
    state.availableCoinUnits = data || [];
  });
}

function handleAdd() {
  state.dialog = { title: '新增提现链配置', visible: true, loading: false };
  state.isCreate = true;
  state.availableCoinUnits = [];
  state.formData = {
    coinUnit: '',
    chainName: '',
    rpcUrl: '',
    contractAddress: '',
    payoutAddress: '',
    currency: 3,
    keyType: 0,
    signKey: '',
    derivePath: '',
    testMode: 0,
    enabled: 1,
    remark: ''
  };
  fetchChainNames();

}

function handleEdit(row: WithdrawChainConfigItem) {
  state.dialog = { title: '修改提现链配置', visible: true, loading: false };
  state.isCreate = false;
  state.formData = {
    id: row.id,
    coinUnit: row.coinUnit,
    chainName: row.chainName,
    rpcUrl: row.rpcUrl,
    contractAddress: row.contractAddress || '',
    payoutAddress: row.payoutAddress || '',
    currency: row.currency ?? 3,
    keyType: row.keyType ?? 0,
    signKey: row.signKey || '',
    derivePath: row.derivePath || '',
    testMode: row.testMode ?? 0,
    enabled: row.enabled ?? 1,
    remark: row.remark || ''
  };
  fetchChainNames();
  loadCoinUnitsForEdit(row.chainName, row.coinUnit);
}

function submitFormData() {
  dataFormRef.value.validate((valid: any) => {
    if (!valid) {
      return;
    }
    state.dialog.loading = true;
    const api = state.isCreate ? addWithdrawChainConfig : updateWithdrawChainConfig;
    api(state.formData)
      .then(() => {
        state.dialog.visible = false;
        state.dialog.loading = false;
        ElMessage.success(state.isCreate ? '添加成功' : '修改成功');
        handleQuery();
      })
      .catch(() => {
        state.dialog.loading = false;
      });
  });
}

function handleDelete(row: WithdrawChainConfigItem) {
  ElMessageBox.confirm(
    `确认删除"${row.coinUnit} - ${row.chainName}"配置吗？`,
    '提示',
    { type: 'warning' }
  )
    .then(() => {
      deleteWithdrawChainConfig(row.id).then(() => {
        ElMessage.success('删除成功');
        handleQuery();
      });
    })
    .catch(() => {});
}

function cancel() {
  state.dialog.visible = false;
  state.dialog.loading = false;
}

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

<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增配置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="list" highlight-current-row border height="460">
      <el-table-column label="ID" prop="id" min-width="60" align="center" />
      <el-table-column label="币种单位" prop="coinUnit" min-width="100" align="center" />
      <el-table-column label="链名称" prop="chainName" min-width="100" align="center" />
      <el-table-column label="RPC 地址" prop="rpcUrl" min-width="200" align="center" show-overflow-tooltip />
      <el-table-column label="合约地址" prop="contractAddress" min-width="180" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row.contractAddress">{{ scope.row.contractAddress }}</span>
          <span v-else style="color:#999">-</span>
        </template>
      </el-table-column>
      <el-table-column label="打款地址" prop="payoutAddress" min-width="180" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row.payoutAddress">{{ scope.row.payoutAddress }}</span>
          <span v-else style="color:#999">-</span>
        </template>
      </el-table-column>
      <el-table-column label="密钥类型" prop="keyType" min-width="90" align="center">
        <template #default>
          <el-tag size="small" type="info">私钥</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="enabled" min-width="80" align="center">
        <template #default="scope">
          <el-tag size="small" :type="scope.row.enabled === 1 ? 'success' : 'danger'">
            {{ scope.row.enabled === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" min-width="140" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
          <span v-else style="color:#999">-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="140" fixed="right">
        <template #default="scope">
          <el-link size="default" @click.stop="handleEdit(scope.row)">修改</el-link>
          <el-link size="default" type="danger" style="margin-left:12px" @click.stop="handleDelete(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="580px" destroy-on-close>
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="110px">

        <!-- 第一步：选链 -->
        <el-form-item label="链名称" prop="chainName">
          <el-select
            v-model="formData.chainName"
            placeholder="请先选择链"
            filterable
            allow-create
            clearable
            style="width:100%"
            @change="onChainChange"
          >
            <el-option
              v-for="item in allChainNames"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
          <div style="font-size:12px;color:#999;margin-top:4px">
            可选已有链，也可直接输入新链名称（如 ERC20、TRC20、BEP20）
          </div>
        </el-form-item>

        <!-- 第二步：选币种（依赖链） -->
        <el-form-item label="币种单位" prop="coinUnit">
          <el-select
            v-model="formData.coinUnit"
            :placeholder="formData.chainName ? '请选择币种单位' : '请先选择链'"
            :disabled="!formData.chainName"
            filterable
            allow-create
            clearable
            style="width:100%"
          >
            <el-option
              v-for="unit in availableCoinUnits"
              :key="unit"
              :label="unit"
              :value="unit"
            />
          </el-select>
          <div v-if="formData.chainName && !availableCoinUnits.length" style="font-size:12px;color:#999;margin-top:4px">
            该链下暂无已配置币种，可直接输入新币种单位（如 USDT、ETH）
          </div>
        </el-form-item>

        <el-form-item label="RPC 地址" prop="rpcUrl">
          <el-input v-model="formData.rpcUrl" placeholder="节点 RPC URL" />
        </el-form-item>
        <el-form-item label="合约地址" prop="contractAddress">
          <el-input v-model="formData.contractAddress" placeholder="代币合约地址，原生币可为空" />
        </el-form-item>
        <el-form-item label="打款地址" prop="payoutAddress">
          <el-input v-model="formData.payoutAddress" placeholder="热钱包出款地址" />
        </el-form-item>
        <el-form-item label="货币类型" prop="currency">
          <el-input-number v-model="formData.currency" :min="0" style="width:100%" />
        </el-form-item>
        <el-form-item label="签名私钥" prop="signKey">
          <el-input
            v-model="formData.signKey"
            type="textarea"
            :rows="3"
            placeholder="填入私钥（0x开头）"
          />
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
          <el-switch
            v-model="formData.enabled"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            size="large"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="dialog.loading" @click="submitFormData">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
a { color: #2d8cf0; }
a:hover { color: #0C25F1; }
</style>
