<script lang="ts">
export default {
  name: 'coinNetworkConfig'
};
</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 {
  queryCoinNetworkConfig,
  addCoinNetworkConfig,
  updateCoinNetworkConfig,
  deleteCoinNetworkConfig,
  getAvailableCoinsForNetwork
} from '@/api/system/coinNetworkConfig';
import { getAllCoinNetworks } from '@/api/system/coinNetwork';
import {
  CoinNetworkConfigQueryParam,
  CoinNetworkConfigItem,
  CoinNetworkConfigFormData
} from '@/types/api/system/coinNetworkConfig';
import { CoinNetworkItem } from '@/types/api/system/coinNetwork';

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

const state = reactive({
  loading: true,
  queryParams: {
    pageNo: 1,
    pageSize: 15,
  } as CoinNetworkConfigQueryParam,
  list: [] as CoinNetworkConfigItem[],
  total: 0,
  isCreate: false,
  allNetworks: [] as CoinNetworkItem[],
  availableCoinNames: [] as string[],
  dialog: {
    title: '',
    visible: false,
    loading: false,
  },
  formData: {
    coinName: '',
    networkId: undefined as number | undefined,
    contractAddress: '',
    rechargeAddress: '',
    contractDecimals: 6,
    scale: 2,
    sort: 0,
    memo: ''
  } as CoinNetworkConfigFormData,
  rules: {
    networkId: [{ required: true, message: '请选择主网', trigger: 'change' }],
    coinName: [{ required: true, message: '请选择币种', trigger: 'change' }],
  },
});

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

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

function fetchNetworks() {
  getAllCoinNetworks().then(({ data }) => {
    state.allNetworks = data || [];
  });
}

function loadAvailableCoins(networkId: number) {
  const includeCoinName = state.isCreate ? undefined : state.formData.coinName || undefined;
  getAvailableCoinsForNetwork(networkId, includeCoinName).then(({ data }) => {
    state.availableCoinNames = data || [];
  });
}

function onNetworkChange(networkId: number | undefined) {
  state.formData.coinName = '';
  state.availableCoinNames = [];
  if (networkId) {
    loadAvailableCoins(networkId);
  }
}

function handleAdd() {
  state.dialog = { title: '添加币种主网配置', visible: true, loading: false };
  state.isCreate = true;
  state.formData.coinName = '';
  state.formData.networkId = undefined;
  state.formData.contractAddress = '';
  state.formData.rechargeAddress = '';
  state.formData.contractDecimals = 6;
  state.formData.scale = 2;
  state.formData.sort = 0;
  state.formData.memo = '';
  state.availableCoinNames = [];
}

function handleEdit(row: CoinNetworkConfigItem) {
  state.dialog = { title: '修改币种主网配置', visible: true, loading: false };
  state.isCreate = false;
  state.formData.id = row.id;
  state.formData.coinName = row.coinName;
  state.formData.networkId = row.network.id;
  state.formData.contractAddress = row.contractAddress || '';
  state.formData.rechargeAddress = row.rechargeAddress || '';
  state.formData.contractDecimals = row.contractDecimals ?? 6;
  state.formData.scale = row.scale ?? 2;
  state.formData.sort = row.sort;
  state.formData.memo = row.memo || '';
  loadAvailableCoins(row.network.id);
}

function submitFormData() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      state.dialog.loading = true;
      const payload = { ...state.formData, networkId: state.formData.networkId! };
      if (state.isCreate) {
        addCoinNetworkConfig(payload).then(() => {
          state.dialog.visible = false;
          state.dialog.loading = false;
          ElMessage.success('添加成功');
          handleQuery();
        }).catch(() => { state.dialog.loading = false; });
      } else {
        updateCoinNetworkConfig(payload).then(() => {
          state.dialog.visible = false;
          state.dialog.loading = false;
          ElMessage.success('修改成功');
          handleQuery();
        }).catch(() => { state.dialog.loading = false; });
      }
    }
  });
}

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

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

onMounted(() => {
  handleQuery();
  fetchNetworks();
});
</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="coinName" min-width="120" align="center" />
      <el-table-column label="主网" prop="network.name" min-width="120" align="center" />
      <el-table-column label="合约地址" prop="contractAddress" min-width="180" align="center">
        <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="rechargeAddress" min-width="180" align="center">
        <template #default="scope">
          <span v-if="scope.row.rechargeAddress">{{ scope.row.rechargeAddress }}</span>
          <span v-else style="color:#999">-</span>
        </template>
      </el-table-column>
      <el-table-column label="链上精度" prop="contractDecimals" min-width="90" align="center">
        <template #default="scope">
          <el-tag size="small" type="info">{{ scope.row.contractDecimals ?? 6 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="入账精度" prop="scale" min-width="80" align="center">
        <template #default="scope">
          <el-tag size="small" type="success">{{ scope.row.scale ?? 2 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" min-width="70" align="center" />
      <el-table-column label="备注" prop="memo" min-width="160" align="center" />
      <el-table-column label="操作" align="center" width="160" 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="550px" destroy-on-close>
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="主网" prop="networkId">
          <el-select
            v-model="formData.networkId"
            placeholder="请先选择主网"
            filterable
            clearable
            style="width:100%"
            @change="onNetworkChange"
          >
            <el-option
              v-for="net in allNetworks"
              :key="net.id"
              :label="net.name + (net.protocol ? ' (' + net.protocol + ')' : '')"
              :value="net.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="币种名称" prop="coinName">
          <el-select
            v-model="formData.coinName"
            :placeholder="formData.networkId ? '请选择币种' : '请先选择主网'"
            :disabled="!formData.networkId"
            filterable
            clearable
            style="width:100%"
          >
            <el-option
              v-for="name in availableCoinNames"
              :key="name"
              :label="name"
              :value="name"
            />
          </el-select>
          <div v-if="formData.networkId && !availableCoinNames.length" style="font-size:12px;color:#999;margin-top:4px">
            当前主网下无可配置子币种（需 coin 表 parent_coin_name 不为空且未配置）
          </div>
        </el-form-item>
        <el-form-item label="合约地址" prop="contractAddress">
          <el-input type="text" v-model="formData.contractAddress" placeholder="原生币可为空" />
        </el-form-item>
        <el-form-item label="收款地址" prop="rechargeAddress">
          <el-input type="text" v-model="formData.rechargeAddress" placeholder="用户充值时转入的地址" />
        </el-form-item>
        <el-form-item label="链上精度" prop="contractDecimals">
          <el-input-number v-model="formData.contractDecimals" :min="0" :max="18" style="width:100%" />
          <div style="font-size:12px;color:#999;margin-top:4px">
            链上最小单位换算位数：USDT(ERC20/TRC20/BEP20)=6，ETH/BNB=18，TRX=6
          </div>
        </el-form-item>
        <el-form-item label="入账精度" prop="scale">
          <el-input-number v-model="formData.scale" :min="0" :max="18" style="width:100%" />
          <div style="font-size:12px;color:#999;margin-top:4px">
            写入数据库时保留的小数位数：USDT=2，ETH=8
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" style="width:100%" />
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input type="textarea" v-model="formData.memo" 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>