<template>
  <el-card style="margin-bottom: 5px">
    <el-row style="margin-bottom: 10px">
      <el-col :span="6">
        <el-text size="large">精网号：</el-text>
        <el-input v-model="searchForm.jwcode" placeholder="请输入精网号" style="width: 240px" clearable/>
      </el-col>
      <el-col :span="6">
        <el-text size="large">所属地区：</el-text>
        <el-select v-model="searchForm.market" placeholder="请选择" style="width: 240px" clearable>
          <el-option v-for="item in marketOptions" :key="item" :label="item" :value="item"/>
        </el-select>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="15">
        <div class="time-controls">
          <div class="time-group">
            <el-text size="large" style="width: 80px">充值时间：</el-text>
            <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至"
                            start-placeholder="开始时间" end-placeholder="结束时间" style="width: 400px"
                            @change="handleDatePickerChange" :default-time="defaultTime"/>
            <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 type="success" @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </el-card>

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

    <div>
      总条数：{{ stats.num }}条&nbsp;&nbsp;&nbsp;&nbsp;
      总金豆数：{{ stats.beanNum }}金豆&nbsp;&nbsp;&nbsp;&nbsp;
      永久金豆：{{ stats.permanentBean }}金豆&nbsp;&nbsp;&nbsp;&nbsp;
      免费金豆：{{ stats.freeBean }}金豆
    </div>

    <el-table :data="tableData" height="540px" @sort-change="handleSortChange">
      <el-table-column prop="id" label="序号" width="80"/>
      <el-table-column prop="name" label="姓名" width="120" show-overflow-tooltip/>
      <el-table-column prop="jwcode" label="精网号" width="120"/>
      <el-table-column prop="market" label="所属地区" width="120"/>
      <el-table-column prop="permanentBean" label="付费金豆" width="120" sortable="custom"/>
      <el-table-column prop="freeBean" label="免费金豆" width="120" sortable="custom"/>
      <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip/>
      <el-table-column prop="submitName" label="提交人" width="120"/>
      <el-table-column v-if="checkTab === 'reject'" prop="reason" label="驳回理由" width="120"
                       show-overflow-tooltip/>
      <el-table-column v-if="checkTab !== 'pending'" prop="auditName" label="审核人" width="120"/>
      <el-table-column prop="createTime" label="提交时间" width="180" sortable="custom">
        <template #default="{ row }">
          {{ moment(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column v-if="checkTab !== 'pending'" prop="auditTime" label="审核时间" width="240" sortable="custom">
        <template #default="{ row }">
          {{ row.auditTime ? moment(row.auditTime).format('YYYY-MM-DD HH:mm:ss') : '--' }}
        </template>
      </el-table-column>
      <el-table-column v-if="checkTab === 'pending'" fixed="right" prop="operation" label="操作" width="400px">
        <template #default="scope">
          <div class="operation">
            <el-popconfirm title="确定要通过此条记录吗？" @confirm="handleApprove(scope.row)">
              <template #reference>
                <el-button :disabled="scope.row.status === 1 || scope.row.status === 2" type="primary"
                           text>
                  通过
                </el-button>
              </template>
            </el-popconfirm>
            <el-button :disabled="scope.row.status === 1 || scope.row.status === 2" type="primary" text
                       @click="showRejectDialog(scope.row)">
              驳回
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="margin-top:20px" v-model:current-page="pagination.pageNum"
                   v-model:page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
                   :total="stats.num"
                   @size-change="handlePageSizeChange" @current-change="handleCurrentChange"></el-pagination>
  </el-card>

  <el-dialog v-model="rejectDialogVisible" title="驳回理由" width="500px">
    <el-form>
      <el-form-item label="驳回理由" required>
        <el-input v-model="reason" 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, ref} from 'vue'
import {ElMessage} from 'element-plus'
import API from '@/util/http'
import moment from 'moment'
import {useAdminStore} from "@/store/index.js";
import {storeToRefs} from "pinia";
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1,23 , 59, 59),
]
const adminStore = useAdminStore();
const {adminData, menuTree} = storeToRefs(adminStore);
import {permissionMapping, findMenuById} from "@/utils/menuTreePermission.js"
import dayjs from "dayjs";

