Newer
Older
smart-metering-front / src / views / device / standingBook / components / templatePage.vue
dutingting on 27 Feb 15 KB 需求更改、excel在线编辑
<!-- 设备台账公共模板 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { fixedAssetsParams, fixedAssetsType, selectType } from '../standingBook-interface'
import { printJSON } from '@/utils/printUtils'
import { getDictByCode } from '@/api/system/dict'
import { uploadApi } from '@/api/system/notice'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { assetsDeleteApi, listExportApi, listImportApi, listPageApi } from '@/api/device/standingBook'
import { exportFile } from '@/utils/exportUtils'
import scanEquipmentDialog from '@/components/scanEquipmentDialog/index.vue'
import useTemplateDownload from '@/utils/useTemplateDownload'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
const props = defineProps({
  /**
   * 页面名称
   */
  name: {
    type: String,
    default: '',
  },
  // 权限
  authority: {
    type: String,
    required: true,
  },
  // 是否测量设备
  assetType: {
    type: String,
    default: '',
  },
  // 是否固定资产
  isFixedAssets: {
    type: String,
    default: '',
  },
  // 是否是技术指标需要校准检定的设备
  isCalibrationTestEquipment: {
    type: String,
    default: '',
  },
  // 是否是技术指标需要校准检定的设备
  isMeasureAccount: {
    type: String,
    default: '',
  },
  // 是否是技术指标需要校准检定的设备
  isStandardSupportEquipment: {
    type: String,
    default: '',
  },
})
const scanEquipmentRef = ref() // 标签绑定弹窗ref
const $router = useRouter()
const { proxy } = getCurrentInstance() as any
const validDate = ref()
let searchQuery: fixedAssetsParams = reactive({
  equipmentNo: '', // 设备编号
  equipmentName: '', // 名称
  mesureType: '', // 检定方式
  managerState: '', // 管理状态
  useDept: '', // 使用部门
  assetType: '', // 资产类型
  equipmentCategory: '', // 设备类别
  isCalibrationTestEquipment: '', // 校准/检定设备
  isMeasureAccount: '', // 测量工装
  isStandardSupportEquipment: '', // 标准配套设备
  isFixedAssets: '', // 固定资产
  validDateStart: '', // 有效开始日期
  validDateEnd: '', // 有效结束日期
  abc: '',
  limit: 20,
  offset: 1,
  ids: [] as string[],
}) // 查询参数

// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, `device-standingBook-${props.name}`, searchQuery)
})
// 重新赋值
searchQuery = reactive(renewSearchParams(`device-standingBook-${props.name}`) || {
  equipmentNo: '', // 设备编号
  equipmentName: '', // 名称
  mesureType: '', // 检定方式
  managerState: '', // 管理状态
  useDept: '', // 使用部门
  assetType: '', // 资产类型
  equipmentCategory: '', // 设备类别
  isCalibrationTestEquipment: '', // 校准/检定设备
  isMeasureAccount: '', // 测量工装
  isStandardSupportEquipment: '', // 标准配套设备
  isFixedAssets: '', // 固定资产
  validDateStart: '', // 有效开始日期
  validDateEnd: '', // 有效结束日期
  abc: '',
  limit: 20,
  offset: 1,
  ids: [] as string[],
})
watch(() => searchQuery.abc, (newVal) => {
  if (!newVal) {
    searchQuery.abc = ''
  }
})
watch(() => validDate.value, (newVal) => {
  if (newVal) {
    searchQuery.validDateStart = newVal[0]
    searchQuery.validDateEnd = newVal[1]
  }
  else {
    searchQuery.validDateStart = ''
    searchQuery.validDateEnd = ''
  }
})
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref<TableColumn[]>([
  { text: '设备编号', value: 'equipmentNo', align: 'center', width: 160 },
  { text: '名称', value: 'equipmentName', align: 'center' },
  { text: '型号', value: 'modelNo', align: 'center' },
  { text: 'ABC', value: 'abc', align: 'center', width: 58 },
  // { text: '检定方式', value: 'mesureTypeName', align: 'center', width: 90 },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  // { text: '强制检定', value: 'compulsoryVerification', align: 'center', width: 65 },
  { text: '测量范围', value: 'mesureRange', align: 'center' },
  { text: '管理状态', value: 'managerStateName', align: 'center', width: 100 },
  { text: '使用部门', value: 'useDeptName', align: 'center' },
  // { text: '使用人', value: 'usePersonName', align: 'center' },
  { text: '溯源机构', value: 'mesureDeptName', align: 'center' },
  { text: '有效日期', value: 'validDate', align: 'center', width: 120 },
  // { text: '备注', value: 'remark', align: 'center' },
])

