<!-- 印章管理登记 -->
<script name="SealInfoList" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IListQuery, ISealInfo } from './seal-info'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { delSealInfo, getSealInfoList } from '@/api/resource/seal'
import { getDictByCode } from '@/api/system/dict'
import type { IDictType } from '@/commonInterface/resource-interface'

const { proxy } = getCurrentInstance() as any
const router = useRouter()

// 查询条件
const searchQuery = ref<IListQuery>({
  sealNo: '', // 印章编号
  sealName: '', // 印章名
  status: '',
  offset: 1,
  limit: 10,
})
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '印章编号', value: 'sealNo', align: 'center' },
  { text: '印章名称', value: 'sealName', align: 'center' },
  { text: '在用状态', value: 'statusName', align: 'center', width: '100' },
  { text: '申请时间', value: 'applyTimeStr', align: 'center', width: '130' },
  { text: '批准时间', value: 'ratifyTimeStr', align: 'center', width: '130' },
  { text: '报废时间', value: 'abandonTimeStr', align: 'center', width: '130' },
  { text: '批准', value: 'approverName', align: 'center' },
  { text: '图形', value: 'minioFileUrl', align: 'center', width: '240' },
])
const sealInfoList = ref<Array<ISealInfo>>([]) // 表格数据

const sealStatusDict = ref<Array<IDictType>>([])
const sealTypeDict = ref<Array<IDictType>>([])

// 逻辑

// 跳转到新建的页面
const addSealInfo = () => {
  router.push({
    query: {
      type: 'create',
    },
    path: 'list/detail',
  })
}

// 详情
const detail = (row: ISealInfo) => {
  sessionStorage.setItem('sealInfo', JSON.stringify(row))
  router.push({
    query: {
      type: 'detail',
      id: row.id,
    },
    path: 'list/detail',
  })
}

// 编辑
const updateById = (row: ISealInfo) => {
  sessionStorage.setItem('sealInfo', JSON.stringify(row))
  router.push({
    query: {
      type: 'update',
      id: row.id,
    },
    path: 'list/detail',
  })
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getSealInfoList(searchQuery.value).then((response) => {
    if (response.code === 200) {
      sealInfoList.value = response.data.rows.map((item: ISealInfo) => {
        return {
          ...item,
          applyTimeStr: dayjs(item.applyTime).format('YYYY-MM-DD') !== 'Invalid Date' ? dayjs(item.applyTime).format('YYYY-MM-DD') : '',
          ratifyTimeStr: dayjs(item.ratifyTime).format('YYYY-MM-DD') !== 'Invalid Date' ? dayjs(item.ratifyTime).format('YYYY-MM-DD') : '',
          abandonTimeStr: dayjs(item.abandonTime).format('YYYY-MM-DD') !== 'Invalid Date' ? dayjs(item.abandonTime).format('YYYY-MM-DD') : '',
        }
      })
      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)
}
// 改变页容量
function handleSizeChange(val: number) {
  changePage({ size: val })
}
// 改变当前页
function handleCurrentChange(val: number) {
  changePage({ page: val })
}

// 重置
const reset = () => {
  searchQuery.value = {
    sealNo: '', // 印章编号
    sealName: '', // 印章名
    status: '',
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}

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

// 获取在用状态字典值
const getSealStatusDict = () => {
  getDictByCode('bizSealStatus').then((res: any) => {
    if (res.code === 200) {
      sealStatusDict.value = res.data
      sessionStorage.setItem('bizSealStatus', JSON.stringify(sealStatusDict.value))
    }
  })
}
const getSealTypeDict = () => {
  getDictByCode('bizSealType').then((res: any) => {
    if (res.code === 200) {
      sealTypeDict.value = res.data
      sessionStorage.setItem('bizSealType', JSON.stringify(sealTypeDict.value))
    }
  })
}
const getDict = async () => {
  getSealStatusDict()
  getSealTypeDict()
}

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

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.sealNo" placeholder="印章编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.sealName" placeholder="印章名称" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.status" placeholder="在用状态" clearable>
          <el-option v-for="item in sealStatusDict" :key="item.id" :value="item.value" :label="item.name" />
        </el-select>
      </search-item>
    </search-area>

    <!-- 表格数据展示 -->
    <table-container title="印章列表">
      <!-- 表头区域 -->
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm(`/resource/seal/list/add`)" icon="icon-add" title="新建" @click="addSealInfo" />
      </template>

      <!-- 表格区域 -->
      <el-table :data="sealInfoList" :columns="columns" border stripe>
        <el-table-column align="center" label="序号" width="55" type="index" />

        <el-table-column v-for="col in columns" :key="col.value" :label="col.text" :align="col.align" :width="col.width">
          <template #default="scope">
            <el-image v-if="col.value === 'minioFileUrl'" :src="scope.row.minioFileUrl" />
            <span v-else>{{ scope.row[col.value] }}</span>
          </template>
        </el-table-column>

        <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>
            <el-button v-if="proxy.hasPerm(`/resource/seal/list/edit`)" size="small" type="primary" link @click="updateById(row)">
              编辑
            </el-button>
            <el-button v-if="proxy.hasPerm(`/resource/seal/list/del`)" size="small" type="danger" link @click="deleteById(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="searchQuery.offset"
        :page-sizes="[10, 20, 30]"
        :page-size="searchQuery.limit"
        :total="total"
        layout="total, sizes, prev, pager, next"
        style="margin-top: 10px;"
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
      />
    </table-container>
  </app-container>
</template>

