<template>
  <div class="store-page power-page">
    <div class="power-page__inner power-page__inner--wide">
      <Breadcrumb />

      <header class="page-header">
        <div>
          <h1 class="store-section-title">定制电费提醒</h1>
          <p class="store-section-desc">绑定宿舍号，余额低于阈值时将通过邮件通知您</p>
        </div>
        <a-button type="primary" class="primary-btn" @click="editAccount()">
          <template #icon><icon-plus /></template>
          添加提醒任务
        </a-button>
      </header>

      <a-alert v-if="notice" type="info" closable class="notice">{{ notice }}</a-alert>

      <a-skeleton animation :loading="loading" class="store-spin">
        <StoreStackSkeleton :count="3" :show-action="false" />
        <template #content>
          <a-empty v-if="data.length === 0" description="暂无提醒任务">
            <a-button type="primary" class="primary-btn" @click="editAccount()">添加第一个任务</a-button>
          </a-empty>

          <div v-else class="account-list">
          <article
            v-for="record in data"
            :key="record.id"
            class="account-card"
            :class="{ 'account-card--low': isLowBalance(record) }"
          >
            <div class="account-card__head">
              <div class="account-card__location">
                <icon-home class="loc-icon" />
                <span>{{ record.area }} · {{ record.building }} · {{ record.room }}</span>
              </div>
              <!-- <a-tag color="arcoblue" size="small">
                扣费时间 {{ record.koufei_date || '-' }}
              </a-tag> -->
            </div>

            <div class="account-card__stats">
              <div class="stat" :class="{ 'stat--low': isLowBalance(record) }">
                <span class="stat__label">当前余额</span>
                <span class="stat__value">￥{{ record.balance }}</span>
              </div>
              <div class="stat">
                <span class="stat__label">提醒阈值</span>
                <span class="stat__value">￥{{ record.lowest }}</span>
              </div>
            </div>

            <div class="account-card__meta">
              <span><icon-email /> 通知邮箱：{{ record.email }}</span>
              <span><icon-clock-circle /> 更新时间：{{ formatTime(record.update_time) }}</span>
              <span><icon-clock-circle /> 扣费时间：{{ record.koufei_date || '-' }}</span>
            </div>

            <p v-if="record.notes" class="account-card__notes">{{ record.notes }}</p>

            <div class="account-card__actions">
              <a-button size="small" type="outline" @click="GetChangeRecord(record.id)">
                <template #icon><icon-select-all /></template>
                账单记录
              </a-button>
              <a-dropdown :popup-max-height="false" trigger="hover">
                <a-button size="small" type="text">
                  更多
                  <icon-down />
                </a-button>
                <template #content>
                  <a-doption @click="editAccount(record)"><icon-edit /> 编辑任务</a-doption>
                  <a-doption @click="DeleteAccount(record)"><icon-delete /> 删除任务</a-doption>
                </template>
              </a-dropdown>
            </div>
          </article>
          </div>
        </template>
      </a-skeleton>
    </div>
  </div>

  <a-modal
    v-model:visible="visible"
    :title="form.id ? '编辑电费提醒任务' : '添加电费提醒任务'"
    class="power-modal"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
    draggable
    :ok-loading="ok_loading"
    esc-to-close
    closable
  >
    <a-form :model="form" layout="vertical" class="power-form">
      <a-form-item field="area" label="校区" :loading="selectLoading">
        <a-select
          v-model="form.area"
          placeholder="请选择所在校区"
          :options="areas"
          @change="GetPowerData('dylist', form.area)"
        />
      </a-form-item>
      <a-form-item field="building" label="楼栋" :loading="selectLoading">
        <a-select
          v-model="form.building"
          placeholder="请选择所在楼栋"
          :options="buildings"
          @change="GetPowerData('mphlist', form.building)"
        />
      </a-form-item>
      <a-form-item field="room" label="宿舍号" :loading="selectLoading">
        <a-select v-model="form.room" placeholder="请选择所在宿舍" :options="rooms" />
      </a-form-item>
      <a-form-item field="lowest" label="提醒阈值（元）">
        <a-input-number v-model="form.lowest" placeholder="余额低于该值时发送邮件" :step="1" :precision="2" />
      </a-form-item>
      <a-form-item field="email" label="通知邮箱">
        <EmailAutoComplete v-model="form.email" placeholder="用于接收电费变更通知" allow-clear />
      </a-form-item>
      <a-form-item field="notes" label="备注">
        <a-textarea
          v-model="form.notes"
          no-trim
          placeholder="添加对账号的备注（非必填）"
          :max-length="{ length: 50 }"
          allow-clear
          show-word-limit
        />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal
    v-model:visible="listVisible"
    title="电费变更记录"
    class="power-modal power-modal--wide"
    esc-to-close
    closable
    width="auto"
    hide-cancel
  >
    <a-table
      :bordered="false"
      :data="changeList"
      :columns="listColumns"
      stripe
      hoverable
      :loading="listLoading"
      class="change-table"
      :scroll="{ x: 720 }"
      :pagination="{
        showPageSize: true,
        showJumper: true,
        showTotal: true,
        pageSize: pagination.pagesize,
        current: pagination.current,
        total: pagination.total
      }"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #time="{ record }">
        {{ formatTime(record.time) }}
      </template>
      <template #balance="{ record }">
        ￥{{ record.balance }}
      </template>
      <template #old_balance="{ record }">
        ￥{{ record.old_balance }}
      </template>
      <template #change="{ 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>
  </a-modal>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { getPowerData, addAccount, deleteAccount, getAccount, getChangeRecord } from '@/api/power'
