<script setup>
import { ref, reactive, onMounted, toRefs, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/util/http.js'
import dayjs from 'dayjs'
import { useI18n } from 'vue-i18n'
import { refundOnline,performanceSelect,exportPerformance,adjustment } from '@/api/cash/financialAccount.js'
import { getUserInfo } from '@/api/common/common.js'
import { useAdminStore } from '@/store/index.js'
import { permissionMapping, hasMenuPermission } from "@/utils/menuTreePermission.js"
import { storeToRefs } from 'pinia'

const adminStore = useAdminStore()
const {  menuTree,flag } = storeToRefs(adminStore)
const adminData = ref({})


const { t } = useI18n()

const paytypeList = [
    t('cash.payMethods.stripe'),
    t('cash.payMethods.paymentAsia'),
    t('cash.payMethods.ipay88'),
    t('cash.payMethods.bankTransfer'),
    t('cash.payMethods.card'),
    t('cash.payMethods.cash'),
    t('cash.payMethods.check'),
    t('cash.payMethods.grabpay'),
    t('cash.payMethods.nets'),
    t('cash.payMethods.transfer'),
    t('cash.payMethods.iotPay'),
    t('cash.payMethods.stripe3'),
    t('cash.payMethods.paypal'),
]

const hasperformanceAdjustment = ref(false)
// 初始化权限状态
const initPermissions = async () => {
  if (!menuTree.value || !menuTree.value.length) return;
  // 业绩调整
  hasperformanceAdjustment.value = hasMenuPermission(menuTree.value, permissionMapping.performance_adjustment);
  console.log('业绩调整权限',hasperformanceAdjustment.value);
  
};

const payPlatformOptions = ref([...paytypeList])

const statusOptions = [
  { label: t('cash.statusList.received'), value: 4 },
  { label: t('cash.statusList.refunded'), value: 6 }
]

// 地区树
const marketOptions = ref([])

// 查询参数
const queryParams = reactive({
  jwcode: '',
  adminMarket: [], // 下拉多选
  timeRange: [], // [startTime, endTime]
  customerMarket: [], // 客户地区
  pageNum: 1,
  pageSize: 20
})

const total = ref(0)
const tableData = ref([])
const tableRef = ref(null)
const scrollTableTop = () => {
  tableRef.value?.setScrollTop?.(0)
}
const loading = ref(false)

// 转换树形结构（参考 coinConsumeDetail.vue）
const transformTree = (nodes) => {
  const allChildren = nodes.flatMap(node => node.children || []);
  return allChildren.map(child => {
    const grandchildren = child.children && child.children.length
      ? transformTree([child])
      : null;
    return {
      value: child.id,
      label: child.name,
      children: grandchildren
    };
  });
};

// 获取地区数据
const getMarket = async () => {
  try {
    const result = await request({ url: '/market/selectMarket' });
    if (result && result.data) {
      marketOptions.value = transformTree(result.data)
      console.log('地区树:', marketOptions.value)
    }
  } catch (error) {
    console.error('获取地区失败', error)
  }
}

// 查询列表
const fetchData = async () => {
  loading.value = true
  try {
    // 构建请求参数
    console.log('adminData.value.markets:', adminData.value.markets)
    const params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      performanceDTO:{
        jwcode: queryParams.jwcode,
        adminMarket: adminData.value.marketName.split(',').filter(item => item.trim() !== '') || [],
        customerMarket: queryParams.customerMarket,
        startTime: queryParams.timeRange?.[0] ? dayjs(queryParams.timeRange[0]).format('YYYY-MM-DD HH:mm:ss') : '',
        endTime: queryParams.timeRange?.[1] ? dayjs(queryParams.timeRange[1]).format('YYYY-MM-DD HH:mm:ss') : '',
      }
    }
    
    console.log('查询参数:', params)
    const res = await performanceSelect(params)
    if (res.code == 200) {
      tableData.value = res.data.list || []
      await nextTick()
      scrollTableTop()
      total.value = res.data.total || 0
      loading.value = false
    } else {
      ElMessage.error(res.msg || t('elmessage.getDataFailed'))
      loading.value = false
    }   
  } catch (error) {
    console.error(error)
    loading.value = false
    ElMessage.error(t('elmessage.getDataFailed'))
  }
}

