<!-- 标签列表 -->
<script lang="ts" setup name="Label">
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { ILabelItem, IUseStateList, IlistQuery, dictType } from './label'
import { getDictByCode } from '@/api/system/dict'
import { batchImportLabel, delLabel, getLabelList, importLabel } from '@/api/system/label'
import { exportFile } from '@/utils/exportUtils'
const { proxy } = getCurrentInstance() as any
const useStateList = ref<dictType[]>([]) // 关联使用情况字典值
const listQuery = reactive({
  rfid: '',
  equipmentNo: '',
  equipmentName: '',
  useStatus: '', // 使用情况
  offset: 1,
  limit: 20,
})
const fileRef = ref() // 文件上传input，获取input的引用
// 表头
const columns = ref([
  { text: 'RFID标签编号', value: 'rfid', width: '200', align: 'center' },
  { text: '使用情况', value: 'usageStatusName', width: '100', align: 'center' },
  { text: '绑定设备编号', value: 'equipmentNo', width: '300', align: 'center' },
  { text: '绑定设备名称', value: 'equipmentName', width: '300', align: 'center' },
  { text: '使用岗位', value: 'usePosition', align: 'center' },
  { text: '负责人', value: 'directorName', width: '150', align: 'center' },
])
const list = ref([])
const total = ref(0)
const listLoading = ref(false)

// 获取标签使用情况字典值
const fetchLabelUseDict = () => {
  getDictByCode('labelUseState').then((res) => {
    useStateList.value = res.data
  })
}
// 表格被选中的行
const selectList = ref<any[]>([])
// 表格多选
const multiSelect = (row: any[]) => {
  selectList.value = row
}
// 获取流程列表
const fetchData = async (isNowPage: boolean) => {
  listLoading.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.offset = 1
  }
  const response = await getLabelList(listQuery)
  total.value = parseInt(response.data.total)
  list.value = response.data.rows
  listLoading.value = false
}

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

// 查询数据
const search = () => {
  fetchData(false)
}

// 重置
const reset = () => {
  listQuery.rfid = ''
  listQuery.equipmentNo = ''
  listQuery.equipmentName = ''
  listQuery.useStatus = ''
  listQuery.limit = 20
  listQuery.offset = 1
  fetchData(true)
}

const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('file', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    // TODO: 暂时用上传接口，将来改为导入的接口
    batchImportLabel(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('上传成功')
        loading.close()
        fileRef.value.value = ''
        fetchData(true)
      }
      else {
        // ElMessage.error(res.message)
        loading.close()
      }
    }).catch(() => {
      // ElMessage.error(err.message)
      loading.close()
    })
  }
}

// 删除
const del = (row: ILabelItem) => {
  ElMessageBox.confirm(
    `确认删除标签${row.rfid}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      delLabel({ rfids: [row.rfid] }).then((res) => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          fetchData(true)
        }
      })
    })
}
// 导入
const ImportFile = () => {
  fileRef.value.click()
}
// 导出
const exportFileFun = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  const data = {
    ...listQuery,
    offset: undefined,
    limit: undefined,
    rfids: selectList.value.map(item => item.rfid),
  }
  importLabel(data).then((res) => {
    exportFile(res.data, '标签管理')
    loading.close()
  })
    .catch((_) => {
      loading.close()
    })
}
// 批量删除
const batchDeleteLabel = () => {
  if (selectList.value.length) {
    ElMessageBox.confirm(
      '确认删除所选数据吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        delLabel({ rfids: selectList.value.map(item => item.rfid) }).then((res) => {
          if (res.code === 200) {
            ElMessage.success('删除成功')
            fetchData(true)
          }
        })
      })
  }
  else {
    ElMessage.warning('请选择需要删除的数据')
  }
}
onMounted(() => {
  fetchLabelUseDict()
  fetchData(true)
})
</script>

<template>
  <div class="label">
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="listQuery.rfid" placeholder="rfid标签编号" clearable />
        </search-item>
        <search-item>
          <el-input v-model="listQuery.equipmentNo" placeholder="绑定设备编号" clearable />
        </search-item>
        <search-item>
          <el-input v-model="listQuery.equipmentName" placeholder="绑定设备名称" clearable />
        </search-item>
        <search-item>
          <el-select v-model="listQuery.useStatus" placeholder="请选择使用情况" clearable>
            <el-option
              v-for="item in useStateList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
      </search-area>

      <!-- 查询结果Table显示 -->
      <table-container>
        <template #btns-right>
          <icon-button icon="icon-import" title="导入" type="primary" @click="ImportFile" />
          <icon-button icon="icon-sweep" title="扫描识读" type="primary" />
          <icon-button icon="icon-export" title="导出" type="primary" @click="exportFileFun" />
          <icon-button icon="icon-delete" title="删除" type="primary" @click="batchDeleteLabel" />
          <input ref="fileRef" style="display: none;" type="file" accept=".xls,.xlsx" @change="onFileChange">
        </template>

        <div class="table-area">
          <normal-table
            :data="list"
            :total="total"
            :columns="columns"
            :query="listQuery"
            :is-multi="true"
            :is-showmulti-select="true"
            :list-loading="listLoading"
            @change="changePage"
            @multi-select="multiSelect"
          >
            <template #preColumns>
              <el-table-column label="序号" width="55" align="center">
                <template #default="scope">
                  {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
                </template>
              </el-table-column>
            </template>
            <template #columns>
              <el-table-column label="操作" width="100" align="center" fixed="right">
                <template #default="scope">
                  <el-button type="danger" :disabled="scope.row.usageStatusName === '已使用'" link size="small" class="table-text-button" @click="del(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </template>
          </normal-table>
        </div>
      </table-container>
    </app-container>
  </div>
</template>

<style lang="scss" scoped>
.label {
  .table-area {
    background-color: #fff;
    padding: 10px;
    margin-top: 10px;
    border-radius: 7px;
  }
}
</style>

<style lang="scss">
  .list-login-log {
    .el-button + .el-button {
      margin-top: -10px;
    }
  }

  .el-message-box {
    overflow: auto;
  }
</style>
