<template>
  <div class="communityPage">
    <div class="searchBar">
      <a-form layout="inline" @keydown.enter="searchHandler">
        <a-form-item label="事件类型" name="eventType">
          <a-select
            v-model:value="searchState.eventType"
            :options="eventTypeList"
            placeholder="请选择"
            style="width: 150px"
          />
        </a-form-item>

        <a-form-item label="是否启用">
          <a-select
            v-model:value="searchState.enable"
            style="width: 120px"
            :options="enableOptions"
            @change="searchHandler"
          />
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" @click="searchHandler"> 搜索 </a-button>
            <a-button @click="resetHandler"> 重置 </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <div class="tableCard">
      <div class="tableCard-header">
        <div class="tableCard-header-title">告警模板列表</div>
        <div class="tableCard-header-extra">
          <a-space>
            <a-button type="primary" @click="addTemplateHandler">添加模板</a-button>
          </a-space>
        </div>
      </div>
      <a-table
        :columns="columns"
        :data-source="listData"
        :loading="loading"
        :pagination="false"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'time'">
            <div>{{ record.createTime }}</div>
            <div>{{ record.updateTime }}</div>
          </template>

          <template v-if="column.key === 'eventType'">
            {{ record.eventTypeName }}
          </template>

          <template v-if="column.key === 'enable'">
            <a-popconfirm
              :title="`确认${record.isEnable ? '禁用' : '启用'}模板吗？`"
              ok-text="确认"
              cancel-text="取消"
              @confirm="swtichTemplateHandler(record.id, record.enable, record)"
            >
              <a-switch :checked="record.isEnable" />
            </a-popconfirm>
          </template>

          <template v-if="column.key === 'action'">
            <a-button type="link" @click="editTemplateHandler(record)">编辑</a-button>
            <a-popconfirm
              title="确认删除模板吗？"
              ok-text="确认"
              cancel-text="取消"
              @confirm="deleteTemplateHandler(record.id)"
            >
              <a-button type="link">删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>

      <base-pagination
        v-if="listTotal > 0"
        v-model:current="current"
        v-model:pageSize="pageSize"
        :total="listTotal"
        @change="paginationChange"
        @showSizeChange="paginationSizeChange"
      ></base-pagination>
    </div>

    <alarmPlanModal
      v-if="alarmPlanVisible"
      v-model:open="alarmPlanVisible"
      :title="alarmPlanTitle"
      type="template"
      :alarm-plan-id="alarmPlanId"
      :data="alarmPlanDataWithType"
      :area="{
        width: 400,
        height: 400,
        ranges: [-200, 200, -200, 200],
      }"
      @success="fetchList"
    ></alarmPlanModal>
  </div>
</template>

<script setup lang="ts">
import { ref, onActivated, computed } from 'vue'
import { columns, enableOptions } from './const'
import { useSearch } from '@/hooks/useSearch'
// import { useRouter } from 'vue-router'
import * as alarmApi from '@/api/alarm'
import type { AlarmPlanTemplateItem } from '@/api/alarm/types'
import alarmPlanModal from '@/views/device/detail/components/alarmPlanModal/index.vue'
import { message } from 'ant-design-vue'
import { useDictName } from '@/hooks/useDictName'

// const router = useRouter()

defineOptions({
  name: 'AlarmTemplateIndex',
})

interface SearchData {
  eventType: number | null // 事件类型
  enable: SwitchType | null // 是否启用
}
// 默认搜索条件
const defaultSearch: SearchData = {
  eventType: null,
  enable: null,
}

const [searchState, resetHandler] = useSearch(defaultSearch, { afterReset: () => searchHandler() })

const listData = ref<AlarmPlanTemplateItem[]>()
const listTotal = ref<number>(0)
const current = ref<number>(1)
const pageSize = ref<number>(10)

// 分页变化
const paginationChange = (current: number, pageSize: number) => {
  console.log('change', current, pageSize)
  fetchList()
}
// 分页大小变化
const paginationSizeChange = (current: number, pageSize: number) => {
  console.log('showSizeChange', current, pageSize)
}

const eventTypeList = ref<{ label: string; value: string }[]>([])
// 获取事件类型下拉列表
const fetchEventTypeList = async () => {
  try {
    const res = await alarmApi.getAlarmEventTypeList()
    console.log('获取事件类型下拉列表成功✅', res)
    const data = res.data
    eventTypeList.value =
      (Array.isArray(data) &&
        data.map((item) => ({
          label: item.eventDesc,
          value: item.eventVal,
        }))) ||
      []
  } catch (err) {
    console.log('获取事件类型下拉列表失败❌', err)
  }
}