import { Modal, Notification, Message } from '@arco-design/web-vue'
import { useRoute } from 'vue-router'
import { getNotice } from '@/utils/util'
import { formatStoreTimeFull } from '@/utils/storeFormat'
import StoreStackSkeleton from '@/components/skeleton/StoreStackSkeleton.vue'

const notice = ref('')

const GetNotice = async () => {
  const { path } = useRoute()
  notice.value = await getNotice(path)
}

const data = ref([])
const loading = ref(false)

const formatTime = (time) => formatStoreTimeFull(time)

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

const listVisible = ref(false)
const pagination = reactive({
  total: 0,
  current: 1,
  pagesize: 15
})

const handlePageChange = (page) => {
  pagination.current = page
}

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

const changeList = ref([])
const listLoading = ref(false)

const listColumns = [
  { title: '记录时间', slotName: 'time', width: 170, ellipsis: true, tooltip: true },
  { title: '扣费时间', dataIndex: 'change_time', width: 170, ellipsis: true, tooltip: true },
  { title: '电费余额', slotName: 'balance', width: 120, ellipsis: true, tooltip: true },
  { title: '原余额', slotName: 'old_balance', width: 120, ellipsis: true, tooltip: true },
  { title: '变动金额', slotName: 'change', width: 120, ellipsis: true, tooltip: true }
]

