<template>
  <div class="container">
    <Breadcrumb />

    <a-card title="定制电费提醒">
      <a-button type="primary" size="large" @click="editAccount()">
        <template #icon>
          <icon-plus />
        </template>
        添加提醒任务
      </a-button>

      <a-alert v-if="notice" style="margin-top: 15px;">{{ notice }}</a-alert>

      <a-table :data="data" :columns="columns" :bordered="false" hoverable class="table" :loading="loading" :scroll="{
        x: 1600
      }" :pagination="{ showPageSize: true, showJumper: true, defaultPageSize: 15 }">

        <template #name-filter="{ filterValue, setFilterValue, handleFilterConfirm, handleFilterReset }">
          <div class="custom-filter">
            <a-space direction="vertical">
              <a-input :model-value="filterValue[0]" @input="(value) => setFilterValue([value])" />
              <div class="custom-filter-footer">
                <a-button @click="handleFilterReset">重置</a-button>
                <a-button @click="handleFilterConfirm">确定</a-button>
              </div>
            </a-space>
          </div>
        </template>
        <template #balance="{ record }">
          <a-tag :color="record.balance <= record.lowest ? 'red' : 'green'">￥{{ record.balance
          }}</a-tag>
        </template>
        <template #lowest="{ record }">
          ￥{{ record.lowest }}
        </template>
        <template #update_time="{ record }">
          {{ stramptoTime(record.update_time) }}
        </template>
        <template #optional="{ record }">
          <div style="display: flex; gap:10px">
            <a-button @click="GetChangeRecord(record.id)">账单&nbsp;<icon-select-all /></a-button>
            <a-dropdown :popup-max-height="false" trigger="hover">
              <a-button>操作&nbsp;<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>
        </template>
      </a-table>
    </a-card>
  </div>

  <!-- 账号编辑对话框 -->
  <a-modal v-model:visible="visible" title="编辑电费提醒任务" @cancel="handleCancel" @before-ok="handleBeforeOk" draggable
    :ok-loading="ok_loading" esc-to-close closable>
    <a-form :model="form">
      <a-form-item field="area" label="校区" :loading="selectLoading">
        <a-select v-model="form.area" placeholder="请选择所在校区" default-value="" :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="请选择所在楼栋" default-value="" :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="请选择所在宿舍" default-value="" :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="电费变更记录" esc-to-close closable width="auto" hide-cancel>
    <a-table :bordered="false" :data="changeList" :columns="listColumns" stripe hoverable :loading="listLoading" :pagination="{
      showPageSize: true,
      showJumper: true,
      showTotal: true,
      pageSize: pagination.pagesize,
      current: pagination.current,
      total: pagination.total
    }" @page-change="handlePageChange" @page-size-change="handlePageSizeChange">
      <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
          - record.old_balance).toFixed(2)
        }}</a-tag>
      </template>
      <template #time="{ record }">
        {{ stramptoTime(record.time) }}
      </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'

const notice = ref('')

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

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

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 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 ?? '请稍后再试'
      })
    changeList.value = res.data
    pagination.total = res.data.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.00
})

const columns = [{
  title: '校区',
  dataIndex: 'area',
  width: 120
}, {
  title: '楼栋',
  dataIndex: 'building',
  width: 130
}, {
  title: '寝室号',
  dataIndex: 'room',
}, {
  title: '通知邮箱',
  dataIndex: 'email',
  width: 220
}, {
  title: '当前余额',
  slotName: 'balance',
  width: 120
}, {
  title: '触发提醒阈值',
  slotName: 'lowest',
  width: 120
}, {
  title: '扣费日期',
  dataIndex: 'koufei_date',
  width: 170
}, {
  title: '上次更新时间',
  slotName: 'update_time',
  width: 170
}, {
  title: '备注',
  dataIndex: 'notes'
}, {
  title: '操作',
  slotName: 'optional',
  width: 200,
  fixed: 'right'
}]

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

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

const GetPowerData = async (type, pid = '') => {
  try {
    const data = {
      type,
      pid
    }
    const res = await getPowerData(data)
    if (!res || res.code !== 0)
      return Notification.error({
        title: '获取电费信息失败！',
        content: res?.msg ?? '请稍后再试'
      })
    let 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.00
  } else {
    form.id = null
    form.area = ''
    form.building = ''
    form.room = ''
    form.email = ''
    form.notes = ''
    form.lowest = 10.00
  }
  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
    }

    let data = {
      ...form
    }

    const res = await addAccount(data)
    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()
    }
  })
}

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

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

</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.table {
  margin-top: 15px;

  .state {
    display: flex;
    align-items: center;

    .circle {
      border-radius: 50%;
      height: 8px;
      min-height: 8px;
      width: 8px;
      min-width: 8px;
      margin-right: 5px;
    }

    .zero {
      background-color: rgb(var(--orange-6));
    }

    .one {
      background-color: rgb(var(--green-6));
    }

    .else {
      background-color: rgb(var(--red-6));
    }
  }
}

.custom-filter {
  padding: 20px;
  background: var(--color-bg-5);
  border: 1px solid var(--color-neutral-3);
  border-radius: var(--border-radius-medium);
  box-shadow: 0 2px 5px rgb(0 0 0 / 10%);
}

.custom-filter-footer {
  display: flex;
  justify-content: space-between;
}
</style>