<template>
  <div class="financial-salary-page">
    <!-- 查询区域 -->
    <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-input
                v-model="queryParams.broker"
                placeholder="请输入转介人"
                clearable
              />
            </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.accountDate"
                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>
          <el-button @click="handleImport">批量导入</el-button>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-button
            type="success"
            :disabled="selectedRows.length === 0"
            @click="completeBilling"
          >
            完成出账
          </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="broker" label="转介人" min-width="120" />
        <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)">
              {{convertStatusToDict(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="300" 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="generateSalarySlip(row)">生成薪资单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNo"
        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="新建薪资记录"
      v-model="createDialogVisible"
      width="500px"
    >
      <el-form :model="createFormData" label-width="100px">
        <el-form-item label="转介人" required>
          <el-select v-model="createFormData.referrer" placeholder="请选择转介人">
            <el-option
              v-for="item in referrerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出账金额" required>
          <el-input-number
            v-model="createFormData.amount"
            :min="0"
            :precision="2"
            placeholder="请输入出账金额"
          />
        </el-form-item>
        <el-form-item label="出账项目" required>
          <el-input
            v-model="createFormData.billingItem"
            placeholder="请输入出账项目"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="createFormData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 出账完成弹窗 -->
    <el-dialog
      title="出账完成"
      v-model="billingCompleteDialogVisible"
      width="400px"
    >
      <div style="text-align: center;">
        <el-icon size="48" color="#67C23A">
          <SuccessFilled />
        </el-icon>
        <p style="margin-top: 16px; font-size: 16px;">出账操作已完成！</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="generateSalarySlips">生成薪资单</el-button>
        <el-button @click="billingCompleteDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { SuccessFilled } from '@element-plus/icons-vue'
import { getReferrerFortuneList,updatePolicyFortuneStatus } from '@/api/financial/commission'

// 查询参数
const queryParams = reactive({
  broker: '',
  accountDate: [],
  accountDateStart: '',
  accountDateEnd: '',
  pageNo: 1,
  pageSize: 10,
  sortField: '',
  sortOrder: 'desc'
})

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

// 对话框相关
const createDialogVisible = ref(false)
const billingCompleteDialogVisible = ref(false)

// 新建表单数据
const createFormData = reactive({
  referrer: '',
  amount: 0,
  billingItem: '',
  remark: ''
})

// 转介人选项
const referrerOptions = [
  { label: '张三', value: 'zhangsan' },
  { label: '李四', value: 'lisi' },
  { label: '王五', value: 'wangwu' },
  { label: '赵六', value: 'zhaoliu' }
]

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



// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    if (queryParams.accountDate.length > 0) {
      queryParams.accountDateStart = queryParams.accountDate[0]
      queryParams.accountDateEnd = queryParams.accountDate[1]
    }
    const response = await getReferrerFortuneList(queryParams)
    tableData.value = response.data.records
    total.value = response.data.total
    loading.value = false
  } catch (error) {
    loading.value = false
    // ElMessage.error('获取数据失败')
  }
}

const getStatusType = (status) => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return types[status] || 'info'
}

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

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    broker: '',
    accountDateStart: '',
    accountDateEnd: '',
    pageNo: 1,
    pageSize: 10,
    sortField: '',
    sortOrder: 'desc'
  })
  getList()
}

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

// 新建薪资记录
const handleCreate = () => {
  Object.assign(createFormData, {
    referrer: '',
    amount: 0,
    billingItem: '',
    remark: ''
  })
  createDialogVisible.value = true
}

// 编辑薪资记录
const handleEdit = (row) => {
  // 这里可以打开编辑对话框
  ElMessage.info(`编辑转介人：${row.referrer}`)
}

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

// 批量导入
const handleImport = () => {
  ElMessage.info('批量导入功能待实现')
}

// 完成出账
const completeBilling = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要出账的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认完成 ${selectedRows.value.length} 条记录的出账操作吗？`,
      '提示',
      { type: 'warning' }
    )
    console.log(selectedRows.value)
    const arr = selectedRows.value.map(item => item.fortuneAccountBizId)
    
    // 调用出账API
   await fetchCompletePolicyFortune(arr)
 
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('出账操作失败')
    }
  }
}

// 生成薪资单（单条）
const generateSalarySlip = (row) => {
  // 调用生成薪资单API
  // await api.generateSalarySlip(row.id)
  ElMessage.success(`已为 ${row.referrer} 生成薪资单`)
}

// 生成薪资单（批量）
const generateSalarySlips = () => {
  // 调用批量生成薪资单API
  // await api.generateSalarySlips(selectedRows.value.map(item => item.id))
  ElMessage.success(`已为 ${selectedRows.value.length} 条记录生成薪资单`)
  billingCompleteDialogVisible.value = false
  selectedRows.value = []
}

// 提交新建表单
const submitCreateForm = async () => {
  try {
    // 表单验证
    if (!createFormData.referrer || !createFormData.amount || !createFormData.billingItem) {
      ElMessage.warning('请填写必填字段')
      return
    }
    
    // 调用保存API
    // await api.createSalary(createFormData)
    
    ElMessage.success('新建成功')
    createDialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('新建失败')
  }
}

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

import { listType } from '@/api/system/dict/type'
const dictLists = ref([])
// 获取出账状态字典值
const getDictLists = () => {
    return new Promise((resolve, reject) => {
        listType({typeList: ['csf_fortune_status']}).then(res => {
            if (res.code === 200 && res.data) {
                const dictData = res.data.find(item => item.dictType === 'csf_fortune_status');
                dictLists.value = dictData?.dictItemList || [];
                console.log('获取到的字典数据:', dictLists.value);
                resolve(dictLists.value);
            } else {
                dictLists.value = [];
                resolve([]);
            }
        }).catch(error => {
            console.error('获取状态列表失败:', error);
            dictLists.value = [];
            reject(error);
        });
    });
}

// 返回数据中状态需要转换为字典值
const convertStatusToDict = (status) => {
    const dictItem = dictLists.value.find(item => item.itemValue == status);
    return dictItem?.itemLabel ?? status;
}

// 更新出账状态
const updateStatus = async (row) => {
    try {
       const res =  await updatePolicyFortuneStatus({
            fortuneBizIdList: row,
            status: 2
        });
        console.log(res)
           if (res.code === 200) {
       // 显示完成弹窗
      billingCompleteDialogVisible.value = true
      getList()
    } else {
      ElMessage.error(res.msg)
    }

    } catch (error) {
    }
}

// 完成出账
import { completePolicyFortune } from '@/api/financial/commission'
const fetchCompletePolicyFortune = async (row) => {
    try {
       const res =  await completePolicyFortune({
            fortuneBizIdList: row
        });
        console.log(res)
           if (res.code === 200) {
       // 显示完成弹窗
      billingCompleteDialogVisible.value = true
      getList()
    } else {
      ElMessage.error(res.msg)
    }

    } catch (error) {
    }
}

</script>

<style scoped>
.financial-salary-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-salary-page {
    padding: 10px;
  }
  
  .search-card {
    margin-bottom: 15px;
  }
  
  .operation-card {
    margin-bottom: 15px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
}
</style>