<!-- 点位列表 -->
<script name="LocateList" lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IDictType } from '../common-interface'
import type { IDeviceInfo, IListQuery } from './locate-info'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import { exportFile } from '@/utils/exportUtils'
import { getLocateList } from '@/api/basic/locate'

const router = useRouter()

// 分组列表
const groupList = ref<Array<IGroupInfo>>([])

// 查询条件
const searchQuery = ref<IListQuery>({
  keywords: '', // 分组
  offset: 1,
  limit: 20,
})
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '点位编号', value: 'wellCode', align: 'center', width: '160' },
  { text: '点位名称', value: 'wellName', align: 'center', width: '160' },
  { text: '具体位置', value: 'position', align: 'center' },
  { text: '责任部门', value: 'responsibleDept', align: 'center', width: '160' },
  { text: '责任人', value: 'staff', align: 'center', width: '160' },
  { text: '联系电话', value: 'tel', align: 'center', width: '160' },
  { text: '点位类型', value: 'wellTypeName', align: 'center', width: '100' },
  { text: '最新数据', value: 'dataValue', align: 'center' },
  { text: '最新上线时间', value: 'logtime', align: 'center', width: '180' },
])
const dataList = ref<Array<IDeviceInfo>>([]) // 表格数据

const deviceTypeDict = ref<Array<IDictType>>([])

// 逻辑
// 导出所有
const exportAllDevice = () => {
  if (dataList.value.length > 0) {
    const filename = `设备列表${new Date().valueOf()}.xlsx`

    const loading = ElLoading.service({
      lock: true,
      text: '下载中请稍后',
      background: 'rgba(255, 255, 255, 0.8)',
    })

    // 导出接口
    exportDevice(searchQuery.value).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, filename)

      nextTick(() => {
        // 关闭loading
        loading.close()
      })
    }).catch(() => {
      loading.close()
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
}

// 详情
const detail = (row: IDeviceInfo) => {
  router.push({
    query: {
      type: 'detail',
      id: row.id,
    },
    path: 'detail',
  })
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getLocateList(searchQuery.value).then((response) => {
    if (response.code === 200) {
      dataList.value = response.data.rows.map((item: IDeviceInfo) => {
        return {
          ...item,
        }
      })
      total.value = parseInt(response.data.total)
    }
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

const searchList = () => {
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData(true)
}

// 重置
const reset = () => {
  searchQuery.value = {
    deptid: '',
    keywords: '', // 分组
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}

// 删除
const deleteById = (row: IDeviceInfo) => {
  ElMessageBox.confirm(`是否删除设备 ${row.devcode}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delDevice(row.id).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`设备 ${row.devcode} 删除成功`)
        searchList()
      }
      else {
        ElMessage.error(`设备 ${row.devcode} 删除失败: ${res.message}`)
      }
    })
  })
}

// 获取在用状态字典值
const getStatusDict = async () => {
  getDictByCode('onlineStatus').then((res: any) => {
    if (res.code === 200) {
      statusDict.value = res.data
      sessionStorage.setItem('onlineStatus', JSON.stringify(statusDict.value))
    }
  })
}
const getLocateTypeDict = async () => {
  getDictByCode('deviceType').then((res: any) => {
    if (res.code === 200) {
      deviceTypeDict.value = res.data
      sessionStorage.setItem('deviceType', JSON.stringify(deviceTypeDict.value))
    }
  })
}

const getDict = async () => {
  await getStatusDict()
  await getLocateTypeDict()
}

onMounted(async () => {
  await getDict()
  searchList()
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-form-item class="selectForm-container-item" prop="keywords">
          <el-input v-model.trim="searchQuery.keywords" placeholder="点位编号" clearable />
        </el-form-item>
      </search-item>
    </search-area>

    <!-- 表格数据展示 -->
    <table-container title="点位列表">
      <!-- 表头区域 -->
      <template #btns-right>
        <el-button type="primary" @click="exportDevice">
          批量下发配置
        </el-button>
        <el-button type="primary" @click="exportAllDevice">
          导出列表
        </el-button>
      </template>

      <!-- 表格区域 -->
      <normal-table
        :data="dataList" :columns="columns" :total="total"
        :query="searchQuery" :list-loading="loadingTable"
        @change="changePage"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (searchQuery.offset! - 1) * searchQuery.limit! + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>

        <template #columns>
          <el-table-column fixed="right" label="操作" align="center" width="130">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="detail(row)">
                查看
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