const tableData = ref([])
const marketOptions = ref([])
const dateRange = ref([])
const activeTimeRange = ref('')
const activeName = ref('wait')
const sortField = ref('')
const sortOrder = ref('')
const checkTab = ref('pending')
const rejectDialogVisible = ref(false)
const reason = ref('')
const rejectRow = ref({
  id: null
})// 驳回行数据
// 状态常量
const STATUS = {
  PENDING: 0, // 待审核
  APPROVED: 1, // 通过
  REJECTED: 2 // 驳回
}
const searchForm = ref({
  jwcode: '',
  market: '',
  createStartTime: '',
  createEndTime: '',
  status: STATUS.PENDING,
  auditStartTime: '',
  auditEndTime: ''
})
const pagination = ref({
  pageNum: 1,
  pageSize: 50
})
// 合计数
const stats = ref({
  num: 0,
  beanNum: 0,
  permanentBean: 0,
  freeBean: 0
})
const showRejectDialog = (row) => {
  rejectRow.value.id = row.id
  reason.value = ''
  rejectDialogVisible.value = true
}
const getmarkets = async () => {
  try {
    const result = await API({url: '/beanConsume/getDept', data: {}})
    marketOptions.value = result.data || []
  } catch (error) {
    console.error('获取地区列表失败', error)
  }
}
const handleSortChange = (column) => {
  if (column.prop === 'permanentBean') {
    sortField.value = 'permanentBean'
  } else if (column.prop === 'freeBean') {
    sortField.value = 'freeBean'
  } else if (column.prop === 'createTime') {
    sortField.value = 'createTime'
  } else if (column.prop === 'auditTime') {
    sortField.value = 'auditTime'
  } else {
    sortField.value = ''
  }
  sortOrder.value = column.order === 'ascending' ? 'ASC' : 'DESC'
  console.log('排序字段：', sortField.value)
  console.log('排序方式：', sortOrder.value)
  get()
}
const handleSearch = function () {
  if(searchForm.value.jwcode){
        const numRef = /^\d{1,9}$/;
        if(!numRef.test(searchForm.value.jwcode)){
            ElMessage.error('请检查精网号格式')
            return 
        }
    }
  get()
  getStats()
}
const get = async function () {
  if (findMenuById(menuTree.value, permissionMapping.View_Golden_Bean_Recharge_Audit)) {
    try {
      if (dateRange.value && dateRange.value.length === 2) {
        searchForm.value.createStartTime = moment(dateRange.value[0]).format('YYYY-MM-DD HH:mm:ss')
        searchForm.value.createEndTime = moment(dateRange.value[1]).format('YYYY-MM-DD HH:mm:ss')
      } else {
        searchForm.value.createStartTime = ''
        searchForm.value.createEndTime = ''
      }
      const params = {
        pageNum: pagination.value.pageNum,//页码
        pageSize: pagination.value.pageSize,//页面大小
        beanAuditInfo: {
          jwcode: searchForm.value.jwcode,
          status: searchForm.value.status,
          market: searchForm.value.market,
          createStartTime: searchForm.value.createStartTime,
          createEndTime: searchForm.value.createEndTime,
          auditStartTime: searchForm.value.auditStartTime,
          auditEndTime: searchForm.value.auditEndTime,
          sortField: sortField.value,
          sortOrder: sortOrder.value
        }
      }
      console.log('看看传给后端的参数：', params)
      const res = await API({url: '/beanAudit/selectBy', data: params})
      tableData.value = res.data.list || []
    } catch (error) {
      console.error('获取数据失败', error)
    }
  } else {
    ElMessage.error('无此权限')
  }
}
const getStats = async () => {
  if (findMenuById(menuTree.value, permissionMapping.View_Golden_Bean_Recharge_Audit)) {
    try {
      const params = {
        jwcode: searchForm.value.jwcode,
        status: searchForm.value.status,
        market: searchForm.value.market,
        createStartTime: searchForm.value.createStartTime,
        createEndTime: searchForm.value.createEndTime,
        auditStartTime: searchForm.value.auditStartTime,
        auditEndTime: searchForm.value.auditEndTime
      }

      const res = await API({
        url: '/beanAudit/statsBean',
        data: params
      })

      stats.value.num = res.data.num
      stats.value.permanentBean = res.data.permanentBean
      stats.value.freeBean = res.data.freeBean
      stats.value.beanNum = res.data.beanNum
      console.log('see see stats和搜索对象', stats.value, params)
    } catch (error) {
      console.log('请求失败', error)
    }
  } else {
    ElMessage.error('无此权限')
  }
}
// 通过
const handleApprove = async (row) => {
  if (findMenuById(menuTree.value, permissionMapping.Golden_Bean_Recharge_Approval)) {
    try {
      const params = {
        id: row.id,
        auditName: adminData.value.name,
      }
      await API({url: '/beanAudit/status1', data: params})
      ElMessage.success('审核通过成功')
      get()
      getStats()
    } catch (error) {
      console.error('审核通过失败', error)
      ElMessage.error('操作失败')
    }
  } else {
    ElMessage.error('无此权限')
  }
}

