<script setup lang="ts">
  import {DeviceAbnormalRecord} from "@/api/deviceAbnormalRecord.ts";
  import {DataTableColumns, NButton, NDataTable, NIcon, NSpace, NTag} from "naive-ui";
  import {h, onMounted, reactive, ref} from "vue";
  import {dictDataApi} from "@/api/org.ts";
  import {ArrowDown, ArrowUp, RefreshOutline, SearchOutline} from "@vicons/ionicons5";
  import {deviceAbnormalRecordApi} from "@/api/deviceAbnormalRecord.ts";


  const deviceNormalRecordOptions =  ref<{ label: string; value: any;class:any }[]>([])

  const props =  defineProps({
    deviceId:Number
  })

  const showSearchInput = ref<Boolean>(false)


  const searchForm = ref({
    abnormalCode: undefined,
    abnormalType: undefined
  })

  const abnormalTypes = [
      {
        label: '机械异常',
        value: '0'
      },
      {
        label: '电气异常',
        value: '1'
      },
      {
        label: '软件异常',
        value: '2'
      },
      {
        label: '其他异常',
        value: '3'
      }
  ]

  const pagination = reactive({
    page: 1,
    pageSize: 10,
    itemCount: 0,
    showSizePicker: true,
    pageSizes: [10, 20, 50]
  })

  //报警异常字典
  const deviceAbnormalTypeOptions = ref<{ label: string; value: any;class:any }[]>( [])

  //异常级别字典
  const deviceAbnormalLevelOptions = ref<{ label: string; value: any;class:any }[]>( [])

  //汇报信息表格
  const columns:DataTableColumns<DeviceAbnormalRecord> = [

    { title: '报警异常', key: 'abnormalType',align: 'center',
      render(row) {
        const val = row.abnormalType
        const opt = deviceAbnormalTypeOptions.value.find(o => o.value === val || String(o.value) === String(val))
        if (!opt) return val ?? '-'
        return h(NTag, { type: opt.class, size: 'small' }, { default: () => opt.label })
      }
    },
    { title: '异常级别', key: 'abnormalLevel',align: 'center',
      render(row) {
        const val = row.abnormalLevel
        const opt = deviceAbnormalLevelOptions.value.find(o => o.value === val || String(o.value) === String(val))
        if (!opt) return val ?? '-'
        return h(NTag, { type: opt.class, size: 'small' }, { default: () => opt.label })
      }
    },
    { title: '异常描述', key: 'abnormalDesc',align: 'center' },
    { title: '异常时间', key: 'abnormalTime',align: 'center' },
    { title: '处理状态', key: 'status',align: 'center',
      render(row) {
        const val = row.status
        const opt = deviceNormalRecordOptions.value.find(o => o.value === val || String(o.value) === String(val))
        if (!opt) return val ?? '-'
        return h(NTag, { type: opt.class, size: 'small' }, { default: () => opt.label })
      }
    },
    { title: '检验完成时间', key: 'inspectTime',align: 'center' },
  ]

  async function loadDictOptions() {
    try {
      const data = await dictDataApi.listByType('device_abnormal_status')
      deviceNormalRecordOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class: d.listClass }))
    }catch {}

    try {
      const data = await dictDataApi.listByType('abnormal_type')
      deviceAbnormalTypeOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class: d.listClass }))
    }catch {}
    try {
      const data = await dictDataApi.listByType('abnormal_level')
      deviceAbnormalLevelOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class: d.listClass }))
    }catch {}
  }


  const data = ref([])
  const load = async() => {
    try {
      const res = await deviceAbnormalRecordApi.page({
        page: pagination.page,
        pageSize: pagination.pageSize,
        deviceId: props.deviceId,
        abnormalCode: searchForm.value.abnormalCode,
        abnormalType: searchForm.value.abnormalType,
      })
      data.value = res.list
      pagination.itemCount = res.total
    } catch (e) {}
  }

  const doShowInner = () => {
    if (showSearchInput.value) {
      showSearchInput.value = false
    }else {
      showSearchInput.value = true
    }
  }

  const handleSearch =  () => {
    load()
  }

  const handleReset = () => {
    searchForm.value.abnormalType = null
    searchForm.value.abnormalCode = null
    pagination.page = 1
    pagination.pageSize = 10
    load()
  }


  // 分页
  function handlePageChange(page: number) {
    pagination.page = page
    load()
  }

  function handlePageSizeChange(pageSize: number) {
    pagination.pageSize = pageSize
    pagination.page = 1
    load()
  }


  onMounted(()=>{
    load()
    loadDictOptions()
  })
</script>

<template>
  <div>
    <n-button @click="doShowInner" v-if="showSearchInput">
      <n-icon size="20" :depth="3">
        <ArrowDown/>
      </n-icon>
      展开
    </n-button>
    <n-card v-if="!showSearchInput">
      <n-form inline :model="searchForm" label-placement="left">
        <n-grid :x-gap="8" :cols="4">
          <n-gi>
            <n-form-item label="异常编号">
              <n-input v-model:value="searchForm.abnormalCode" placeholder="请输入异常编号" clearable style="width: 200px"/>
            </n-form-item>
          </n-gi>
          <n-gi>
            <n-form-item label="操作人员">
              <n-select
                  v-model:value="searchForm.abnormalType"
                  :options="abnormalTypes"
                  placeholder="请选择异常类型"
                  clearable
                  style="width: 200px"
              />
            </n-form-item>
          </n-gi>
          <n-gi>
            <n-form-item>
              <n-space>
                <n-button type="primary" @click="handleSearch">
                  <template #icon>
                    <n-icon>
                      <SearchOutline/>
                    </n-icon>
                  </template>
                  搜索
                </n-button>
                <n-button @click="handleReset">
                  <template #icon>
                    <n-icon>
                      <RefreshOutline/>
                    </n-icon>
                  </template>
                  重置
                </n-button>
              </n-space>
            </n-form-item>
          </n-gi>
        </n-grid>


      </n-form>
      <n-button @click="doShowInner" v-if="!showSearchInput" style="float: right;margin: 10px">
        <n-icon size="20" :depth="3">
          <ArrowUp/>
        </n-icon>
        闭合
      </n-button>
    </n-card>
    <n-card style="margin: 20px 0">
      <n-data-table
          :columns="columns"
          :data="data"
          :bordered="false"
      />

      <div class="pagination-container" style="display: flex; justify-content: flex-end; margin-top: 12px">
        <n-pagination
            v-model:page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :item-count="pagination.itemCount"
            :page-sizes="[10, 20, 50, 100]"
            show-size-picker
            show-quick-jumper
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
        >
          <template #prefix>
            共 {{ pagination.itemCount }} 条
          </template>
        </n-pagination>
      </div>
    </n-card>
  </div>

</template>

<style scoped>

</style>