const list = ref<fixedAssetsType[]>([]) // 表格数据

// 获取数据
const useDeptList = ref([])
const mesureTypeList = ref<selectType[]>([])
const managerStateList = ref<selectType[]>([])
const abcList = ref<selectType[]>([])
const fetchData = () => {
  // 获取使用部门
  getDeptTreeList().then((res) => {
    if (res.data) { // 将列表转树结构
      useDeptList.value = toTreeList(res.data, '0', true)
    }
  })
  // 获取检定方式
  getDictByCode('measureType').then((response) => {
    mesureTypeList.value = response.data
  })
  // 获取管理状态
  getDictByCode('managerState').then((response) => {
    managerStateList.value = response.data
  })
  // 获取ABC
  getDictByCode('ABC').then((response) => {
    abcList.value = response.data
  })
}
// 获取数据列表
const getList = () => {
  loadingTable.value = true
  searchQuery.isCalibrationTestEquipment = props.isCalibrationTestEquipment
  searchQuery.isMeasureAccount = props.isMeasureAccount
  searchQuery.isStandardSupportEquipment = props.isStandardSupportEquipment
  if (props.name === '测量设备') {
    searchQuery.assetType = '1'
  }
  listPageApi(searchQuery).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows.map((item: any) => {
        item.validDate = item.validDate.split(' ')[0]
        return {
          ...item,
          validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : item.validDate,
          compulsoryVerification: item.compulsoryVerification === 1 ? '是' : item.compulsoryVerification === 0 ? '否' : '',
        }
      })
      total.value = res.data.total
    }
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}
// 页数发生变化后的操作,可能是页码变化,可能是每页容量变化,此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.limit = val.size
  }
  if (val && val.page) {
    searchQuery.offset = val.page
  }
  getList()
}
// 详情
const detail = (row: fixedAssetsType) => {
  $router.push({
    name: 'standingBookDetail',
    params: { type: 'detail' },
    query: { title: '详情', name: props.name, id: row.id },
  })
}
// 编辑
const update = (row: fixedAssetsType) => {
  $router.push({
    name: 'standingBookDetail',
    params: { type: 'edit' },
    query: { title: '编辑', name: props.name, id: row.id },
  })
}
// 删除
const remove = (row: fixedAssetsType) => {
  ElMessageBox.confirm(
    `确认删除${row.equipmentName}吗?`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      assetsDeleteApi({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          getList()
        }
      })
    })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  validDate.value = ''
  searchQuery.equipmentNo = '' // 设备编号
  searchQuery.equipmentName = ''
  searchQuery.mesureType = ''
  searchQuery.managerState = ''
  searchQuery.useDept = ''
  searchQuery.validDateStart = ''
  searchQuery.validDateEnd = ''
  searchQuery.abc = ''
  getList()
}

// 新增
const add = () => {
  $router.push({
    name: 'standingBookDetail',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: props.name,
    },
  })
}

// ---------------------------------------------扫描--------------------------------------
// 点击扫描收添加
const identify = () => {
  // 参数:不是标签绑定
  scanEquipmentRef.value.initDialog(false)
}
// --------------------------------------------------------------------------------------

// 表格被选中的行
const selectList = ref<fixedAssetsType[]>([])
// 表格多选
const multiSelect = (row: fixedAssetsType[]) => {
  selectList.value = row
}

