<!-- 供暖监测/热水监测 -->
<script lang="ts" setup name="network">
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import editList from './pageAdd.vue'
import { deleteCarbonOtherMonitor, getCarbonOtherMonitor } from '@/api/api/index'
import { templateDownload, templateExport, templateImport } from '@/api/api/electricity'
import { exportFile } from '@/utils/exportUtils'
import { download } from '@/utils/download'
import { getDictByCode } from '@/api/system/dict'
const props = defineProps({
  // 根据type发送不同请求
  type: {
    type: String,
    default: '0',
  },
})

// 查询参数
const searchQuery = reactive({
  offset: 1,
  limit: 20,
  startTime: '',
  endTime: '',
  deviceClassify: '',
  deviceNo: '',
})
const deviceTypeList = ref([])
// 获取设备类型列表
const getdeviceTypeList = () => {
  getDictByCode('device_type').then((res) => {
    deviceTypeList.value = res.data
  })
}
getdeviceTypeList()
// 查询时间段范围
const TimeRanges = ref()
// 监听时间段范围
watch(() => TimeRanges.value, (newVal: string[]) => {
  if (newVal && newVal.length) {
    searchQuery.startTime = newVal[0]
    searchQuery.endTime = newVal[1]
  }
}, { deep: true })
const loadingTable = ref(true)
const columns = ref([
  { text: '设备类型', value: 'deviceTypeName', align: 'center' },
  { text: '设备编号', value: 'deviceNo', align: 'center' },
  { text: '安装位置', value: 'installLocaltion', align: 'center' },
  { text: props.type === '0' ? '负荷有功功率(MW)' : '数值', value: props.type === '0' ? 'pd' : 'monitorVal', align: 'center' },
  { text: props.type === '0' ? '负荷无功功率(MW)' : '单位', value: props.type === '0' ? 'qd' : 'monitorUnit', align: 'center' },
  { text: '上传时间', value: 'createTime', align: 'center' },
]) // 表格
const total = ref<number>(0)
const list = ref<any[]>([])
// 搜索
const search = () => {
  list.value = []
  loadingTable.value = true
  getCarbonOtherMonitor(searchQuery).then((res) => {
    list.value = res.data.rows
    total.value = res.data.total
    loadingTable.value = false
  })
}
// 重置
const reset = () => {
  searchQuery.offset = 1
  searchQuery.limit = 20
  searchQuery.startTime = ''
  searchQuery.endTime = ''
  searchQuery.deviceNo = ''
  search()
}
// 新增或编辑组件
const editRef = ref()
// 新增
const add = () => {
  editRef.value.initDialog('create', { type: props.type })
}
// 编辑
const edit = (row: any) => {
  editRef.value.initDialog('update', { ...row, type: props.type })
}
// 删除
const del = (row: any) => {
  console.log(row, 'row')
  ElMessageBox.confirm(
    '确认删除选中的数据吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      deleteCarbonOtherMonitor(row.id).then((res) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        search()
      })
    })
    .catch(() => {
    })
}
// 导出
const exportFun = () => {
  if (searchQuery.startTime && searchQuery.endTime && searchQuery.deviceNo) {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(255, 255, 255, 0.8)',
    })
    templateExport({ ...searchQuery, offset: undefined, limit: undefined }).then((res) => {
      let flag = ''
      searchQuery.deviceClassify === '0' ? flag = '用电' : searchQuery.deviceClassify === '1' ? flag = '用热' : searchQuery.deviceClassify === '2' ? flag = '用气' : flag = ''
      exportFile(res.data, `${searchQuery.deviceNo}${flag}设备采集日志`)
      loading.close()
    }).catch((_) => {
      loading.close()
    })
  }
  else {
    ElMessage.warning('请先选择时间范围或设备编号')
  }
}
// 导入
const fileRef = ref() // 文件上传input
const importFun = () => {
  fileRef.value.click()
}
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    const file = event.target.files[0]
    const fd = new FormData()
    fd.append('deviceClassify', searchQuery.deviceClassify)
    fd.append('file', file)
    templateImport(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    }).catch(() => {
      loading.close()
    })
  }
}
// 模板下载
const downloadFun = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  templateDownload(searchQuery.deviceClassify).then((res) => {
    let flag = ''
    searchQuery.deviceClassify === '0' ? flag = '用电' : searchQuery.deviceClassify === '1' ? flag = '用热' : searchQuery.deviceClassify === '2' ? flag = '用气' : flag = ''
    exportFile(res.data, `${flag}采集日志模板`)
    loading.close()
  }).catch((_) => {
    loading.close()
  })
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.limit = val.size
  }
  if (val && val.page) {
    searchQuery.offset = val.page
  }
  search()
}
// 表格被选中的行
const selectList = ref<any[]>([])
// 表格多选
const multiSelect = (row: any[]) => {
  selectList.value = row
}
onMounted(() => {
  if (searchQuery.deviceClassify) {
    search()
  }
})
watch(() => props.type, (newVal) => {
  searchQuery.deviceClassify = newVal
  if (newVal) {
    search()
  }
}, {
  immediate: true,
})
</script>

<template>
  <div>
    <edit-list ref="editRef" @refresh="search" />
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.deviceNo" placeholder="设备编号" clearable class="w-50 m-2 normal-input" />
      </search-item>
      <!-- <search-item>
        <el-select v-model="searchQuery.deviceType" placeholder="设备类型">
          <el-option v-for="item in deviceTypeList" :key="item.id" :value="item.value" :label="item.name" />
        </el-select>
      </search-item> -->
      <!-- <search-item>
        <el-select v-model="searchQuery.deviceType" placeholder="监测类别">
          <el-option :value="1" label="1" />
        </el-select>
      </search-item> -->
      <search-item>
        <el-date-picker
          v-model="TimeRanges" type="datetimerange" format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss" range-separator="至" start-placeholder="上传开始时间" end-placeholder="上传结束时间"
          clearable
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <!-- 3D7EFF -->
        <icon-button icon="icon-add" title="新增" @click="add" />
        <icon-button icon="icon-export" title="导出" @click="exportFun" />
        <icon-button icon="import" title="导入" @click="importFun" />
        <icon-button icon="download" title="模板下载" @click="downloadFun" />
        <input v-show="false" ref="fileRef" type="file" @change="onFileChange">
      </template>
      <!-- 表格区域 -->
      <normal-table
        :data="list" :total="total" :columns="columns as any"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }" :list-loading="loadingTable"
        :is-showmulti-select="true" :is-multi="true" @change="changePage" @multiSelect="multiSelect"
      >
        <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 label="操作" align="center" width="120">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="edit(row)">
                修改
              </el-button>
              <el-button type="primary" link size="small" @click="del(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </div>
</template>