// 驳回
const handleReject = async () => {
  if (findMenuById(menuTree.value, permissionMapping.Golden_Bean_Recharge_Approval)) {
    if (!reason.value.trim()) {
      ElMessage.warning('请输入驳回理由')
      return
    }
    try {
      const params = {
        id: rejectRow.value.id,
        auditName: adminData.value.adminName,
        reason: reason.value
      }
      await API({url: '/beanAudit/status2', data: params})
      ElMessage.success('驳回成功')
      rejectDialogVisible.value = false
      get()
      getStats()
    } catch (error) {
      console.error('驳回失败', error)
      ElMessage.error('操作失败')
    }
  } else {
    ElMessage.error('无此权限')
  }
}
const getToday = function () {
  const today = dayjs()
  const startTime = today.startOf('day').format('YYYY-MM-DD HH:mm:ss')
  const endTime = today.endOf('day').format('YYYY-MM-DD HH:mm:ss')
  dateRange.value = [startTime, endTime]
  console.log('dateRange', dateRange.value)
  activeTimeRange.value = 'today'

  get()
  getStats()
}
const getYesterday = function () {
  const today = dayjs()
  const startTime = today.subtract(1, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss')
  const endTime = today.subtract(1, 'day').endOf('day').format('YYYY-MM-DD HH:mm:ss')
  dateRange.value = [startTime, endTime]
  console.log('dateRange', dateRange.value)
  activeTimeRange.value = 'yesterday'

  get()
  getStats()
}
const get7Days = function () {
  const today = dayjs()
  const startTime = today.subtract(6, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss')
  const endTime = today.add(1, 'day').endOf('day').format('YYYY-MM-DD HH:mm:ss')
  dateRange.value = [startTime, endTime]
  console.log('dateRange', dateRange.value)
  activeTimeRange.value = '7days'

  get()
  getStats()
}
const resetSearch = function () {
  const status = searchForm.value.status;
  searchForm.value = {
    jwcode: '',
    market: '',
    createStartTime: '',
    createEndTime: '',
    status: status,
    auditStartTime: '',
    auditEndTime: ''
  }
  dateRange.value = []
  activeTimeRange.value = '' // 清除激活状态
}

const handleClick = function (tab) {
  resetSearch()                                                                                                                                                                                         
  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 adminWait = async function () {
  checkTab.value = 'pending'
  searchForm.value.status = STATUS.PENDING
  await get()
  await getStats()
}

// 已通过充值明细
const adminPass = async function () {
  checkTab.value = 'pass'
  searchForm.value.status = STATUS.APPROVED
  await get()
  await getStats()
}

// 已驳回充值明细
const adminReject = async function () {
  checkTab.value = 'reject'
  searchForm.value.status = STATUS.REJECTED
  await get()
  await getStats()
}
const handleDatePickerChange = () => {
  activeTimeRange.value = ''
}
const handlePageSizeChange = function (val) {
  pagination.value.pageSize = val
  get()
}
const handleCurrentChange = function (val) {
  pagination.value.pageNum = val
  get()
}
onMounted(async () => {
  getmarkets()
  get()
  getStats()
  console.log("看看通信来的用户身份", adminData.value)
})
</script>

<style scoped></style>