<template>
  <div class="trade-page">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <a-page-header title="交易管理" sub-title="交易记录和合同管理">
        <template #extra>
          <a-button type="primary" @click="showAddModal('transaction')">
            <PlusOutlined /> 新增交易
          </a-button>
          <a-button @click="showAddModal('contract')">
            <FileTextOutlined /> 新增合同
          </a-button>
        </template>
      </a-page-header>
    </div>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-cards">
      <a-col :span="6">
        <a-card>
          <a-statistic title="总交易量" :value="stats.totalTransactions" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="有效合同" :value="stats.totalContracts" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic 
            title="交易总金额" 
            :value="stats.totalAmount" 
            suffix="万元" 
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic 
            title="今日交易" 
            :value="stats.todayTransactions" 
          />
        </a-card>
      </a-col>
    </a-row>

    <!-- 标签页 -->
    <a-tabs v-model:activeKey="activeTab" class="trade-tabs">
      <a-tab-pane key="transactions" tab="交易记录">
        <!-- 交易搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="transactionSearchForm">
            <a-form-item label="交易编号">
              <a-input v-model:value="transactionSearchForm.transactionNumber" placeholder="请输入交易编号" />
            </a-form-item>
            <a-form-item label="交易类型">
              <a-select v-model:value="transactionSearchForm.transactionType" placeholder="请选择交易类型" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="cattle_sale">牛只销售</a-select-option>
                <a-select-option value="feed_purchase">饵料采购</a-select-option>
                <a-select-option value="equipment_sale">设备销售</a-select-option>
                <a-select-option value="service">服务</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="交易状态">
              <a-select v-model:value="transactionSearchForm.status" placeholder="请选择状态" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="pending">待处理</a-select-option>
                <a-select-option value="confirmed">已确认</a-select-option>
                <a-select-option value="in_progress">进行中</a-select-option>
                <a-select-option value="completed">已完成</a-select-option>
                <a-select-option value="cancelled">已取消</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchTransactions">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetTransactionSearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 交易列表 -->
        <a-card>
          <a-table 
            :columns="transactionColumns" 
            :data-source="transactions" 
            :loading="transactionLoading"
            :pagination="transactionPagination"
            @change="handleTransactionTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'transaction_type'">
                <a-tag color="blue">
                  {{ getTransactionTypeText(record.transaction_type) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'status'">
                <a-tag :color="getTransactionStatusColor(record.status)">
                  {{ getTransactionStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewTransactionDetail(record)">
                    详情
                  </a-button>
                  <a-button 
                    v-if="record.status === 'pending'" 
                    size="small" 
                    type="primary"
                    @click="confirmTransaction(record)"
                  >
                    确认
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="contracts" tab="合同管理">
        <!-- 合同搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="contractSearchForm">
            <a-form-item label="合同编号">
              <a-input v-model:value="contractSearchForm.contractNumber" placeholder="请输入合同编号" />
            </a-form-item>
            <a-form-item label="合同类型">
              <a-select v-model:value="contractSearchForm.contractType" placeholder="请选择合同类型" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="sale">销售合同</a-select-option>
                <a-select-option value="purchase">采购合同</a-select-option>
                <a-select-option value="service">服务合同</a-select-option>
                <a-select-option value="lease">租赁合同</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="合同状态">
              <a-select v-model:value="contractSearchForm.status" placeholder="请选择状态" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="draft">草稿</a-select-option>
                <a-select-option value="pending">待签署</a-select-option>
                <a-select-option value="signed">已签署</a-select-option>
                <a-select-option value="executing">执行中</a-select-option>
                <a-select-option value="completed">已完成</a-select-option>
                <a-select-option value="terminated">已终止</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchContracts">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetContractSearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 合同列表 -->
        <a-card>
          <a-table 
            :columns="contractColumns" 
            :data-source="contracts" 
            :loading="contractLoading"
            :pagination="contractPagination"
            @change="handleContractTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'contract_type'">
                <a-tag color="green">
                  {{ getContractTypeText(record.contract_type) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'status'">
                <a-tag :color="getContractStatusColor(record.status)">
                  {{ getContractStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewContractDetail(record)">
                    详情
                  </a-button>
                  <a-button 
                    v-if="record.status === 'pending'" 
                    size="small" 
                    type="primary"
                    @click="signContract(record)"
                  >
                    签署
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { tradingAPI } from '@/services/api.js';
import { 
  PlusOutlined, 
  SearchOutlined, 
  FileTextOutlined 
} from '@ant-design/icons-vue';

export default {
  name: 'Trade',
  components: {
    PlusOutlined,
    SearchOutlined,
    FileTextOutlined
  },
  setup() {
    const activeTab = ref('transactions');
    const transactionLoading = ref(false);
    const contractLoading = ref(false);
    
    // 统计数据
    const stats = reactive({
      totalTransactions: 2456,
      totalContracts: 189,
      totalAmount: 8650,
      todayTransactions: 45
    });

    // 交易数据
    const transactions = ref([]);
    const transactionSearchForm = reactive({
      transactionNumber: '',
      transactionType: '',
      status: ''
    });
    const transactionPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 合同数据
    const contracts = ref([]);
    const contractSearchForm = reactive({
      contractNumber: '',
      contractType: '',
      status: ''
    });
    const contractPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 交易表格列
    const transactionColumns = [
      { title: '交易编号', dataIndex: 'transaction_number', key: 'transaction_number', width: 150 },
      { title: '交易类型', dataIndex: 'transaction_type', key: 'transaction_type' },
      { title: '买方', dataIndex: 'buyer_name', key: 'buyer_name' },
      { title: '卖方', dataIndex: 'seller_name', key: 'seller_name' },
      { title: '交易金额(万元)', dataIndex: 'total_amount', key: 'total_amount' },
      { title: '交易状态', dataIndex: 'status', key: 'status' },
      { title: '交易时间', dataIndex: 'created_at', key: 'created_at' },
      { title: '操作', key: 'action', width: 150 }
    ];

    // 合同表格列
    const contractColumns = [
      { title: '合同编号', dataIndex: 'contract_number', key: 'contract_number', width: 150 },
      { title: '合同类型', dataIndex: 'contract_type', key: 'contract_type' },
      { title: '甲方', dataIndex: 'party_a_name', key: 'party_a_name' },
      { title: '乙方', dataIndex: 'party_b_name', key: 'party_b_name' },
      { title: '合同金额(万元)', dataIndex: 'contract_amount', key: 'contract_amount' },
      { title: '合同状态', dataIndex: 'status', key: 'status' },
      { title: '签署时间', dataIndex: 'signed_date', key: 'signed_date' },
      { title: '操作', key: 'action', width: 150 }
    ];

    // 加载交易数据
    const loadTransactions = async () => {
      transactionLoading.value = true;
      try {
        const params = {
          page: transactionPagination.current,
          limit: transactionPagination.pageSize,
          ...transactionSearchForm
        };
        const response = await tradingAPI.getTransactions(params);
        if (response.success) {
          transactions.value = response.data.transactions || [];
          transactionPagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取交易列表失败:', error);
        message.error('获取交易列表失败');
      } finally {
        transactionLoading.value = false;
      }
    };

    // 加载合同数据
    const loadContracts = async () => {
      contractLoading.value = true;
      try {
        const params = {
          page: contractPagination.current,
          limit: contractPagination.pageSize,
          ...contractSearchForm
        };
        const response = await tradingAPI.getContracts(params);
        if (response.success) {
          contracts.value = response.data.contracts || [];
          contractPagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取合同列表失败:', error);
        message.error('获取合同列表失败');
      } finally {
        contractLoading.value = false;
      }
    };

    // 交易类型文本
    const getTransactionTypeText = (type) => {
      const texts = {
        'cattle_sale': '牛只销售',
        'feed_purchase': '饲料采购',
        'equipment_sale': '设备销售',
        'service': '服务'
      };
      return texts[type] || type;
    };

    // 交易状态颜色
    const getTransactionStatusColor = (status) => {
      const colors = {
        'pending': 'orange',
        'confirmed': 'blue',
        'in_progress': 'purple',
        'completed': 'green',
        'cancelled': 'red',
        'refunded': 'red'
      };
      return colors[status] || 'default';
    };

    // 交易状态文本
    const getTransactionStatusText = (status) => {
      const texts = {
        'pending': '待处理',
        'confirmed': '已确认',
        'in_progress': '进行中',
        'completed': '已完成',
        'cancelled': '已取消',
        'refunded': '已退款'
      };
      return texts[status] || status;
    };

    // 合同类型文本
    const getContractTypeText = (type) => {
      const texts = {
        'sale': '销售合同',
        'purchase': '采购合同',
        'service': '服务合同',
        'lease': '租赁合同'
      };
      return texts[type] || type;
    };

    // 合同状态颜色
    const getContractStatusColor = (status) => {
      const colors = {
        'draft': 'default',
        'pending': 'orange',
        'signed': 'blue',
        'executing': 'purple',
        'completed': 'green',
        'terminated': 'red'
      };
      return colors[status] || 'default';
    };

    // 合同状态文本
    const getContractStatusText = (status) => {
      const texts = {
        'draft': '草稿',
        'pending': '待签署',
        'signed': '已签署',
        'executing': '执行中',
        'completed': '已完成',
        'terminated': '已终止'
      };
      return texts[status] || status;
    };

    // 搜索交易
    const searchTransactions = () => {
      transactionPagination.current = 1;
      loadTransactions();
    };

    // 重置交易搜索
    const resetTransactionSearch = () => {
      Object.assign(transactionSearchForm, {
        transactionNumber: '',
        transactionType: '',
        status: ''
      });
      searchTransactions();
    };

    // 搜索合同
    const searchContracts = () => {
      contractPagination.current = 1;
      loadContracts();
    };

    // 重置合同搜索
    const resetContractSearch = () => {
      Object.assign(contractSearchForm, {
        contractNumber: '',
        contractType: '',
        status: ''
      });
      searchContracts();
    };

    // 表格变化处理
    const handleTransactionTableChange = (pagination) => {
      transactionPagination.current = pagination.current;
      transactionPagination.pageSize = pagination.pageSize;
      loadTransactions();
    };

    const handleContractTableChange = (pagination) => {
      contractPagination.current = pagination.current;
      contractPagination.pageSize = pagination.pageSize;
      loadContracts();
    };

    // 显示添加模态框
    const showAddModal = (type) => {
      message.info(`添加${type === 'transaction' ? '交易' : '合同'}功能开发中`);
    };

    // 查看详情
    const viewTransactionDetail = (record) => {
      message.info(`查看交易详情: ${record.transaction_number}`);
    };

    const viewContractDetail = (record) => {
      message.info(`查看合同详情: ${record.contract_number}`);
    };

    // 确认交易
    const confirmTransaction = (record) => {
      message.info(`确认交易: ${record.transaction_number}`);
    };

    // 签署合同
    const signContract = (record) => {
      message.info(`签署合同: ${record.contract_number}`);
    };

    onMounted(() => {
      loadTransactions();
      loadContracts();
    });

    return {
      activeTab,
      stats,
      transactions,
      transactionLoading,
      transactionSearchForm,
      transactionPagination,
      transactionColumns,
      contracts,
      contractLoading,
      contractSearchForm,
      contractPagination,
      contractColumns,
      loadTransactions,
      loadContracts,
      getTransactionTypeText,
      getTransactionStatusColor,
      getTransactionStatusText,
      getContractTypeText,
      getContractStatusColor,
      getContractStatusText,
      searchTransactions,
      resetTransactionSearch,
      searchContracts,
      resetContractSearch,
      handleTransactionTableChange,
      handleContractTableChange,
      showAddModal,
      viewTransactionDetail,
      viewContractDetail,
      confirmTransaction,
      signContract
    };
  }
};
</script>

<style scoped>
.trade-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  margin-bottom: 16px;
  border-radius: 8px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stats-cards .ant-card {
  text-align: center;
}

.trade-tabs {
  background: white;
  padding: 24px;
  border-radius: 8px;
}

.search-card {
  margin-bottom: 16px;
}

.search-card .ant-form {
  margin-bottom: 0;
}
</style>