<template>
  <div class="trade-order">
    <!-- 搜索条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="140px" inline>
        <el-form-item>
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="请输入订单编号/交易号等" 
            clearable
            @keyup.enter="handleSearch"
            style="width: 400px;"
          >
            <template #prepend>
              <el-select v-model="searchForm.searchType" placeholder="请选择" style="width: 130px;">
                <el-option label="订单编号" value="order_sn"></el-option>
                <el-option label="商户支付订单号" value="out_trade_no"></el-option>
                <el-option label="拉卡拉交易号" value="transaction_id"></el-option>
                <el-option label="微信交易号" value="wechat_transaction_id"></el-option>
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表数据 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <div class="header-title">拉卡拉交易记录列表</div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="订单与交易编号" min-width="300">
          <template #default="{ row }">
            <div class="order-numbers">
              <div class="number-item">
                <span class="label">订单编号：</span>
                <span class="value">{{ row.order_sn || '-' }}</span>
              </div>
              <div class="number-item">
                <span class="label">商户支付订单号：</span>
                <span class="value">{{ row.out_trade_no || '-' }}</span>
              </div>
              <div class="number-item">
                <span class="label">拉卡拉交易号：</span>
                <span class="value">{{ row.transaction_id || '-' }}</span>
              </div>
              <div class="number-item">
                <span class="label">微信交易号：</span>
                <span class="value">{{ row.wechat_transaction_id || '-' }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="支付金额(元)" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-highlight">¥{{ formatAmount(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="order_state_text" label="状态" width="100" />
        <el-table-column label="支付时间" width="150">
          <template #default="{ row }">
            <div>{{ formatPaymentTime(row.payment_time) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="update_time" width="150" />
        <el-table-column label="快递信息" min-width="250">
          <template #default="{ row }">
            <div class="express-info">
              <div>快递公司：{{ row.express_name || '-' }}</div>
              <div>快递单号：{{ row.express_number || '-' }}</div>
              <div>快递公司编号: {{ row.express_company || '-' }}</div>
              <div v-if="!row.express_company && row.express_company_name" class="correct-button">
                <el-button type="primary" size="small" @click="handleCorrectExpress(row)">纠正</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="收货人信息" min-width="250">
          <template #default="{ row }">
            <div class="consignee-info">
              <div>收货人：{{ row.consignee || '-' }}</div>
              <div>联系电话：{{ row.mobile || '-' }}</div>
              <div class="address-line">收货地址：{{ (row.province || '') + (row.city || '') + (row.district || '') + (row.address || '') }}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>
    
    <!-- 快递公司选择弹窗 -->
    <el-dialog
      title="选择快递公司"
      v-model="dialogVisible"
      width="500px"
    >
      <el-select 
        v-model="selectedExpress" 
        placeholder="请选择快递公司" 
        style="width: 100%"
        filterable
      >
        <el-option
          v-for="item in expressList"
          :key="item.delivery_id"
          :label="item.delivery_name"
          :value="item.delivery_id"
        />
      </el-select>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCorrect">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "TradeOrder",
  props: {
    axiosInstance: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      searchForm: {
        searchType: 'order_sn',
        keyword: ''
      },
      statusOptions: [
        { label: '待支付', value: 0 },
        { label: '支付中', value: 1 },
        { label: '成功', value: 2 },
        { label: '失败', value: 3 },
        { label: '已关闭', value: 4 },
        { label: '退款中', value: 5 }
      ],
      bizTypeOptions: [
        { label: '商品订单支付', value: 1 }
      ],
      tableData: [],
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },
      dialogVisible: false,
      expressList: [], // 快递公司列表
      currentRow: null, // 当前操作行
      selectedExpress: '' // 选中的快递公司
    }
  },
  async created() {
    this.fetchData()
  },
  methods: {
    // 格式化金额显示
    formatAmount(amount) {
      return amount || amount === 0 ? amount : '-';
    },
    
    // 格式化支付时间显示
    formatPaymentTime(timestamp) {
      if (!timestamp) return '-';
      const date = new Date(timestamp * 1000);
      return date.getFullYear() + '-' + 
             String(date.getMonth() + 1).padStart(2, '0') + '-' + 
             String(date.getDate()).padStart(2, '0') + ' ' + 
             String(date.getHours()).padStart(2, '0') + ':' + 
             String(date.getMinutes()).padStart(2, '0') + ':' + 
             String(date.getSeconds()).padStart(2, '0');
    },

    // 获取业务类型文本
    getBizTypeText(bizType) {
      const bizTypeMap = {
        1: '商品订单支付'
      };
      return bizTypeMap[bizType] || bizType;
    },

    // 获取列表数据
    async fetchData() {
      if (!this.axiosInstance) {
        this.$message.error('无法获取请求实例')
        return
      }
      
      this.loading = true
      try {
        const params = {
          page: this.pagination.page,
          limit: this.pagination.limit
        }
        
        // 添加搜索参数
        if (this.searchForm.keyword) {
          params[this.searchForm.searchType] = this.searchForm.keyword
        }
        
        const res = await this.axiosInstance.get('/lakala/trade_order', { params })
        if (res.code === 200) {
          this.tableData = res.page.data
          this.pagination.total = res.page.total
          this.pagination.limit = res.page.per_page
        } else {
          this.$message.error(res.msg || res.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取交易记录列表失败:', error)
        this.$message.error('获取数据失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },

    // 查询
    handleSearch() {
      this.pagination.page = 1
      this.fetchData()
    },
    
    // 重置
    handleReset() {
      this.searchForm = {
        searchType: 'order_sn',
        keyword: ''
      }
      this.pagination.page = 1
      this.fetchData()
    },
    
    // 分页相关
    handleSizeChange(val) {
      this.pagination.limit = val
      this.pagination.page = 1
      this.fetchData()
    },
    
    handleCurrentChange(val) {
      this.pagination.page = val
      this.fetchData()
    },

    // 纠正快递公司信息
    async handleCorrectExpress(row) {
      this.currentRow = row;
      // 获取快递公司列表
      try {
        const res = await this.axiosInstance.get('/wechat/delivery');
        if (res.code === 200) {
          this.expressList = res.page.data;
          this.dialogVisible = true;
        } else {
          this.$message.error(res.msg || '获取快递公司列表失败');
        }
      } catch (error) {
        console.error('获取快递公司列表失败:', error);
        this.$message.error('获取快递公司列表失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 确认纠正快递公司
    async confirmCorrect() {
      if (!this.selectedExpress) {
        this.$message.warning('请选择快递公司');
        return;
      }
      
      try {
        const params = {
          express_company: this.selectedExpress
        };
        
        const res = await this.axiosInstance.put(`/lakala/trade_order/${this.currentRow.wechat_payment_id}/express_company`, params);
        if (res.code === 200) {
          this.$message.success('纠正成功');
          this.dialogVisible = false;
          this.selectedExpress = '';
          // 重新获取数据
          this.fetchData();
        } else {
          this.$message.error(res.msg || '纠正失败');
        }
      } catch (error) {
        console.error('纠正快递公司失败:', error);
        this.$message.error('纠正失败: ' + (error.message || '未知错误'));
      }
    }
  }
}
</script>

<style scoped>
.trade-order {
  padding: 20px;
}

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

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 16px;
  font-weight: bold;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 支付金额高亮显示 */
.amount-highlight {
  font-size: 16px;
  font-weight: 600;
  color: #e65a00;
}

/* 快递信息样式 */
.express-info div {
  margin-bottom: 4px;
  font-size: 13px;
}

.express-info div:last-child {
  margin-bottom: 0;
}

/* 收货人信息样式 */
.consignee-info div {
  margin-bottom: 4px;
  font-size: 13px;
}

.consignee-info div:last-child {
  margin-bottom: 0;
}

.address-line {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.correct-button {
  margin-top: 8px;
}

.order-numbers {
  font-size: 12px;
}

.number-item {
  margin-bottom: 4px;
  display: flex;
}

.number-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 500;
  color: #606266;
  min-width: 90px;
  flex-shrink: 0;
  text-align: right;
}

.value {
  color: #303133;
  word-break: break-all;
  margin-left: 8px;
}
</style>