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

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { ElTable, ElForm, ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Search } from '@element-plus/icons-vue';
import {
  currencyCoinPageQuery,
  createCurrencyCoin,
  updateCurrencyCoin,
  deleteCurrencyCoin
} from '@/api/system/currency-coin';
import { CurrencyCoinItem, CurrencyCoinFormData } from '@/types/api/system/currency-coin';

const dataTableRef = ref(ElTable);
const dataFormRef = ref(ElForm);

const state = reactive({
  loading: true,
  ids: [] as number[],
  multiple: true,
  queryParams: { pageNo: 1, pageSize: 15, currency: '' },
  list: [] as CurrencyCoinItem[],
  total: 0,
  isCreate: false,
  dialog: { title: '', visible: false },
  formData: {
    currency: '',
    symbol: '',
    rate: '',
    coinPrecision: 2
  } as CurrencyCoinFormData,
  rules: {
    currency: [{ required: true, message: '请输入法币名称', trigger: 'blur' }],
    symbol: [{ required: true, message: '请输入法币符号', trigger: 'blur' }],
    rate: [{ required: true, message: '请输入汇率', trigger: 'blur' }],
    coinPrecision: [{ required: true, message: '请输入精度', trigger: 'blur' }]
  }
});

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

function handleQuery() {
  state.loading = true;
  currencyCoinPageQuery(state.queryParams).then(({ data }: any) => {
    state.list = data.content || data.data?.content || [];
    state.total = data.totalElements || data.data?.totalElements || 0;
    state.loading = false;
  }).catch(() => { state.loading = false; });
}

function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
  state.multiple = !selection.length;
}

function handleAdd() {
  state.dialog = { title: '新增法币', visible: true };
  state.isCreate = true;
  state.formData = { currency: '', symbol: '', rate: '', coinPrecision: 2 };
}

function handleEdit(row: CurrencyCoinItem) {
  state.dialog = { title: '编辑法币', visible: true };
  state.isCreate = false;
  state.formData = {
    id: row.id,
    currency: row.currency,
    symbol: row.symbol,
    rate: row.rate,
    coinPrecision: row.coinPrecision
  };
}

function submitFormData() {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) return;
    state.loading = true;
    const action = state.isCreate ? createCurrencyCoin : updateCurrencyCoin;
    action(state.formData).then(() => {
      ElMessage.success(state.isCreate ? '新增成功' : '修改成功');
      state.dialog.visible = false;
      handleQuery();
    }).catch(() => { state.loading = false; });
  });
}

function handleDelete() {
  ElMessageBox.confirm(`确认删除选中的 ${state.ids.length} 条记录?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCurrencyCoin(state.ids.join(',')).then(() => {
      ElMessage.success('删除成功');
      handleQuery();
    });
  }).catch(() => ElMessage.info('已取消'));
}

function handleReset() {
  state.queryParams = { pageNo: 1, pageSize: 15, currency: '' };
  handleQuery();
}

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

<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="queryParams">
      <el-form-item label="法币名称">
        <el-input v-model="queryParams.currency" placeholder="如 CNY、USD" clearable style="width:160px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="danger" :icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="dataTableRef"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      border
      highlight-current-row
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="法币名称" prop="currency" width="120" align="center" />
      <el-table-column label="符号" prop="symbol" width="80" align="center" />
      <el-table-column label="USDT汇率" prop="rate" min-width="140" align="center" />
      <el-table-column label="精度" prop="coinPrecision" width="80" align="center" />
      <el-table-column label="创建时间" prop="ctime" min-width="160" align="center" />
      <el-table-column label="更新时间" prop="mtime" min-width="160" align="center" />
      <el-table-column label="操作" align="center" width="100" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
        </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="480px" destroy-on-close>
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="90px">
        <el-form-item label="法币名称" prop="currency">
          <el-input
            v-model="formData.currency"
            placeholder="如 CNY、USD（自动转大写）"
            :disabled="!isCreate"
            style="width:280px"
          />
        </el-form-item>
        <el-form-item label="法币符号" prop="symbol">
          <el-input v-model="formData.symbol" placeholder="如 ¥、$" style="width:280px" />
        </el-form-item>
        <el-form-item label="USDT汇率" prop="rate">
          <el-input-number
            v-model="formData.rate"
            :precision="formData.coinPrecision ?? 2"
            :step="0.01"
            :min="0"
            style="width:280px"
          />
        </el-form-item>
        <el-form-item label="精度" prop="coinPrecision">
          <el-input-number v-model="formData.coinPrecision" :min="0" :max="18" style="width:280px" />
          <span style="margin-left:8px;color:#999;font-size:12px">小数位数</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitFormData">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
