<template>
  <div class="financial-billing-page app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="保单号">
              <el-input
                v-model="queryParams.policyNo"
                placeholder="请输入保单号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="对账公司">
              <el-select
                v-model="queryParams.company"
                placeholder="请选择对账公司"
                clearable
              >
                <el-option
                  v-for="item in companyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="出账日期">
              <el-date-picker
                v-model="queryParams.billingDate"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <el-row :gutter="10">
        <el-col :span="12">
          <!-- <el-button type="primary" @click="handleCreate">新建出账记录</el-button> -->
           <FileUpload :fileType="['xlsx', 'xls']" 
            :action="'/csf/api/fortune/upload/excel'"
            :uploadBtnText="'批量导入'"
            @input = 'getUploadFileFunc'
            :responseType="'onlyStatus'"
            
            />
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-button
            type="success"
            :disabled="selectedRows.length === 0"
            @click="generateBillingList"
          >
            生成出账清单
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <el-table
        :data="tableData"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="policyNo" label="保单号" min-width="120" />
        <el-table-column prop="fortunePeriod" label="出账期数" width="100" />
        <el-table-column prop="fortuneTotalPeriod" label="预计总期数" width="100" />
        <el-table-column prop="fortuneName" label="出账项目" min-width="120" />
        <el-table-column prop="broker" label="转介人" min-width="100" />
        <el-table-column prop="team" label="所属团队" min-width="120" />
        <el-table-column prop="amount" label="出账金额" width="120">
          <template #default="{ row }">
            {{ formatCurrency(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="currency" label="出账币种" width="100" />
        <el-table-column prop="status" label="出账状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button size="small" type="info" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="getList"
        @current-change="getList"
      />
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="保单号" required>
          <el-input v-model="formData.policyNo" />
        </el-form-item>
        <el-form-item label="对账公司" required>
          <el-select v-model="formData.company">
            <el-option
              v-for="item in companyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出账期数" required>
          <el-input-number v-model="formData.billingPeriod" :min="1" />
        </el-form-item>
        <el-form-item label="预计总期数" required>
          <el-input-number v-model="formData.totalPeriods" :min="1" />
        </el-form-item>
        <el-form-item label="出账项目" required>
          <el-input v-model="formData.billingItem" />
        </el-form-item>
        <el-form-item label="转介人">
          <el-input v-model="formData.referrer" />
        </el-form-item>
        <el-form-item label="所属团队">
          <el-input v-model="formData.team" />
        </el-form-item>
        <el-form-item label="出账金额" required>
          <el-input-number v-model="formData.amount" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="出账币种" required>
          <el-select v-model="formData.currency">
            <el-option label="人民币" value="CNY" />
            <el-option label="美元" value="USD" />
            <el-option label="港币" value="HKD" />
          </el-select>
        </el-form-item>
        <el-form-item label="出账状态" required>
          <el-select v-model="formData.status">
            <el-option label="待出账" value="pending" />
            <el-option label="已出账" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 引入API
import { getPolicyFortuneList, downloadPolicyFortune ,downloadPolicyFortuneAccount} from "@/api/financial/commission"

// 查询参数
const queryParams = reactive({
  policyNo: '',
  company: '',
  billingDate: [],
  pageNum: 1,
  pageSize: 10
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = reactive({
  policyNo: '',
  company: '',
  billingPeriod: 1,
  totalPeriods: 1,
  billingItem: '',
  referrer: '',
  team: '',
  amount: 0,
  currency: 'CNY',
  status: 'pending',
  remark: ''
})

// 对账公司选项
const companyOptions = [
  { label: '公司A', value: 'company_a' },
  { label: '公司B', value: 'company_b' },
  { label: '公司C', value: 'company_c' }
]
const getUploadFileFunc = (data) => {
  if(data===200){
    ElMessage.success('上传成功');
    getList()
  }else{
    ElMessage.error('上传失败')
  }
}
// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    // API调用
    const response = await getPolicyFortuneList(queryParams)
    tableData.value = response.data.records
    total.value = response.data.total
      loading.value = false
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    policyNo: '',
    company: '',
    billingDate: [],
    pageNum: 1,
    pageSize: 10
  })
  getList()
}

// 选择行变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新建出账记录
const handleCreate = () => {
  dialogTitle.value = '新建出账记录'
  Object.assign(formData, {
    policyNo: '',
    company: '',
    billingPeriod: 1,
    totalPeriods: 1,
    billingItem: '',
    referrer: '',
    team: '',
    amount: 0,
    currency: 'CNY',
    status: 'pending',
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑出账记录
const handleEdit = (row) => {
  dialogTitle.value = '编辑出账记录'
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 删除出账记录
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除这条出账记录吗？', '提示', {
      type: 'warning'
    })
    // await api.deleteBilling(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 查看详情
const handleView = (row) => {
  // 这里可以跳转到详情页面或者打开详情对话框
  ElMessage.info(`查看保单号：${row.policyNo}`)
}



// 生成出账清单
const generateBillingList = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要生成清单的记录')
    return
  }
  
  ElMessageBox.confirm(
    `确认生成 ${selectedRows.value.length} 条记录的出账清单吗？`,
    '提示',
    {
      type: 'warning'
    }
  ).then(() => {
    // 调用生成清单的API
    downloadPolicyFortuneAccount({
      fortuneBizIdList: selectedRows.value.map(item => item.fortuneBizId)
    }).then((response) => {
      // 创建 Blob
        const blob = new Blob([response.data], {
          type: 'application/vnd.ms-excel;charset=utf-8'
        });

        // 检查 Blob 是否有效
        if (!(blob instanceof Blob)) {
          throw new Error('创建的 Blob 对象无效');
        }

        if (blob.size === 0) {
          throw new Error('Blob 大小为 0');
        }

        // 创建下载链接
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        
        // 从响应头获取文件名，或使用默认名
        const fileName = getFileName(response) || 'export.xls';
        link.download = fileName;
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 清理 URL
        setTimeout(() => {
          URL.revokeObjectURL(url);
        }, 100);
    })
    ElMessage.success('出账清单生成成功')
    selectedRows.value = []
  }).catch(() => {})
}
//  getFileName 方法
const getFileName = (response) =>{
  // 安全地访问 headers
  const headers = response.headers || {};
  const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
  
  if (!contentDisposition) {
    console.warn('未找到 Content-Disposition 头');
    return 'export.xls'; // 返回默认文件名
  }
  
  try {
    const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
    if (fileNameMatch && fileNameMatch[1]) {
      let fileName = fileNameMatch[1].replace(/['"]/g, '');
      // 处理 URL 编码
      try {
        fileName = decodeURIComponent(fileName);
      } catch (e) {
        console.warn('文件名解码失败，使用原始文件名');
      }
      return fileName;
    }
  } catch (error) {
    console.error('解析文件名时出错:', error);
  }
  
  return 'export.xls'; // 默认文件名
}
// 提交表单
const submitForm = async () => {
  try {
    // 表单验证
    if (!formData.policyNo || !formData.company || !formData.billingItem) {
      ElMessage.warning('请填写必填字段')
      return
    }
    
    // 调用保存API
    // if (formData.id) {
    //   await api.updateBilling(formData)
    // } else {
    //   await api.createBilling(formData)
    // }
    
    ElMessage.success('保存成功')
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 格式化金额
const formatCurrency = (amount) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(amount)
}

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.financial-billing-page {
  padding: 20px;
}

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

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

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

.el-pagination {
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .financial-billing-page {
    padding: 10px;
  }
  
  .search-card {
    margin-bottom: 15px;
  }
  
  .operation-card {
    margin-bottom: 15px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
}
</style>