const { dictNameMap: alarmEventTypeName } = useDictName(eventTypeList)

const loading = ref(false)
// 获取列表
const fetchList = async () => {
  try {
    loading.value = true
    await alarmApi
      .getAlarmPlanTemplateList({
        pageNo: current.value,
        pageSize: pageSize.value,
        enable: searchState.enable,
        eventVal: searchState.eventType,
      })
      .then((res) => {
        console.log('获取告警计划模板成功✅', res)
        const { rows, total } = res.data
        try {
          listData.value =
            rows &&
            rows.map((item) => ({
              ...item,
              isEnable: item.enable === 1 ? true : false,
              eventTypeName: alarmEventTypeName(item.eventVal),
            }))
        } catch (err) {
          console.log('获取告警计划模板失败❌', err)
        }
        listTotal.value = Number(total)
        loading.value = false
      })
      .catch((err) => {
        console.log('获取告警计划模板失败❌', err)
        loading.value = false
      })
  } catch (err) {
    console.log('获取告警计划列表失败❌', err)
  }
}

// 搜索
const searchHandler = async () => {
  console.log('searchState', searchState)
  current.value = 1
  pageSize.value = 10
  await fetchList()
}

const alarmPlanVisible = ref(false) // 告警计划弹窗
const alarmPlanId = ref<number | null>(null) // 当前编辑的告警计划id
const alarmPlanTitle = ref<string>('添加告警计划')

type AlarmPlan = {
  id: number
  uuid: ID
  name: string
  clientId: string
  enable: SwitchType
  region: string
  eventVal: number
  alarmTimePlanId: ID
  thresholdTime: ID
  mergeTime: ID
  param: string
  createTime: string
  updateTime: string
  remark: string | null
  alarmTimePlan: {
    createId: ID
    updateId: ID
    createTime: ID
    updateTime: ID
    isDeleted: SwitchType | null
    remark: ID
    id: ID
    startDate: string
    stopDate: string
    timeRange: string
    monthDays: string
    weekdays: string
  }
}

interface AlarmPlanItem {
  id?: number
  loading?: boolean
  [key: string]: unknown
}
const alarmPlanData = ref<AlarmPlanItem | undefined>(undefined)
const alarmPlanDataWithType = computed(() => alarmPlanData.value as AlarmPlan)

// 添加告警模板
const addTemplateHandler = () => {
  console.log('addTemplateHandler')
  alarmPlanVisible.value = true
  alarmPlanTitle.value = '添加告警模板'
  alarmPlanData.value = undefined
  alarmPlanId.value = null
}

// 编辑告警模板
const editTemplateHandler = async (item: AlarmPlanItem) => {
  console.log('editTemplateHandler', item)
  alarmPlanVisible.value = true
  alarmPlanTitle.value = '编辑告警模板'
  alarmPlanData.value = item
  alarmPlanId.value = item?.id ?? null
}

// 删除告警模板
const deleteTemplateHandler = async (id: number) => {
  console.log('deleteTemplateHandler', id)
  try {
    alarmApi.deleteAlarmPlanTemplate({ id }).then(() => {
      message.success('删除成功')
      fetchList()
    })
  } catch (err) {
    console.log('删除告警计划失败❌', err)
    message.error('删除失败')
  }
}

// 启用/禁用告警计划
const swtichTemplateHandler = async (id: number, swtich: boolean, item: AlarmPlanItem) => {
  console.log('swtichTemplateHandler', id, swtich, item)
  try {
    item.loading = true
    alarmApi
      .enableAlarmPlanTemplate({ id, enable: Number(!swtich) as 0 | 1 })
      .then(() => {
        message.success('变更成功')
        item.loading = false
        fetchList()
      })
      .catch((err) => {
        console.log('启用/禁用告警计划失败❌', err)
        item.loading = false
        message.error('操作失败')
      })
  } catch (err) {
    console.log('启用/禁用告警计划失败❌', err)
    message.error('变更失败')
  }
}

onActivated(async () => {
  await fetchEventTypeList().catch((err) => {
    console.error('fetchEventTypeList 失败', err)
  })

  await fetchList().catch((err) => {
    console.error('fetchList 失败', err)
  })
})
</script>

<style scoped lang="less">
.communityPage {
  .searchBar {
    padding: 20px;
    background-color: #fff;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    .ant-form {
      flex-grow: 1;
    }
    :deep(.ant-form-inline .ant-form-item) {
      margin-bottom: 16px !important;
    }
  }

  .tableCard {
    background-color: #fff;

    &-header {
      display: flex;
      justify-content: space-between;
      padding: 20px;
      &-title {
        font-size: 18px;
        font-weight: 600;
      }
    }
  }
}
</style>
