<template>
  <div class="store-page">
    <Breadcrumb />
    <a-card title="电费查询任务">
      <AppQueryFilter>
        <a-row class="query-row">
          <a-col :flex="'1000px'" class="query-main">
            <a-form class="queryForm app-query-form" :model="query" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="create_user" label="用户UUID">
                    <a-input v-model="query.create_user" placeholder="创建人 UUID" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="username" label="用户名">
                    <a-input v-model="query.username" placeholder="平台用户名" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="email" label="通知邮箱">
                    <a-input v-model="query.email" placeholder="任务通知邮箱" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="area" label="校区">
                    <a-input v-model="query.area" placeholder="校区" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="building" label="楼栋">
                    <a-input v-model="query.building" placeholder="楼栋" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="room" label="宿舍号">
                    <a-input v-model="query.room" placeholder="宿舍号" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="queryTime" label="更新时间">
                    <a-range-picker v-model="query.queryTime" show-time format="YYYY-MM-DD HH:mm" value-format="x" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
          <a-divider class="query-divider" style="height: 84px" direction="vertical" />
          <a-col :flex="1" class="app-query-actions">
            <a-space class="query-actions-space" direction="vertical" :size="18">
              <a-button type="primary" @click="search">搜索</a-button>
              <a-button @click="reset">重置</a-button>
            </a-space>
          </a-col>
        </a-row>
      </AppQueryFilter>

      <a-table
        :bordered="false"
        class="table"
        :data="data"
        :loading="loading"
        :scroll="{ x: 1670 }"
        :pagination="{
          showPageSize: true,
          showJumper: true,
          showTotal: true,
          pageSize: pagination.pagesize,
          current: pagination.current,
          total: pagination.total
        }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #columns>
          <a-table-column title="ID" data-index="id" :width="80" />
          <a-table-column title="创建用户" :width="180">
            <template #cell="{ record }">
              <a-space>
                <a-avatar :size="26">
                  <img :src="record.avatar || defaultAvatar" />
                </a-avatar>
                {{ record.username || record.create_user || '-' }}
              </a-space>
            </template>
          </a-table-column>
          <a-table-column title="宿舍" :width="220">
            <template #cell="{ record }">
              {{ record.area }} · {{ record.building }} · {{ record.room }}
            </template>
          </a-table-column>
          <a-table-column title="余额" :width="100">
            <template #cell="{ record }">
              <a-tag :color="isLowBalance(record) ? 'red' : 'green'">￥{{ record.balance }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="阈值" :width="90">
            <template #cell="{ record }">￥{{ record.lowest }}</template>
          </a-table-column>
          <a-table-column title="通知邮箱" data-index="email" :width="180" ellipsis tooltip />
          <a-table-column title="扣费时间" data-index="koufei_date" :width="170" ellipsis tooltip />
          <a-table-column title="已提醒" :width="90">
            <template #cell="{ record }">
              <a-tag :color="Number(record.is_notice) === 1 ? 'orange' : 'gray'">
                {{ Number(record.is_notice) === 1 ? '是' : '否' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="备注" data-index="notes" :width="140" ellipsis tooltip />
          <a-table-column title="添加时间" :width="170">
            <template #cell="{ record }">{{ formatTime(record.create_time) }}</template>
          </a-table-column>
          <a-table-column title="更新时间" :width="170">
            <template #cell="{ record }">{{ formatTime(record.update_time) }}</template>
          </a-table-column>
          <a-table-column title="操作" :width="120" :fixed="tableFixed('right')">
            <template #cell="{ record }">
              <a-button type="text" size="small" @click="openChangeRecord(record)">账单记录</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="recordVisible"
      title="电费变更记录"
      width="auto"
      hide-cancel
      esc-to-close
      draggable
    >
      <a-table
        :bordered="false"
        :data="changeList"
        :loading="recordLoading"
        :scroll="{ x: 720 }"
        :pagination="false"
        stripe
      >
        <template #columns>
          <a-table-column title="记录时间" :width="170">
            <template #cell="{ record }">{{ formatTime(record.time) }}</template>
          </a-table-column>
          <a-table-column title="扣费时间" data-index="change_time" :width="170" ellipsis tooltip />
          <a-table-column title="电费余额" :width="110">
            <template #cell="{ record }">￥{{ record.balance }}</template>
          </a-table-column>
          <a-table-column title="原余额" :width="110">
            <template #cell="{ record }">￥{{ record.old_balance }}</template>
          </a-table-column>
          <a-table-column title="变动金额" :width="110">
            <template #cell="{ record }">
              <a-tag :color="Number(record.balance) < Number(record.old_balance) ? 'red' : 'green'">
                ￥{{ (Number(record.balance) - Number(record.old_balance)).toFixed(2) }}
              </a-tag>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { adminPowerTaskList, adminPowerGetChangeRecord } from '@/api/power'
import { useResponsiveTable } from '@/hooks/useResponsiveTable'

const { tableFixed } = useResponsiveTable()
const defaultAvatar = 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'
const loading = ref(false)
const data = ref([])
const query = reactive({
  create_user: '',
  username: '',
  email: '',
  area: '',
  building: '',
  room: '',
  queryTime: []
})
const pagination = reactive({
  total: 0,
  current: 1,
  pagesize: 20
})

const recordVisible = ref(false)
const recordLoading = ref(false)
const changeList = ref([])

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(Number(time)).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const isLowBalance = (record) => Number(record.balance) <= Number(record.lowest)

const getList = async () => {
  try {
    loading.value = true
    const res = await adminPowerTaskList({
      ...query,
      current: pagination.current,
      pagesize: pagination.pagesize
    })
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取电费任务失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    data.value = res.data || []
    pagination.total = res.pagination?.total || 0
  } catch (error) {
    Notification.error({
      title: '获取电费任务失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

const openChangeRecord = async (record) => {
  try {
    recordLoading.value = true
    recordVisible.value = true
    changeList.value = []
    const res = await adminPowerGetChangeRecord({ id: record.id })
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取账单记录失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    changeList.value = res.data || []
  } catch (error) {
    Notification.error({
      title: '获取账单记录失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    recordLoading.value = false
  }
}

const search = () => {
  pagination.current = 1
  getList()
}

const reset = () => {
  query.create_user = ''
  query.username = ''
  query.email = ''
  query.area = ''
  query.building = ''
  query.room = ''
  query.queryTime = []
  pagination.current = 1
  getList()
}

const onPageChange = (page) => {
  pagination.current = page
  getList()
}

const onPageSizeChange = (size) => {
  pagination.pagesize = size
  pagination.current = 1
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.query-row {
  margin-bottom: 10px;
}

.query-main {
  min-width: 0;
}

.query-actions-space {
  width: 100%;
}

.table {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .query-row {
    display: block;
  }

  .query-divider {
    display: none;
  }

  .query-actions-space {
    margin-top: 4px;
    flex-direction: row !important;
    gap: 10px !important;
  }

  .query-actions-space :deep(.arco-btn) {
    flex: 1;
  }
}
</style>