const GetChangeRecord = async (id) => {
  try {
    listLoading.value = true
    pagination.current = 1
    listVisible.value = true
    changeList.value = []
    const res = await getChangeRecord({ id })
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取电费变更记录失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    const rows = Array.isArray(res.data) ? res.data : res.data?.list ?? []
    changeList.value = rows
    pagination.total = res.pagination?.total ?? rows.length
  } catch (error) {
    Notification.error({
      title: '获取电费变更记录失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    listLoading.value = false
  }
}

const visible = ref(false)
const ok_loading = ref(false)
const form = reactive({
  id: null,
  area: '',
  building: '',
  room: '',
  email: '',
  notes: '',
  lowest: 10.0
})

const selectLoading = ref(false)
const areas = ref([])
const buildings = ref([])
const rooms = ref([])

const GetPowerData = async (type, pid = '') => {
  try {
    const payload = { type, pid }
    const res = await getPowerData(payload)
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取电费信息失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    const resdata = res.data.map((item) => ({
      value: item,
      label: item
    }))
    switch (type) {
      case 'buildlist':
        areas.value = resdata
        break
      case 'dylist':
        buildings.value = resdata
        form.building = ''
        form.room = ''
        break
      case 'mphlist':
        rooms.value = resdata
        form.room = ''
        break
    }
  } catch (error) {
    Notification.error({
      title: '获取电费信息失败',
      content: error.message || '请稍后再试'
    })
  }
}

const editAccount = (item) => {
  if (item) {
    form.id = item.id
    form.area = item.area
    form.building = item.building
    form.room = item.room
    form.email = item.email
    form.notes = item.notes
    form.lowest = Number(item.lowest) ?? 10.0
    if (form.area) GetPowerData('dylist', form.area)
    if (form.building) GetPowerData('mphlist', form.building)
  } else {
    form.id = null
    form.area = ''
    form.building = ''
    form.room = ''
    form.email = ''
    form.notes = ''
    form.lowest = 10.0
  }
  visible.value = true
}

const handleBeforeOk = async (done) => {
  try {
    ok_loading.value = true
    const { area, building, room, email } = form
    if (!area || !building || !room || !email) {
      Message.error('请填写完整的任务信息')
      return false
    }

    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    if (!emailRegex.test(email)) {
      Message.error('请检查邮箱格式是否正确')
      return false
    }

    const res = await addAccount({ ...form })
    if (!res || res.code !== 0) {
      Notification.error({
        title: '保存电费提醒任务失败',
        content: res?.msg ?? '请稍后再试'
      })
      return false
    }

    Message.success('保存成功')
    done()
    getAccounts()
  } catch (error) {
    Notification.error({
      title: '保存电费提醒任务失败',
      content: error.message || '请稍后再试'
    })
    return false
  } finally {
    ok_loading.value = false
  }
}

const handleCancel = () => {
  visible.value = false
}

const getAccounts = async () => {
  try {
    loading.value = true
    const res = await getAccount()
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取账号列表失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    data.value = res.data
  } catch (error) {
    Notification.error({
      title: '获取账号列表失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

const DeleteAccount = async (item) => {
  Modal.confirm({
    title: '删除任务',
    content: () =>
      h('div', [h('p', '您是否要删除该电费提醒任务？该操作不可逆')]),
    onOk: async () => {
      const res = await deleteAccount({ id: item.id })
      if (!res || res.code !== 0) {
        return Notification.error({
          title: '删除失败',
          content: res?.msg ?? '请稍后再试'
        })
      }
      Message.success('删除成功')
      getAccounts()
    }
  })
}

onMounted(() => {
  GetPowerData('buildlist')
  getAccounts()
  GetNotice()
})
</script>

<style lang="less" scoped>
@import '@/styles/store-theme.less';

.page-header {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 20px;
}

.primary-btn {
  border-radius: 999px;
  background: @store-primary !important;
  border-color: @store-primary !important;
}

.notice {
  margin-bottom: 16px;
  border-radius: @store-radius-sm;
}

.account-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.account-card {
  width: 100%;
  box-sizing: border-box;
  background: @store-card-bg;
  border: 1px solid @store-card-border;
  border-radius: @store-radius;
  padding: 16px 20px;
  transition: box-shadow 0.2s, border-color 0.2s;

  &:hover {
    box-shadow: @store-shadow;
    border-color: fade(@store-accent, 40%);
  }

  &--low {
    border-color: rgba(245, 63, 63, 0.35);
    background: linear-gradient(135deg, #fff 0%, #fff8f6 100%);
  }

  &__head {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 14px;
  }

  &__location {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 1.05rem;
    font-weight: 600;
    color: @store-primary;

    .loc-icon {
      color: @store-accent;
      font-size: 1.1rem;
      flex-shrink: 0;
    }
  }

  &__stats {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    margin-bottom: 12px;

    @media (min-width: 520px) {
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }
  }

  &__meta {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    font-size: 0.85rem;
    color: @store-text-muted;

    span {
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }
  }

  &__notes {
    margin: 10px 0 0;
    font-size: 0.85rem;
    color: @store-text-muted;
    padding: 8px 12px;
    background: @store-bg;
    border-radius: @store-radius-sm;
  }

  &__actions {
    margin-top: 14px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 8px;
  }
}

.stat {
  padding: 10px 12px;
  background: @store-bg;
  border-radius: @store-radius-sm;

  &__label {
    display: block;
    font-size: 0.75rem;
    color: @store-text-muted;
    margin-bottom: 4px;
  }

  &__value {
    font-size: 0.95rem;
    font-weight: 600;
    color: @store-primary;
  }

  &--low {
    background: #fff5f5;

    .stat__value {
      color: rgb(var(--red-6));
    }
  }
}
</style>

<style lang="less">
@import '@/styles/store-theme.less';

.power-modal {
  .arco-modal-header {
    border-bottom: 1px solid @store-card-border;
  }

  .arco-btn-primary {
    background: @store-primary;
    border-color: @store-primary;
  }
}

.power-modal--wide .arco-modal-body {
  max-width: min(92vw, 720px);
}

.change-table {
  .arco-table-th {
    background: @store-bg;
    color: @store-primary;
  }
}
</style>
