<!-- 支付凭证！！！ -->
<template>
  <el-row>
    <el-col>
      <el-card style="margin-bottom: 5px">
        <el-row style="margin-bottom: 5px">
          <el-col :span="6">
            <el-text size="large">精网号：</el-text>
            <el-input v-model="rechargeAudit.jwcode" placeholder="请输入精网号" style="width: 240px" clearable/>
          </el-col>
          <el-col :span="6">
            <el-text size="large">活动名称：</el-text>
            <el-select v-model="rechargeAudit.activity" placeholder="请选择活动名称" style="width: 240px" clearable>
              <el-option v-for="item in activity" :key="item" :label="item" :value="item"/>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-text size="large">支付方式：</el-text>
            <el-select v-model="rechargeAudit.payModel" placeholder="请选择支付方式" style="width: 240px" clearable>
              <el-option v-for="item in payModel" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-text class="mx-1" size="large">所属地区：</el-text>
            <el-cascader
                v-model="selectedMarketPath"
                :options="markets"
                placeholder="请选择所属地区"
                clearable
                collapse-tags
                collapse-tags-tooltip
                style="width:180px"
                @change="handleMarketChange"
                :props="props"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="time-controls">
              <div class="time-group">
                <el-text size="large" style="width: 80px">充值时间：</el-text>
                <el-date-picker v-model="getTime" type="datetimerange" range-separator="至" start-placeholder="起始时间"
                                end-placeholder="结束时间" style="width: 400px" @change="handleDatePickerChange"/>
                <el-button @click="getToday()" style="margin-left: 10px"
                           :type="activeTimeRange === 'today' ? 'primary' : ''"> 今
                </el-button>
                <el-button @click="getYesterday()" style="margin-left: 10px"
                           :type="activeTimeRange === 'yesterday' ? 'primary' : ''"> 昨
                </el-button>
                <el-button @click="get7Days()" style="margin-left: 10px"
                           :type="activeTimeRange === '7days' ? 'primary' : ''"> 近7天
                </el-button>
                <el-button @click="resetSearch" type="success">重置</el-button>
                <el-button type="primary" @click="handleSearch">查询</el-button>
              </div>

            </div>

          </el-col>

        </el-row>
      </el-card>
    </el-col>
  </el-row>
  <el-row>
    <el-col>
      <el-card>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="待审核" name="wait"></el-tab-pane>
          <el-tab-pane label="已通过" name="pass"></el-tab-pane>
          <el-tab-pane label="已驳回" name="reject"></el-tab-pane>

          <div>
            总条数：{{ stats.totalNum }}条&nbsp;&nbsp;&nbsp;&nbsp;
            总金币数：{{ (stats.permanentGolds + stats.freeGolds + stats.taskGolds).toFixed(2) }}金币&nbsp;&nbsp;&nbsp;&nbsp;
            永久金币：{{ stats.permanentGolds.toFixed(2) }}金币&nbsp;&nbsp;&nbsp;&nbsp;
            免费金币：{{ stats.freeGolds.toFixed(2) }}金币&nbsp;&nbsp;&nbsp;&nbsp;
            <!--            任务金币：{{ stats.taskGolds.toFixed(2) }}金币-->
          </div>
        </el-tabs>

        <!--表格-->
        <div style="height: 540px; overflow-y: auto">
          <el-table :data="tableData" style="width: 100%" height="540px" @sort-change="handleSortChange"
                    :row-style="{ height: '50px' }">
            <el-table-column type="index" label="序号" width="100px" fixed="left">
              <template #default="scope">
                <span>{{ scope.$index + 1 + (getObj.pageNum - 1) * getObj.pageSize }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="left" prop="name" label="姓名" width="150px"/>
            <el-table-column fixed="left" prop="jwcode" label="精网号" width="110px"/>
            <el-table-column prop="market" label="所属地区" width="100px">
              <template #default="scope">
                {{ marketMapping[scope.row.market] || scope.row.market }}
              </template>
            </el-table-column>
            <el-table-column prop="activity" label="活动名称" width="100px" show-overflow-tooltip/>
            <el-table-column prop="money" label="充值金额" sortable="custom" width="110px">
              <template #default="scope">{{ scope.row.permanentGold / 100 }}</template>
            </el-table-column>
            <el-table-column prop="permanentGold" label="永久金币" width="110px" sortable="custom">
              <template #default="scope">{{ scope.row.permanentGold / 100 }}</template>
            </el-table-column>
            <el-table-column prop="freeGold" label="免费金币" sortable="custom" width="110px">
              <template #default="scope">{{ (scope.row.freeGold) / 100 }}</template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="200px" show-overflow-tooltip/>

            <el-table-column prop="payModel" label="支付方式" width="110px"/>
            <el-table-column prop="voucher" label="支付凭证" width="110px">
              <template #default="scope">
                <div v-if="scope.row.voucher"
                     style="display: flex; justify-content: center; align-items: center; cursor: pointer;"
                     @click="previewImage(scope.row.voucher)">
                  <img :src="scope.row.voucher" alt="支付凭证" style="width: auto; height: 40px;">
                </div>
                <div v-else style="display: flex; justify-content: center; align-items: center; height: 40px;">--</div>
              </template>
            </el-table-column>
            <el-table-column prop="adminName" label="提交人" width="100px"/>
            <el-table-column prop="rejectReason" v-if="activeName === 'reject'" label="驳回理由" width="200px"
                             show-overflow-tooltip/>
            <el-table-column v-if="activeName !== 'wait'" prop="auditName" label="审核人" width="100px"/>
            <el-table-column prop="payTime" sortable="custom" label="付款时间" width="200px">
              <template #default="scope">
                {{ moment(scope.row.payTime).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" sortable="custom" label="提交时间" width="200px">
              <template #default="scope">
                {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
            <el-table-column v-if="activeName !== 'wait'" prop="auditTime" label="审核时间" width="200px">
              <template #default="scope">
                {{ moment(scope.row.auditTime).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
            <el-table-column v-if="activeName === 'wait'" fixed="right" prop="operation" label="操作" width="150px">
              <template #default="scope">
                <div class="operation">
                  <el-popconfirm title="确定要通过此条记录吗？" @confirm="handleApprove(scope.row)">
                    <template #reference>
                      <el-button :disabled="scope.row.auditStatus === 1 || scope.row.auditStatus === 2" type="primary"
                                 text>
                        通过
                      </el-button>
                    </template>
                  </el-popconfirm>
                  <el-button :disabled="scope.row.auditStatus === 1 || scope.row.auditStatus === 2" type="primary" text
                             @click="showRejectDialog(scope.row)">
                    驳回
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="pagination">
          <el-pagination background :page-size="getObj.pageSize" :page-sizes="[5, 10, 20, 50, 100]"
                         layout="total, sizes, prev, pager, next, jumper" :total="total"
                         @size-change="handlePagination('size', $event)"
                         @current-change="handlePagination('page', $event)"></el-pagination>
        </div>
      </el-card>
    </el-col>
  </el-row>

  <el-dialog v-model="rejectDialogVisible" title="驳回理由" width="500px">
    <el-form>
      <el-form-item label="驳回理由" required>
        <el-input v-model="rejectReason" type="textarea" :rows="4" placeholder="请输入驳回理由" maxlength="200"
                  show-word-limit/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleReject">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {marketMapping, reverseMarketMapping} from '@/utils/marketMap.js'
import {ElMessage} from 'element-plus'
import request from '@/util/http'
import API from '@/util/http'
import moment from 'moment'
import {useAdminStore} from "@/store/index.js";
import {storeToRefs} from "pinia";
import {findMenuById, permissionMapping} from "@/utils/menuTreePermission.js"
// 精网号去空格
const trimJwCode = () => {
  if (rechargeAudit.value.jwcode) {
    rechargeAudit.value.jwcode = rechargeAudit.value.jwcode.replace(/\s/g, '');
  }
}
const formatTime = (val) => val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''

// 这是获取用户信息的接口
const adminData = ref({})
// 充值明细表格
const tableData = ref([])
// 标记当前激活的时间范围按钮
const activeTimeRange = ref('')
// 日期选择器变化时清除按钮激活状态
const handleDatePickerChange = () => {
  activeTimeRange.value = ''
}

// 搜索表单数据
const rechargeAudit = ref({
  jwcode: "", // 精网号
  activity: "", // 活动名称
  payModel: "", // 支付方式
  startTime: "", // 充值时间开始
  endTime: "", // 充值时间结束
  markets: [], // 地区
  auditStatus: "0",
})

// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})
// 分页总条目
const total = ref(50)
// 搜索对象时间
const getTime = ref([])
const activity = ref([])
// 搜索地区列表
const markets = ref([])
// 驳回弹出框
const rejectDialogVisible = ref(false)
// 驳回理由
const rejectReason = ref('')
// 当前行信息
const currentRecord = ref(null)
// 标签页默认是待审批
const activeName = ref('wait')
// 支付方式选项
const payModel = [

  // 现金、支票、刷卡、其他（各地区电子支付）
  {
    value: '现金',
    label: '现金'
  },
  {
    value: '支票',
    label: '支票'
  },
  {
    value: '刷卡',
    label: '刷卡'
  },
  {
    value: '其他(各地区电子支付)',
    label: '其他(各地区电子支付)'
  },
]
// 表单验证ref
const Ref = ref(null)
// 统计合计数
const stats = ref({
  totalNum: 0,
  totalCoins: 0,
  permanentGolds: 0,
  freeGolds: 0,
  taskGolds: 0
})


// 新增排序字段和排序方式
const sortField = ref('')
const sortOrder = ref('')

// 表单验证
const rules = reactive({
  rejectReason: [{required: true, message: '请输入驳回理由', trigger: 'blur'}]
})

const getAdminData = async function () {
  try {
    const result = await request({
      url: '/admin/userinfo',
      data: {}
    })
    adminData.value = result
    console.log('用户信息', adminData.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 搜索方法
const getRecharge = async function (val) {
  try {
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    // 搜索参数时间赋值
    if (getTime.value && getTime.value.length === 2) {
      rechargeAudit.value.startTime = formatTime(getTime.value[0])
      rechargeAudit.value.endTime = formatTime(getTime.value[1])
    } else {
      rechargeAudit.value.startTime = ''
      rechargeAudit.value.endTime = ''
    }

    console.log('搜索参数', getObj.value)

    const result = await request({
      url: '/audit/selectRecharge',
      data: {
        pageNum: getObj.value.pageNum,
        pageSize: getObj.value.pageSize,
        rechargeAudit: {
          ...rechargeAudit.value,
          sortField: sortField.value,
          sortOrder: sortOrder.value
        }
      }
    })
    // 存储表格数据
    tableData.value = result.list
    // 存储总条数
    total.value = result.total
  } catch (error) {
    console.log('请求失败', error)
  }
}

const getStats = async () => {
  try {
    const params = {
      pageNum: getObj.value.pageNum,
      pageSize: getObj.value.pageSize,
      rechargeAudit: rechargeAudit.value
    }
    const res = await API({
      url: '/audit/sumRechargeGold',
      data: params
    })

    stats.value.totalNum = res.totalNum
    stats.value.permanentGolds = res.permanentGolds / 100
    stats.value.freeGolds = res.freeGolds / 100
    stats.value.taskGolds = res.taskGolds / 100
    console.log('see see stats和搜索对象', stats.value, params)
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 搜索
const handleSearch = function () {
  trimJwCode();
  getObj.value.pageNum = 1
  getRecharge()
  getStats()
}

// 重置
const resetSearch = function () {
  rechargeAudit.value = {
    jwcode: "",
    activity: "",
    payModel: "",
    startTime: "",
    endTime: "",
    markets: [],
    auditStatus: rechargeAudit.value.auditStatus,

  }
  selectedMarketPath.value = []
  getTime.value = []
  activeTimeRange.value = '' // 清除激活状态
  getRecharge()
  getStats()
}

// 今天
const getToday = function () {
  const today = new Date()
  const startTime = new Date(
      today.getFullYear(),
      today.getMonth(),
      today.getDate()
  )
  const endTime = new Date(
      today.getFullYear(),
      today.getMonth(),
      today.getDate() + 1
  )
  getTime.value = [startTime, endTime]
  console.log('getTime', getTime.value)
  activeTimeRange.value = 'today' // 标记当前激活状态
  getRecharge()
  getStats()
}

// 昨天
const getYesterday = function () {
  const yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)
  const startTime = new Date(
      yesterday.getFullYear(),
      yesterday.getMonth(),
      yesterday.getDate()
  )
  const endTime = new Date(
      yesterday.getFullYear(),
      yesterday.getMonth(),
      yesterday.getDate() + 1
  )
  getTime.value = [startTime, endTime]
  console.log('getTime', getTime.value)
  activeTimeRange.value = 'yesterday' // 标记当前激活状态
  getRecharge()
  getStats()
}

// 近7天
const get7Days = function () {
  const today = new Date()
  const startTime = new Date(
      today.getFullYear(),
      today.getMonth(),
      today.getDate() - 6
  )
  const endTime = new Date(
      today.getFullYear(),
      today.getMonth(),
      today.getDate() + 1
  )
  getTime.value = [startTime, endTime]
  console.log('getTime', getTime.value)
  activeTimeRange.value = '7days' // 标记当前激活状态
  getRecharge()
  getStats()
}

// 待审核充值明细
const adminWait = async function () {
  rechargeAudit.value.auditStatus = "0"
  getObj.value.pageNum = 1
  await getRecharge()
  await getStats()
  console.log('adminWait，这是点击待审核调用')
}

// 已通过充值明细
const adminPass = async function () {
  rechargeAudit.value.auditStatus = "1"
  getObj.value.pageNum = 1
  await getRecharge()
  await getStats()
  console.log('adminWait，这是点击已通过调用')
}

// 已驳回充值明细
const adminReject = async function () {
  rechargeAudit.value.auditStatus = "2"
  getObj.value.pageNum = 1
  await getRecharge()
  await getStats()
  console.log('adminWait，这是点击已驳回调用')
}

const handleClick = function (tab, event) {
  activeName.value = tab.props.name
  if (tab.props.name === 'wait') {
    adminWait()
  } else if (tab.props.name === 'pass') {
    adminPass()
  } else if (tab.props.name === 'reject') {
    adminReject()
  }
}

const getActivity = async function () {
  try {
    const result = await request({
      url: '/general/activity',
      data: {}
    })
    activity.value = result.data
    console.log('activity', activity.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}


const handlePagination = (type, val) => {
  if (type === 'size') {
    getObj.value.pageSize = val
  } else {
    getObj.value.pageNum = val
  }
  getRecharge()
  getStats()
}

const adminStore = useAdminStore();
const {menuTree} = storeToRefs(adminStore);


// 处理通过操作
const handleApprove = async (row) => {
  if (findMenuById(menuTree.value, permissionMapping.Recharge_Approval)) {
    try {
      const params = {
        orderCode: row.orderCode,
        auditId: adminData.value.id,
        action: 1,
        rejectReason: ''
      }
      await request({url: '/audit/audit', data: params})
      ElMessage.success('审核通过成功')
      await getRecharge()
      await getStats()
    } catch (error) {
      console.error('审核通过失败', error)
      ElMessage.error('操作失败')
    }
  } else {
    ElMessage.error('无权限')
  }

}

// 显示驳回对话框
const showRejectDialog = (row) => {
  currentRecord.value = row
  rejectReason.value = '' // 清空之前的
  rejectDialogVisible.value = true
}

// 处理驳回操作
const handleReject = async () => {
  if (!rejectReason.value.trim()) {
    ElMessage.warning('请输入驳回理由')
    return
  }
  try {
    const params = {
      orderCode: currentRecord.value.orderCode,
      auditId: adminData.value.id,
      action: 2,
      rejectReason: rejectReason.value
    }

    await request({url: '/audit/audit', data: params})

    ElMessage.success('驳回操作成功')
    rejectDialogVisible.value = false
    await getRecharge()
    await getStats()
  } catch (error) {
    console.error('驳回操作失败', error)
    ElMessage.error('操作失败')
  }
}

// 处理排序事件
const handleSortChange = (column) => {
  console.log('排序字段：', column.prop)
  console.log('排序方式：', column.order)

  if (column.prop === 'money') {
    sortField.value = 'permanent_gold'
  } else if (column.prop === 'permanentGold') {
    sortField.value = 'permanent_gold'
  } else if (column.prop === 'freeGold') {
    sortField.value = 'freeGold'
  } else if (column.prop === 'createTime') {
    sortField.value = 'create_time'
  } else if (column.prop === 'payTime') {
    sortField.value = 'pay_time'
  } else if (column.prop === 'auditTime') {
    sortField.value = 'audit_time'
  }
  sortOrder.value = column.order === 'ascending' ? 'asc' : 'desc'
  getRecharge()
  getStats()
}
// 预览图片函数
const previewImage = (imageUrl) => {
  // 使用 element-plus 的 el-image 组件实现图片预览功能
  const imageElement = document.createElement('img');
  imageElement.src = imageUrl;
  imageElement.style.maxWidth = '80vw';
  imageElement.style.maxHeight = '80vh';

  const viewer = document.createElement('div');
  viewer.style.position = 'fixed';
  viewer.style.top = '0';
  viewer.style.left = '0';
  viewer.style.width = '100vw';
  viewer.style.height = '100vh';
  viewer.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
  viewer.style.display = 'flex';
  viewer.style.justifyContent = 'center';
  viewer.style.alignItems = 'center';
  viewer.style.zIndex = '9999';
  viewer.style.overflow = 'auto';

  viewer.appendChild(imageElement);
  document.body.appendChild(viewer);

  viewer.addEventListener('click', () => {
    document.body.removeChild(viewer);
  });
};

// 存储地区选择变化
const selectedMarketPath = ref([])
//处理地区选择变化
const handleMarketChange = (value) => {
  if (Array.isArray(value) && value.length > 0) {
    const ids = new Set();

    value.forEach(path => {
      const lastName = path[path.length - 1];
      const id = reverseMarketMapping[lastName];
      if (id) ids.add(Number(id));
    });

    // 添加额外处理：如果一个父节点下所有子节点都被选中，则把父节点也加入
    const getAllLeafNames = (nodes) => {
      const leafNames = [];

      const traverse = (node, parentName = null) => {
        if (!node.children || node.children.length === 0) {
          leafNames.push({name: node.label, parent: parentName});
        } else {
          node.children.forEach(child => traverse(child, node.label));
        }
      };

      nodes.forEach(node => traverse(node));
      return leafNames;
    };

    const leafNameMap = getAllLeafNames(markets.value); // 所有叶子节点和对应父级名称

    // 列表构建
    const parentToChildren = {};
    leafNameMap.forEach(({name, parent}) => {
      if (!parentToChildren[parent]) parentToChildren[parent] = [];
      parentToChildren[parent].push(name);
    });

    // 构建当前被选中的叶子节点
    const selectedLeafNames = value.map(path => path[path.length - 1]);

    // 如果 parent 下所有子节点都选中了，就把 parent 加进来
    Object.entries(parentToChildren).forEach(([parent, children]) => {
      const allChildrenSelected = children.every(child => selectedLeafNames.includes(child));
      if (allChildrenSelected && reverseMarketMapping[parent]) {
        ids.add(Number(reverseMarketMapping[parent]));
      }
    });

    rechargeAudit.value.markets = Array.from(ids);
  } else {
    rechargeAudit.value.markets = [];
  }

  console.log('最终映射后的 market IDs:', rechargeAudit.value.markets);
};

const props = {multiple: true}
// 获取地区，修改为级联下拉框
const getMarket = async function () {
  try {
    // 发送POST请求
    const result = await API({

      url: '/market/selectMarket',
    });
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)

    // 递归转换树形结构为级联选择器需要的格式（跳过第一级节点）
    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.name,
          label: child.name,
          children: grandchildren
        };
      });
    };
    // 存储地区信息
    markets.value = transformTree(result.data)
    console.log('转换后的地区树==============', markets.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 挂载
onMounted(async function () {
  await getAdminData()
  await getActivity()
  await getMarket()
  await getRecharge()
  console.log('111')
  await getStats()
})
</script>

<style scoped>
.pagination {
  display: flex;
}

.operation {
  display: flex;
}

.green-dot {
  background-color: #67C23A;
}

.grey-dot {
  background-color: #909399;
}

.red-dot {
  background-color: #F56C6C;
}

.time-controls {
  display: flex;
  align-items: center;
}

.time-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.quick-buttons {
  display: flex;
  align-items: center;
}

.status {
  display: flex;
  align-items: center;
  /* 确保子元素垂直居中对齐 */
  gap: 6px;
  /* 设置圆点和文字之间的间距 */
}

.green-dot,
.grey-dot,
.red-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
  /* 防止圆点在空间不足时缩小 */
  margin: 0;
  /* 移除原有的 margin-right */
}

/* 备注列样式 */
.remark-cell {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 设置单元格内容溢出隐藏 */
.el-table .el-table__cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>