<!-- 固定资产页面 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
// import addDialog from './components/fixedAssetsAdd.vue'
import type { fixedAssetsType, selectType } from './standingBook-interface'
import { exportFile } from '@/utils/exportUtils'
import { printJSON } from '@/utils/printUtils'
import { assetsDeleteApi, listExportApi, listImporttApi, listPageApi } from '@/api/device/standingBook'
import { getDictByCode } from '@/api/system/dict'
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
const $route = useRoute()
const searchQuery = reactive({
  assetNo: '', // 固定编号
  equipmentName: '', // 设备名称
  modelNo: '', // 型号
  equipmentSpecifications: '', // 设备规格
  equipmentCategory: '', // 设备类型
  limit: 20,
  offset: 1,
  ids: [] as string[],
  isFixedAssets: '1',
}) // 查询参数
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref([
  { text: '固定资产编号', value: 'assetNo', align: 'center', width: 160 },
  { text: '设备名称', value: 'equipmentName', align: 'center' },
  { text: '型号', value: 'modelNo', align: 'center' },
  { text: '设备规格', value: 'equipmentSpecifications', align: 'center' },
  { text: '设备类别', value: 'equipmentCategoryName', align: 'center' },
  { text: '设备类型', value: 'equipmentTypeName', align: 'center' },
  { text: '用途', value: 'purpose', align: 'center' },
  { text: '管理级别', value: 'managerLevelName', align: 'center', width: 90 },
  { text: '使用部门', value: 'useDeptName', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: 165 },
]) // 表格
const list = ref([]) // 表格数据
const dialogVisible = ref<boolean>(false) // 添加组件的显示与隐藏
const equipmentCategoryList = ref<selectType[]>([]) // 设备类别
// 获取数据列表
const getList = () => {
  loadingTable.value = true
  listPageApi(searchQuery).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows
      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) => {
  // console.log(row, 'row')
  // dialogVisible.value = true
  // addRef.value.initDialog({
  //   title: '详情',
  //   ...row,
  // })
  $router.push({
    name: 'standingBookDetail',
    params: {
      type: 'detail',
    },
    query: {
      title: '详情',
      name: '固定资产',
      id: row.id,
    },
  })
}
// 编辑
const update = (row: fixedAssetsType) => {
  // dialogVisible.value = true
  // addRef.value.initDialog({
  //   title: '编辑',
  //   ...row,
  // })
  $router.push({
    name: 'standingBookDetail',
    params: {
      type: 'edit',
    },
    query: {
      title: '编辑',
      name: '固定资产',
      id: row.id,
    },
  })
}
// 删除
const remove = (row: fixedAssetsType) => {
  ElMessageBox.confirm(
    `确认删除${row.equipmentName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      assetsDeleteApi({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getList()
        }
      })
    })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  searchQuery.assetNo = ''
  searchQuery.equipmentName = ''
  searchQuery.modelNo = ''
  searchQuery.equipmentSpecifications = ''
  searchQuery.equipmentCategory = ''
  getList()
}
// 模板下载
const templateDownload = () => {

}
// 标签识别
const identify = () => {

}
// 新增
const add = () => {
  $router.push({
    name: 'standingBookDetail',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: '固定资产',
    },
  })
}
// 表格被选中的行
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, '固定资产')
  }
  else if (selectIds.length > 0) {
    const printList = list.value.filter((item: fixedAssetsType) => selectIds.includes(item.id))
    printJSON(printList, properties, '固定资产')
  }
  else {
    ElMessage('无可打印内容')
  }
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (selectList.value.length) {
    selectList.value.forEach((item) => {
      searchQuery.ids?.push(item.id as string)
    })
  }
  listExportApi({ ...searchQuery, limit: undefined, offset: undefined }).then((res) => {
    exportFile(res.data, '固定资产列表')
    loading.close()
    searchQuery.ids = []
  }).catch((_) => {
    loading.close()
  })
}
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])
    listImporttApi(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
//   }
//   else {
//     ElMessage.error('请上传pdf格式')
//   }
}
// 批量导入
const batchImport = () => {
  fileRef.value.click()
}
// 传给子组件的刷新事件
const refreshDta = () => {
  getList()
  dialogVisible.value = false
}
onMounted(() => {
  getList()
  // 获取设备类别
  getDictByCode('equipmentCategory').then((response) => {
    equipmentCategoryList.value = response.data
  })
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="searchQuery.assetNo" placeholder="固定编号" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.equipmentName" placeholder="设备名称" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.modelNo" placeholder="型号" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.equipmentSpecifications" placeholder="设备规格" clearable class="w-50 m-2" />
        </search-item>
        <search-item>
          <!-- <el-input v-model="searchQuery.equipmentCategory" placeholder="设备类型" clearable class="w-50 m-2" /> -->
          <el-select v-model="searchQuery.equipmentCategory" placeholder="设备类别" clearable>
            <el-option v-for="item in equipmentCategoryList" :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/fixedAssets/add`)" icon="icon-add" title="新建" @click="add" />
          <icon-button v-if="proxy.hasPerm(`/device/fixedAssets/identify`)" icon="icon-device" title="标签识别" @click="identify" />
          <icon-button v-if="proxy.hasPerm(`/device/fixedAssets/import`)" icon="icon-import" title="批量导入" @click="batchImport" />
          <icon-button v-if="proxy.hasPerm(`/device/fixedAssets/mould`)" icon="icon-template" title="模板下载" @click="templateDownload" />
          <icon-button v-if="proxy.hasPerm(`/device/fixedAssets/export`)" icon="icon-export" title="导出" @click="exportExcelBtn" />
          <icon-button v-if="proxy.hasPerm(`/device/fixedAssets/print`)" icon="icon-print" title="打印" @click="printList" />
        </template>
        <!-- 表格区域 -->
        <normal-table
          id="print"
          :data="list" :total="total" :columns="columns as any"
          :is-showmulti-select="true"
          :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
          :list-loading="loadingTable"
          :is-multi="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="140" fixed="right">
              <template #default="{ row }">
                <el-button v-if="proxy.hasPerm(`/device/fixedAssets/update`)" size="small" type="primary" link @click="update(row)">
                  编辑
                </el-button>
                <el-button v-if="proxy.hasPerm(`/device/fixedAssets/detail`)" size="small" type="primary" link @click="detail(row)">
                  详情
                </el-button>
                <el-button v-if="proxy.hasPerm(`/device/fixedAssets/delete`)" size="small" type="danger" link @click="remove(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>

<style lang="scss" scoped>
.normal-input {
  width: 154px !important;
}

.normal-date {
  width: 154px !important;
}

.normal-select {
  width: 154px !important;
}

:deep(.el-table__header) {
  background-color: #bbb;
}
</style>

