<template>
  <div class="profit-share-receiver">
    <!-- 搜索条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="订单号" style="width: 300px;">
          <el-input 
            v-model="searchForm.order_no" 
            placeholder="请输入订单号" 
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态" style="width: 250px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%;">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="1" />
            <el-option label="提交中" value="2" />
            <el-option label="验证通过" value="3" />
            <el-option label="验证失败" value="4" />
            <el-option label="绑定中" value="5" />
            <el-option label="绑定成功" value="6" />
            <el-option label="绑定失败" value="7" />
          </el-select>
        </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 prop="order_no" label="订单编号" min-width="180" />
        <el-table-column prop="receiver_name" label="接收方名称" min-width="120" />
        <el-table-column prop="receiver_no" label="接收方编号" min-width="150" />
        <el-table-column prop="acct_name" label="收款账户名称" min-width="120" />
        <el-table-column prop="acct_no" label="收款账户卡号" min-width="180" />
        <el-table-column prop="acct_type_code" label="收款账户账户类型" width="120">
          <template #default="{ row }">
            {{ getAccountTypeText(row.acct_type_code) }}
          </template>
        </el-table-column>
        <el-table-column prop="contact_mobile" label="联系手机号" width="120" />
        <el-table-column prop="status_text" label="状态" width="100" />
        <el-table-column prop="create_time" label="申请时间" width="180" />
        <el-table-column prop="fail_reason" label="失败原因" min-width="150" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">详情</el-button>
          </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
      v-model="detailDialogVisible"
      title="分账接收方详情"
      width="600px"
      :before-close="handleCloseDetailDialog"
    >
      <el-form
        v-loading="detailLoading"
        :model="detailData"
        label-width="140px"
        label-position="left"
      >
        <el-form-item label="订单编号：">
          <span>{{ detailData.order_no }}</span>
        </el-form-item>
        <el-form-item label="分账接收方名称：">
          <span>{{ detailData.receiver_name }}</span>
        </el-form-item>
        <el-form-item label="接收方编号：">
          <span>{{ detailData.receiver_no }}</span>
        </el-form-item>
        <el-form-item label="联系手机号：">
          <span>{{ detailData.contact_mobile }}</span>
        </el-form-item>
        <el-form-item label="收款账户名称：">
          <span>{{ detailData.acct_name }}</span>
        </el-form-item>
        <el-form-item label="收款账户卡号：">
          <span>{{ detailData.acct_no }}</span>
        </el-form-item>
        <el-form-item label="收款账户账户类型：">
          <span>{{ getAccountTypeText(detailData.acct_type_code) }}</span>
        </el-form-item>
        <el-form-item label="收款账户证件类型：">
          <span>{{ getCertificateTypeText(detailData.acct_certificate_type) }}</span>
        </el-form-item>
        <el-form-item label="收款账户证件号：">
          <span>{{ detailData.acct_certificate_no }}</span>
        </el-form-item>
        <el-form-item label="收款账户开户行名称：">
          <span>{{ detailData.acct_open_bank_name }}</span>
        </el-form-item>
        <el-form-item label="提款类型：">
          <span>{{ getSettleTypeText(detailData.settle_type) }}</span>
        </el-form-item>
        <el-form-item label="状态：">
          <span>{{ detailData.status_text }}</span>
        </el-form-item>
        <el-form-item v-if="detailData.fail_reason" label="失败原因：">
          <span>{{ detailData.fail_reason }}</span>
        </el-form-item>
        <el-form-item label="申请时间：">
          <span>{{ detailData.create_time }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button 
            v-if="detailData.status === 1"
            type="success" 
            @click="handleCreateApplication"
            :loading="applyLoading"
          >
            分账接收方创建申请
          </el-button>
          <el-button 
            v-if="detailData.status === 3"
            type="success" 
            @click="handleBindApplication"
            :loading="applyLoading"
          >
            分账关系绑定申请
          </el-button>
          <el-button @click="handleCloseDetailDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ProfitShareReceiver',
  props: {
    axiosInstance: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      detailLoading: false,
      applyLoading: false,
      searchForm: {
        order_no: '',
        status: ''
      },
      tableData: [],
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },
      detailDialogVisible: false,
      detailData: {}
    }
  },
  async created() {
    this.fetchData()
  },
  methods: {
    // 获取账户类型文本
    getAccountTypeText(code) {
      const accountTypes = {
        '57': '对公',
        '58': '对私'
      }
      return accountTypes[code] || code
    },

    // 获取证件类型文本
    getCertificateTypeText(code) {
      const certificateTypes = {
        '17': '身份证',
        '18': '护照',
        '19': '港澳居民来往内地通行证',
        '20': '台湾居民来往内地通行证'
      }
      return certificateTypes[code] || code
    },

    // 获取提款类型文本
    getSettleTypeText(code) {
      const settleTypes = {
        '01': '主动提款',
        '03': '交易自动结算'
      }
      return settleTypes[code] || code
    },
    
    // 获取列表数据
    async fetchData() {
      // 优先使用通过props传递的axios实例
      if (!this.axiosInstance) {
        this.$message.error('无法获取请求实例')
        return
      }
      
      this.loading = true
      try {
        const params = {
          page: this.pagination.page,
          limit: this.pagination.limit,
          order_no: this.searchForm.order_no,
          status: this.searchForm.status
        }
        
        const res = await this.axiosInstance.get('/lakala/profit_share_receiver', { 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
      }
    },

    // 获取详情数据
    async fetchDetail(id) {
      if (!this.axiosInstance) {
        this.$message.error('无法获取请求实例')
        return
      }

      this.detailLoading = true
      try {
        const res = await this.axiosInstance.get(`/lakala/profit_share_receiver/${id}`)
        if (res.code === 200) {
          this.detailData = res.data
        } else {
          this.$message.error(res.msg || res.message || '获取详情失败')
        }
      } catch (error) {
        console.error('获取分账接收方详情失败:', error)
        this.$message.error('获取详情失败: ' + (error.message || '未知错误'))
      } finally {
        this.detailLoading = false
      }
    },
    
    // 查询
    handleSearch() {
      this.pagination.page = 1
      this.fetchData()
    },
    
    // 重置
    handleReset() {
      this.searchForm = {
        order_no: '',
        status: ''
      }
      this.pagination.page = 1
      this.fetchData()
    },
    
    // 查看详情
    async handleView(row) {
      await this.fetchDetail(row.id)
      this.detailDialogVisible = true
    },

    // 关闭详情对话框
    handleCloseDetailDialog() {
      this.detailDialogVisible = false
      this.detailData = {}
    },
    
    // 分账接收方创建申请
    async handleCreateApplication() {
      if (!this.axiosInstance) {
        this.$message.error('无法获取请求实例')
        return
      }

      this.applyLoading = true
      try {
        const res = await this.axiosInstance.put(`/lakala/profit_share_receiver/${this.detailData.id}/apply`)
        if (res.code === 200) {
          this.$message.success('分账接收方创建申请已提交')
          this.handleCloseDetailDialog()
          // 重新加载列表数据以更新状态
          await this.fetchData()
        } else {
          this.$message.error(res.msg || res.message || '申请提交失败')
        }
      } catch (error) {
        console.error('分账接收方创建申请失败:', error)
        this.$message.error('申请提交失败: ' + (error.message || '未知错误'))
      } finally {
        this.applyLoading = false
      }
    },
    
    // 分账关系绑定申请
    async handleBindApplication() {
      if (!this.axiosInstance) {
        this.$message.error('无法获取请求实例')
        return
      }

      this.applyLoading = true
      try {
        const res = await this.axiosInstance.put(`/lakala/profit_share_receiver/${this.detailData.id}/bind`)
        if (res.code === 200) {
          this.$message.success('分账关系绑定申请已提交')
          this.handleCloseDetailDialog()
          // 重新加载列表数据以更新状态
          await this.fetchData()
        } else {
          this.$message.error(res.msg || res.message || '申请提交失败')
        }
      } catch (error) {
        console.error('分账关系绑定申请失败:', error)
        this.$message.error('申请提交失败: ' + (error.message || '未知错误'))
      } finally {
        this.applyLoading = false
      }
    },
    
    // 分页相关
    handleSizeChange(val) {
      this.pagination.limit = val
      this.pagination.page = 1
      this.fetchData()
    },
    
    handleCurrentChange(val) {
      this.pagination.page = val
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.profit-share-receiver {
  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;
}
</style>