const handleAdminInfo = async () => {
  try {
    const res = await getUserInfo()
      adminData.value = res || {}
      console.log('adminData.value:', adminData.value);
      
  } catch (error) {
    console.error(error)
    ElMessage.error(t('elmessage.getDataFailed'))
  }
}

const handleSearch = () => {
  queryParams.pageNum = 1
  fetchData()
}

const handleReset = () => {
  queryParams.jwcode = ''
  queryParams.adminMarket = []
  queryParams.timeRange = null
  queryParams.customerMarket = []
  handleSearch()
}

const handlePageSizeChange = (val) => {
  queryParams.pageSize = val
  fetchData()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}


// 退款操作
const handleRefund = (row) => {
  ElMessageBox.confirm(t('elmessage.refundConfirmContent', { orderNo: row.systemTradeNo }), t('elmessage.refundConfirmTitle'), {
    confirmButtonText: t('common.confirm'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(() => {
    ElMessage.success(t('elmessage.refundSubmitSuccess'))
    // 刷新列表
    fetchData()
  }).catch(() => {})
}

// ==================== 导出相关逻辑 ====================

const exportListVisible = ref(false)
const exportList = ref([])
const exportListLoading = ref(false)

// 导出Excel
const   handleExport = async () => {
  try {
  const params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      performanceDTO:{
        jwcode: queryParams.jwcode,
        adminMarket: adminData.value.marketName.split(',').filter(item => item.trim() !== '') || [],
        customerMarket: queryParams.customerMarket,
        startTime: queryParams.timeRange?.[0] ? dayjs(queryParams.timeRange[0]).format('YYYY-MM-DD HH:mm:ss') : '',
        endTime: queryParams.timeRange?.[1] ? dayjs(queryParams.timeRange[1]).format('YYYY-MM-DD HH:mm:ss') : '',
      }
    }
    
    // TODO: 确认导出接口 URL
    const res = await exportPerformance(params)
    if(res.code == 200){

        console.log('导出参数', params)
        ElMessage.success(t('elmessage.exportSuccess'))
    }                     
    
  } catch (error) {
    console.error(error)
    ElMessage.error(t('elmessage.exportError'))
  }
}

// 打开导出列表弹窗
const openExportList = () => {
  getExportList()
  exportListVisible.value = true
}

// 获取导出列表
const getExportList = async () => {
  exportListLoading.value = true
  try {
    const result = await request({ url: '/export/export' })
    if (result.code === 200) {
      const filteredData = result.data.filter(item => item.type == 14);
      exportList.value = filteredData || []
    } else {
      ElMessage.error(result.msg || t('elmessage.getExportListError'))
    }
  } catch (error) {
    console.error('获取导出列表出错:', error)
    ElMessage.error(t('elmessage.getExportListError'))
  } finally {
    exportListLoading.value = false
  }
}

// 下载导出文件
const downloadExportFile = (item) => {
  if (item.state === 2) {
    const link = document.createElement('a')
    link.href = item.url
    link.download = item.fileName
    link.click()
  } else {
    ElMessage.warning(t('elmessage.exportingInProgress'))
  }
}

// 根据状态返回对应的标签类型
const getTagType = (state) => {
  switch (state) {
    case 0: return 'info';
    case 1: return 'primary';
    case 2: return 'success';
    case 3: return 'danger';
    default: return 'info';
  }
}

// 根据状态返回对应的标签文案
const getTagText = (state) => {
  switch (state) {
    case 0: return t('elmessage.pendingExecution');
    case 1: return t('elmessage.executing');
    case 2: return t('elmessage.executed');
    case 3: return t('elmessage.errorExecution');
    default: return t('elmessage.unknownStatus');
  }
}

// ==================== 业绩调整弹窗相关逻辑 ====================
const adjustVisible = ref(false)
const adjustTime = ref('')
const adjustCoefficient = ref('')

const matrixMarkets = [
  { key: 'sg', label: '新加坡' },
  { key: 'my', label: '马来西亚' },
  { key: 'hk', label: '香港' },
  { key: 'th', label: '泰国' },
  { key: 'vn', label: '越南' },
  { key: 'ca', label: '加拿大' }
]

const adjustData = ref([])

const initAdjustData = () => {
  adjustData.value = matrixMarkets.map(rowMarket => {
    const row = { inMarket: rowMarket.label + '客户' }
    matrixMarkets.forEach(colMarket => {
      row[colMarket.key] = '' // 默认空
    })
    return row
  })
}

const handleAdjustment = () => {
  adjustTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
  adjustCoefficient.value = ''
  initAdjustData()
  adjustVisible.value = true
}

const computedAdjustData = computed(() => {
  const data = [...adjustData.value]
  const sumRow = { inMarket: '合计', isSum: true }
  
  matrixMarkets.forEach(colMarket => {
    let colSum = 0
    adjustData.value.forEach(row => {
      const val = parseFloat(row[colMarket.key])
      if (!isNaN(val)) colSum += val
    })
    sumRow[colMarket.key] = colSum
  })
  
  data.push(sumRow)
  return data
})

const getRowTotal = (row) => {
  let sum = 0
  matrixMarkets.forEach(colMarket => {
    const val = parseFloat(row[colMarket.key])
    if (!isNaN(val)) sum += val
  })
  return sum
}

const formatNumber = (val) => {
  if (val === '' || val === '-' || val === undefined || val === null) return val;
  val = String(val);
  let formatted = val.replace(/[^\d.-]/g, ''); // 移除非数字、点和负号
  formatted = formatted.replace(/(?!^)-/g, ''); // 负号只能在开头
  formatted = formatted.replace(/(\..*?)\..*/g, '$1'); // 只能有一个点
  return formatted;
}

const submitAdjustment = async () => {
  if (!adjustTime.value) {
    ElMessage.warning('请选择时间')
    return
  }
  if (!adjustCoefficient.value) {
    ElMessage.warning('请输入系数')
    return
  }
  
  // 组装矩阵数据 matrix (二维数组，6行6列)
  // 如果单元格为空或者非数字，默认为 0
  const matrix = adjustData.value.map(row => {
    return matrixMarkets.map(colMarket => {
      const val = parseFloat(row[colMarket.key])
      return isNaN(val) ? 0 : val
    })
  })

  // 构造最终提交的数据结构
  const payload = {
    matrix: matrix,
    weight: parseFloat(adjustCoefficient.value), // 系数
    createTime: adjustTime.value,
    submitterId: adminData.value.id || 1000063, // 从全局 adminData 获取
    submitterMarket: adminData.value.marketName || '总部' // 如果为空默认传总部
  }

  console.log('提交的封装数据:', JSON.stringify(payload, null, 2))
  
  await adjustment(payload)
  ElMessage.success('提交成功')
  adjustVisible.value = false
  fetchData()
}

onMounted( async() => {
  await initPermissions()
   await handleAdminInfo()
  getMarket()
  await fetchData()
})
</script>

<template>
  <div class="cash-flow-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-bar">
        <!-- 第一行 -->
        <div class="search-row">
          <div class="search-item">
            <span class="label">{{ t('common.jwcode') }}：</span>
            <el-input v-model="queryParams.jwcode" :placeholder="t('common.jwcodePlaceholder')" clearable />
          </div>
          <div class="search-item">
            <span class="label">{{ t('common.market') }}：</span>
            <!-- 下拉多选，使用 el-cascader 匹配地区树结构 -->
            <el-cascader
              v-model="queryParams.customerMarket"
              :options="marketOptions"
              :props="{ multiple: true, emitPath: false }"
              collapse-tags
              collapse-tags-tooltip
              :placeholder="t('common.marketPlaceholder')"
              clearable
              style="width: 8vw;"
            />
          </div>
          
         <div class="search-item" style="width: auto;">
            <span class="label">{{ t('common.payTime2') }}：</span>
            <el-date-picker
              v-model="queryParams.timeRange"
              type="datetimerange"
              :range-separator="t('common.to')"
              :start-placeholder="t('common.startTime')"
              :end-placeholder="t('common.endTime')"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              style="width: 18vw;"
            />
          </div>
        </div>

         <div class="search-row">
          <el-button type="primary" @click="handleSearch">{{ t('common.search') }}</el-button>
            <el-button type="primary" @click="handleExport">{{ t('common.exportExcel') }}</el-button>
            <el-button type="primary" @click="openExportList">{{ t('common.viewExportList') }}</el-button>
            <el-button type="success" @click="handleReset">{{ t('common.reset') }}</el-button>
            <button v-if="hasperformanceAdjustment" class="adjust-btn" @click="handleAdjustment">业绩调整</button>
        </div>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table ref="tableRef" :data="tableData" v-loading="loading" style="width: 100%; flex: 1;" :cell-style="{ textAlign: 'center' }"  :header-cell-style="{ background: '#F3FAFE', color: '#333',textAlign: 'center' }">
        <el-table-column type="index" :label="t('common_list.id')" min-width="60" align="center" fixed="left" >
          <template #default="scope">
            <span>{{ scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="jwcode" :label="t('common_list.jwcode')" min-width="120" fixed="left" />
        <el-table-column prop="name" :label="t('common_list.name')" min-width="150" show-overflow-tooltip />
        <el-table-column prop="marketName" :label="t('common_list.market')" min-width="120" show-overflow-tooltip />
        <el-table-column prop="orderCode" :label="t('common_list.orderCode')" min-width="280" show-overflow-tooltip />
        
        <el-table-column prop="paymentAmount" :label="t('common_list.payAmount')" min-width="150" align="right">
          <!-- <template #default="{ row }">
            {{ row.paymentAmount }} {{ row.paymentCurrency }}
          </template> -->
        </el-table-column>
        <el-table-column prop="paymentCurrency" :label="t('common_list.payCurrency')" min-width="180" show-overflow-tooltip />
        
        <el-table-column prop="receivedAmount" :label="t('common_list.receiveAmount')" min-width="150" align="right">
          <!-- <template #default="{ row }">
            {{ row.receivedAmount }} {{ row.receivedCurrency }}
          </template> -->
        </el-table-column>
        <el-table-column prop="receivedCurrency" :label="t('common_list.receiveCurrency')" min-width="180" show-overflow-tooltip />
        
        <el-table-column prop="handlingCharge" :label="t('common_list.fee')" min-width="100" align="right" />
      </el-table>

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

    <!-- 导出列表弹窗 -->
    <el-dialog v-model="exportListVisible" :title="t('common_export.exportList')" width="80%">
      <el-table :data="exportList" style="width: 100% ;height: 60vh;" :loading="exportListLoading">
        <el-table-column prop="fileName" :label="t('common_export.fileName')" />
        <el-table-column prop="state" :label="t('common_export.status')">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.state)" :effect="scope.row.state === 3 ? 'light' : 'plain'">
              {{ getTagText(scope.row.state) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="t('common_export.createTime')">
          <template #default="scope">
            {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column :label="t('common_export.operation')">
          <template #default="scope">
            <el-button type="primary" size="small" @click="downloadExportFile(scope.row)"
              :disabled="scope.row.state !== 2">
              {{ t('common_export.download') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button text @click="exportListVisible = false">{{ t('common_export.close') }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 业绩调整弹窗 -->
    <el-dialog v-model="adjustVisible" title="市场消耗金币业绩调整" width="80%" top="5vh" align-center class="custom-adjust-dialog">
      <template #header="{ titleId, titleClass }">
        <div style="text-align: center; font-weight: bold; font-size: 18px;" :id="titleId" :class="titleClass">市场消耗金币业绩调整</div>
      </template>
      <div style="display: flex; gap: 40px; margin-bottom: 20px; align-items: center;">
        <div style="display: flex; align-items: center;">
          <span style="margin-right: 10px; font-weight: bold;">选择时间</span>
          <el-date-picker
            v-model="adjustTime"
            type="datetime"
            placeholder="选择时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
        <div style="display: flex; align-items: center;">
          <span style="margin-right: 10px; font-weight: bold;">系数调整</span>
          <el-input v-model="adjustCoefficient" placeholder="请输入系数调整" style="width: 200px;" @input="adjustCoefficient = formatNumber(adjustCoefficient)" />
        </div>
      </div>

      <el-table :data="computedAdjustData" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{ background: '#F3FAFE', color: '#333', textAlign: 'center', padding: '0' }">
        <el-table-column width="150" align="center" fixed="left">
          <template #header>
            <div class="diagonal-header">
              <span class="top-right">调入</span>
              <span class="bottom-left">调出</span>
            </div>
          </template>
          <template #default="{ row }">
            <span style="font-weight: bold;">{{ row.inMarket }}</span>
          </template>
        </el-table-column>
        
        <el-table-column v-for="col in matrixMarkets" :key="col.key" :label="col.label + '市场团队'" min-width="120" align="center">
          <template #default="{ row }">
            <span v-if="row.isSum">{{ row[col.key] }}</span>
            <el-input v-else v-model="row[col.key]" @input="row[col.key] = formatNumber($event)" placeholder="" class="seamless-input" />
          </template>
        </el-table-column>

        <el-table-column label="合计" min-width="120" align="center" fixed="right">
          <template #default="{ row }">
            {{ getRowTotal(row) }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer" style="text-align: center;">
          <el-button type="primary" plain @click="adjustVisible = false" style="width: 100px;">取消</el-button>
          <el-button type="primary" @click="submitAdjustment" style="width: 100px;">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.cash-flow-container {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.search-card {
  margin-bottom: 10px;
  background: #F3FAFE; // 浅蓝背景
  border: none;
  
  :deep(.el-card__body) {
    padding: 15px;
  }
}

.search-bar {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;

  .label {
    font-size: 15px; // 参考 coinConsumeDetail 的 .text size="large"
    color: #000; // 或 #606266
    white-space: nowrap;
    margin-right: 8px;
    min-width: 60px;
    text-align: right;
  }

  .el-input, .el-select {
    width: 8vw;
  }
}

.search-btn-group {
  margin-left: 2vw; 
  display: flex;
  gap: 10px;
}

.adjust-btn {
  color: #fff;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
  background-color: #7349ad;
  margin-left: auto;
}

.table-card {
  background: #E7F4FD;
  flex: 1;
  border: none;
  display: flex;
  flex-direction: column;
  
  :deep(.el-card__body) {
    padding: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-start;
}

// 表格样式覆盖 (参考 coinConsumeDetail)
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
:deep(.el-table__body td) {
  background-color: #F3FAFE !important; // 如果想完全一致可以加这个，但有时候会影响阅读，暂保留头部颜色
}

:deep(.el-table__row:hover > .el-table__cell) {
  background-color: #E5EBFE !important;
}

.diagonal-header {
  position: relative;
  width: 100%;
  height: 50px; /* Set a fixed height to make diagonal line work well */
  background: linear-gradient(to top right, transparent 49.5%, #dcdfe6 49.5%, #dcdfe6 50.5%, transparent 50.5%);
}
.diagonal-header .top-right {
  position: absolute;
  top: 5px;
  right: 15px;
  font-weight: bold;
}
.diagonal-header .bottom-left {
  position: absolute;
  bottom: 5px;
  left: 15px;
  font-weight: bold;
}

/* 业绩调整弹窗全局样式 */
:deep(.custom-adjust-dialog) {
  background-color: #f3fafe !important; /* 统一淡蓝色背景 */
  border-radius: 8px;
}

:deep(.custom-adjust-dialog .el-dialog__header) {
  padding-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
  margin-right: 0;
}

:deep(.custom-adjust-dialog .el-dialog__body) {
  padding-top: 20px;
}

/* 无缝输入框样式（去除边框和背景） */
.seamless-input :deep(.el-input__wrapper) {
  box-shadow: none !important;
  background-color: transparent !important;
  padding: 0;
}
.seamless-input :deep(.el-input__inner) {
  text-align: center;
  font-size: 14px;
  height: 100%;
}
.seamless-input :deep(.el-input__inner:focus) {
  outline: none;
}
</style>
