<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-select
                v-model="queryParams.status"
                placeholder="请选择出账状态"
                clearable
              >
                <el-option
                  v-for="item in dictLists"
                  :key="item.itemValue"
                  :label="item.itemLabel"
                  :value="item.itemValue"
                />
              </el-select>
            </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, row.currency) }}
          </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="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>
    <!-- 薪资记录对话框（新建/编辑共用） -->
    <el-dialog
      :title="dialogTitle"
      v-model="salaryDialogVisible"
      width="500px"
    >
      <el-form :model="salaryFormData" :rules="salaryFormRules" ref="salaryFormRef" label-width="100px">
        <el-form-item label="转介人" prop="broker" required>
          <el-select v-model="salaryFormData.broker" 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="出账金额" prop="amount" required>
          <el-input-number
            v-model="salaryFormData.amount"
            :min="0"
            :precision="2"
            placeholder="请输入出账金额"
          />
        </el-form-item>
          <el-form-item label="出账币种" prop="currency" required>
          <el-select v-model="salaryFormData.currency" placeholder="请选择出账币种">
            <el-option
              v-for="item in currencyTypeOptions"
              :key="item.itemValue"
              :label="item.itemLabel"
              :value="item.itemValue"
            />
          </el-select>
        </el-form-item>
                  <el-form-item label="出账状态" prop="status" required>
          <el-select v-model="salaryFormData.status" placeholder="请选择出账状态">
            <el-option
              v-for="item in dictLists"
              :key="item.itemValue"
              :label="item.itemLabel"
              :value="item.itemValue"
            />
          </el-select>
        </el-form-item>
              <el-form-item label="出账日期" prop="fortuneAccountDate" required>
          <el-date-picker
            v-model="salaryFormData.fortuneAccountDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出账日期"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="salaryFormData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="salaryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSalaryForm">确认</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 } 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 billingCompleteDialogVisible = ref(false)


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

// 对话框相关
const salaryDialogVisible = ref(false)
const dialogTitle = ref('新建薪资记录')
const isEditMode = ref(false)
const currentEditId = ref('')

// 薪资表单数据
const salaryFormData = reactive({
  broker: '',
  amount: 0,
  currency: 'HKD',
  status: '',
  fortuneAccountDate: '',
  remark: ''
})

// 表单验证规则
const salaryFormRules = {
  broker: [
    { required: true, message: '请选择转介人', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入出账金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '金额不能为负数', trigger: 'blur' }
  ],
  currency: [
    { required: true, message: '请选择出账币种', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择出账状态', trigger: 'change' }
  ],
  fortuneAccountDate: [
    { required: true, message: '请选择出账日期', trigger: 'change' }
  ]
}

// 表单引用
const salaryFormRef = ref()

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



// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      accountDate:undefined,
      accountDateStart: queryParams.accountDate.length > 0 ? queryParams.accountDate[0] + ' 00:00:00' : undefined,
      accountDateEnd: queryParams.accountDate.length > 0 ? queryParams.accountDate[1] + ' 23:59:59' : undefined,
    }
    const response = await getReferrerFortuneList(params)
    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
}

import { deletePolicyFortune } from '@/api/financial/commission'
// 删除薪资记录
const handleDelete = async (row) => {
  try{
    await ElMessageBox.confirm('确认删除这条薪资记录吗？', '提示', {
      type: 'warning'
    }).then(async () => {
      const res = await deletePolicyFortune({ fortuneAccountBizId: row.fortuneAccountBizId})
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } 
      else {
        ElMessage.error(res.msg)
      }
    })
  }
  catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 完成出账
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 formatCurrency = (amount, currency = '') => {
  const currencyConfig = {
    'CNY': {
      currency: 'CNY',
      locale: 'zh-CN',
      symbol: '¥'
    },
    'HKD': {
      currency: 'HKD',
      locale: 'zh-HK',
      symbol: 'HK$'
    },
    'USD': {
      currency: 'USD',
      locale: 'en-US',
      symbol: '$'
    },
    'EUR': {
      currency: 'EUR',
      locale: 'de-DE',
      symbol: '€'
    },
    'JPY': {
      currency: 'JPY',
      locale: 'ja-JP',
      symbol: '¥'
    },
    'GBP': {
      currency: 'GBP',
      locale: 'en-GB',
      symbol: '£'
    },
    '': {
      currency: '',
      locale: '',
      symbol: ''
    }
  }
  
  const config = currencyConfig[currency] || currencyConfig['']
  
  try {
    return new Intl.NumberFormat(config.locale, {
      style: 'currency',
      currency: config.currency,
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }).format(amount)
  } catch (error) {
    // 如果Intl格式化失败，使用简单格式
    return `${config.symbol}${amount.toFixed(2)}`
  }
}

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

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

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

    } catch (error) {
    }
}



// 新建薪资记录
const handleCreate = () => {
  dialogTitle.value = '新建薪资记录'
  isEditMode.value = false
  currentEditId.value = ''
  
  // 重置表单数据
  Object.assign(salaryFormData, {
    broker: '',
    amount: 0,
    currency: 'HKD',
    fortuneAccountDate: '',
    remark: ''
  })
  
  // 重置表单验证
  if (salaryFormRef.value) {
    salaryFormRef.value.clearValidate()
  }
  
  salaryDialogVisible.value = true
}

// 编辑薪资记录
const handleEdit = (row) => {
  dialogTitle.value = '编辑薪资记录'
  isEditMode.value = true
  currentEditId.value = row.fortuneAccountBizId || ''
  
  // 填充表单数据
  Object.assign(salaryFormData, {
    broker: row.broker || row.broker,
    amount: row.amount || 0,
    currency: row.currency || 'HKD',
   fortuneAccountDate: row.fortuneAccountDate || '',
    remark: row.remark || '',
    status: row.status || ''
  })
  
  // 重置表单验证
  if (salaryFormRef.value) {
    salaryFormRef.value.clearValidate()
  }
  
  salaryDialogVisible.value = true
}
import { addPolicyFortuneAccount } from '@/api/financial/commission'
// 提交薪资表单（新建/编辑共用）
const submitSalaryForm = async () => {
  
  try {
    // 表单验证
    const valid = await salaryFormRef.value.validate()
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }
    
    // 准备提交数据
    const submitData = {
      broker: salaryFormData.broker,
      amount: salaryFormData.amount,
      remark: salaryFormData.remark,
      currency: salaryFormData.currency,
      status: salaryFormData.status,
      fortuneAccountDate: salaryFormData.fortuneAccountDate
    }
    
    if (isEditMode.value && currentEditId.value) {
      // 编辑模式
      submitData.fortuneAccountBizId = currentEditId.value
      // 调用编辑API
      const res = await addPolicyFortuneAccount(submitData)
      if (res.code === 200) {
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error(res.msg)
      }
    } else {
      // 新建模式
       const res = await addPolicyFortuneAccount(submitData)
      if (res.code === 200) {
        ElMessage.success('新建成功')
      } else {
        ElMessage.error(res.msg)
      }
    }
    
    salaryDialogVisible.value = false
    getList()
  } catch (error) {
    if (error.errors) {
      // 表单验证失败
      ElMessage.warning('请完善表单信息')
    } else {
      ElMessage.error(isEditMode.value ? '编辑失败' : '新建失败')
    }
  }
}


</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>