// 打印列表
function printList() {
  const selectIds: string[] = selectList.value.map((item: fixedAssetsType) => item.id)
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (selectIds.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, props.name)
  }
  else if (selectIds.length > 0) {
    const printList = list.value.filter((item: fixedAssetsType) => selectIds.includes(item.id))
    printJSON(printList, properties, props.name)
  }
  else {
    ElMessage('无可打印内容')
  }
}
// 导出
const exportExcelBtn = () => {
  if (list.value.length === 0) {
    ElMessage.warning('无数据可导出数据')
    return
  }
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  const selectIds: string[] = selectList.value.map((item: fixedAssetsType) => item.id)
  const params = { ...searchQuery, ids: selectIds }
  console.log(params)
  listExportApi(params).then((res) => {
    const blob = new Blob([res.data])
    exportFile(blob, `${props.name}.xlsx`)
    loading.close()
  }).catch((_) => {
    loading.close()
  })
}
// 模板下载
const templateDownload = () => {
  useTemplateDownload('测量设备模块')
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  // if (event.target.files[0].type === 'application/pdf') {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    listImportApi(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('导入成功')
        getList()
        loading.close()
        event.target.value = ''
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
//   }
//   else {
//     ElMessage.warning('请上传pdf格式')
//   }
}
// 批量导入
const batchImport = () => {
  fileRef.value.click()
}
onMounted(() => {
  getList()
  fetchData()
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="searchQuery.equipmentNo" placeholder="设备编号" clearable class="w-50 m-2" style="width: 185px;" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.equipmentName" placeholder="名称" clearable class="w-50 m-2" style="width: 185px;" />
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.mesureType" class="m-2" placeholder="检定方式" clearable style="width: 185px;">
            <el-option
              v-for="item in mesureTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.managerState" class="m-2" placeholder="管理状态" clearable style="width: 185px;">
            <el-option
              v-for="item in managerStateList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <dept-select v-model="searchQuery.useDept" :data="useDeptList" placeholder="使用部门" style="width: 185px;" />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="validDate"
            type="daterange"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="有效开始日期"
            end-placeholder="有效结束日期"
            clearable
            style="width: 360px;"
          />
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.abc" class="m-2" placeholder="ABC" clearable style="width: 185px;">
            <el-option
              v-for="item in abcList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
      </search-area>
      <table-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <input v-show="(searchQuery.limit === 0)" ref="fileRef" type="file" multiple @change="onFileChange">
          <icon-button v-if="proxy.hasPerm(`/device/${$props.authority}/identify`)" icon="icon-device" title="标签识别" @click="identify" />
          <icon-button v-if="proxy.hasPerm(`/device/${$props.authority}/import`)" icon="icon-import" title="批量导入" @click="batchImport" />
          <icon-button v-if="proxy.hasPerm(`/device/${$props.authority}/mould`)" icon="icon-template" title="模板下载" @click="templateDownload" />
          <icon-button v-if="proxy.hasPerm(`/device/${$props.authority}/add`)" icon="icon-add" title="新建" @click="add" />
          <icon-button v-if="proxy.hasPerm(`/device/${$props.authority}/export`)" icon="icon-export" title="导出" @click="exportExcelBtn" />
          <icon-button v-if="proxy.hasPerm(`/device/${$props.authority}/print`)" icon="icon-print" title="打印" @click="printList" />
        </template>
        <!-- 表格区域 -->
        <normal-table
          id="print"
          :data="list" :total="total" :columns="columns"
          :is-showmulti-select="true"
          :query="searchQuery"
          :list-loading="loadingTable"
          :is-multi="true"
          :options="{ needIndex: true }"
          @change="changePage" @multi-select="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" fixed="right">
              <template #default="{ row }">
                <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/update`)" size="small" type="primary" link @click="update(row)">
                  编辑
                </el-button>
                <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/detail`)" size="small" type="primary" link @click="detail(row)">
                  详情
                </el-button>
                <el-button v-if="proxy.hasPerm(`/device/${$props.authority}/delete`)" size="small" type="danger" link @click="remove(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
      <scan-equipment-dialog ref="scanEquipmentRef" title="标签识别" />
    </app-container>
  </div>
</template>