<template>
  <div class="search" style="padding: 0;">
      <el-tabs v-model="showType" @tab-click="handleTabClick" class="parent-tabs" >
        <el-tab-pane label="平台充值" :name="0" />
        <el-tab-pane label="用户自充值" :name="1" />
        <el-tab-pane label="转账" :name="2" />
        <el-tab-pane label="异动" :name="3" v-if="isAdmin"/>
      </el-tabs>
      <div style="text-align: right;"  class="search-input" v-if="showType === 0">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        >
          <template #suffix>
						<el-icon class="el-input__icon" @click="handleQuery" style="cursor: pointer;">
							<Search />
						</el-icon>
					</template>
          <template #append>
            <el-button :icon="Operation" @click="showSearchMore" />
          </template>
        </el-input>
      
        <el-button
          type="primary"
          plain
          class="ml-5px"
          @click="openForm('ConsumptionCreate')"
          v-if="showType === 0"
          v-hasPermi="['distri:consumption-top-up-log:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </div>
    </div>
    <div class="searchMore" v-show="searchMoreShow">
        <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
          <el-row>
            <el-col>
              <el-form-item>
                <el-button @click="hideSearchMore">
                  收起
                </el-button>
                <el-button @click="resetQuery">
                  重置
                </el-button>
                <el-button @click="handleQuery">
                  <Icon icon="ep:search" class="mr-5px" /> 搜索
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
    </div>
  <!-- 列表 -->
  <ContentWrap class="m-t-10px p-10px">
    <el-table v-if="showType === 0" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column
        label="充值金额"
        align="center"
        prop="consumptionPoints"
        :formatter="pointsFormatter"
      />
      <el-table-column
        label="消费分"
        align="center"
        prop="practicalConsumptionPoints"
        :formatter="pointsFormatter"
      />
      <el-table-column label="转账凭证附件" align="center" prop="attachment">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.attachment"
            @click="openViewer(scope.row.attachment)"
          />
          
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

    </el-table>
    <el-table v-if="showType === 1" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column
        label="充值金额"
        align="center"
        prop="payPrice"
        :formatter="fenToYuanFormatter"
      />
      <el-table-column
        label="消费分"
        align="center"
        prop="practicalConsumptionPoints"
        :formatter="pointsFormatter"
      />
      
      <el-table-column
        label="支付渠道"
        align="center"
        prop="createTime"
        width="180px"
      >
        <template #default="scope">
          {{getDictLabel(DICT_TYPE.PAY_CHANNEL_CODE, scope.row.payChannelCode) }}
        </template>
      </el-table-column>
      <el-table-column
        label="支付时间"
        align="center"
        prop="payTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

    </el-table>
    <el-table v-if="showType === 2" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="转账人" align="center" prop="transferUserName" />
      <el-table-column
        label="转账金额"
        align="center"
        prop="consumptionPoints"
        :formatter="pointsFormatter"
      />
      <el-table-column
        label="转账后余额"
        align="center"
        prop="afterTransferConsumptionPoints"
        :formatter="pointsFormatter"
      />
      <el-table-column label="接收人" align="center" prop="recipientUserName" />
      <el-table-column label="接收人金额" align="center" prop="recipientPoints" :formatter="pointsFormatter"/>
      <el-table-column
        label="接收后余额"
        align="center"
        prop="afterRecipientConsumptionPoints"
        :formatter="pointsFormatter"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

    </el-table>
    <el-table v-if="showType === 3" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"  @row-click="openNotice($event)" row-class-name="row">
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="异常用户数" align="center" prop="errorUsersCount" />
      <el-table-column
        label="异常金额"
        align="center"
        prop="errorConsumptionPointsTotal"
        :formatter="pointsFormatter"
      />
      <el-table-column
        label="时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
      />

    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handleGet"
    />

  </ContentWrap>
  <el-image-viewer
      v-if="showViewer"
      :url-list="urlList"
      :z-index="9999"
      :initial-index="currentIndex"
      @close="closeViewer"
    />
  <!-- 表单弹窗：添加/修改 -->
  <ConsumptionTopUpLogForm ref="formRef" @success="getList" />
  <ConsumptionTopNotice ref="NoticeRef" @success="getList" />

</template>

<script setup lang="ts">
import { pointsFormatter,fenToYuanFormatter } from '@/utils'
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE, getDictLabel, getDictObj } from '@/utils/dict'
import download from '@/utils/download'
import { ConsumptionTopUpLogApi, ConsumptionTopUpLogVO } from '@/api/system/distri/consumption'
import ConsumptionTopUpLogForm from './ConsumptionTopUpLogForm.vue'
import ConsumptionTopNotice from './ConsumptionTopNotice.vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const user = wsCache.get(CACHE_KEY.USER)
const isAdmin = computed(() => {
  return user.user.id  === 1;
})
import { Search, Operation } from '@element-plus/icons-vue'
const { currentRoute, push } = useRouter() // 路由跳转
import { TabsPaneContext } from 'element-plus';
// 从路由中引入store中的app仓库
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const mobile = computed(() => appStore.getMobile)
/** 平台消费分充值记录 列表 */
defineOptions({ name: 'ConsumptionTopUpLog' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ConsumptionTopUpLogVO[]>([]) // 列表的数据
// 列表的总页数
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,

  createTime: [],
  userName: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const searchMoreShow = ref(false)
// 打开更多搜索条件
const showSearchMore = () => {
  searchMoreShow.value = !searchMoreShow.value
}
const hideSearchMore = () => {
  searchMoreShow.value = false
}
// 默认展示待审核
const showType = ref(0)
const handleTabClick = (tab: TabsPaneContext) => {
  showType.value = tab.paneName as number
  queryParams.pageNo = 1;
  queryParams.userName = undefined;
  list.value = []
  total.value = 0
  handleGet()
}
/** 查询平台充值记录 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ConsumptionTopUpLogApi.getConsumptionTopUpLogPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 查询用户自充值记录 */
const getUserList = async () => {
  loading.value = true
  try {
    const data = await ConsumptionTopUpLogApi.getConsumptionUserTopUpLogPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 查询转账记录 */
const getConsumptionTransfersLog = async () => {
  loading.value = true
  try {
    const data = await ConsumptionTopUpLogApi.getConsumptionTransfersLog(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 查询异动记录 */
const getConsumptionNotice= async () => {
  loading.value = true
  try {
    const data = await ConsumptionTopUpLogApi.getConsumptionNotice(queryParams)
    list.value = data.list
    total.value = data.total
    
  } finally {
    loading.value = false
  }
}
const handleGet = () =>{
  if(showType.value == 0){
    getList()
  }else if(showType.value == 1){
    getUserList()
  }else if(showType.value == 2){
    getConsumptionTransfersLog()
  }else{
    getConsumptionNotice()
  }
}
// 控制图片预览器的状态
const showViewer = ref(false);
const urlList = ref<string[]>([]); // 存储所有图片URL的列表
const currentIndex = ref(0); // 当前显示的图片索引

// 打开图片预览
const openViewer = (imageUrl: string) => {
  console.log(imageUrl)
  urlList.value = list.value.map(item => item.attachment); // 提取所有图片URL
  currentIndex.value = urlList.value.indexOf(imageUrl); // 根据点击的图片找到对应的索引
  showViewer.value = true; // 显示图片预览器
};
// 关闭图片预览
const closeViewer = () => {
  showViewer.value = false;
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if(mobile.value){
    push({
      name: 'ConsumptionAdd',
    })
  }else{
    formRef.value.open(type, id)
  }
}
const NoticeRef = ref()
const openNotice = (row) =>{
  NoticeRef.value.open(row.id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ConsumptionTopUpLogApi.deleteConsumptionTopUpLog(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ConsumptionTopUpLogApi.exportConsumptionTopUpLog(queryParams)
    download.excel(data, '平台消费分充值记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style src="@/styles/SearchIndex.css"  lang="scss" scoped></style>
<style scoped>
  .search{
    flex-direction: row;
  }
  .search-input{
    display: flex;
  }
  
</style>
<style>
  .row{
    cursor: pointer;
  }
</style>