<!-- 检测结果复查通知列表 -->
<script name="ReviewNoticeList" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { DateModelType } from 'element-plus'
import type{ ICustomerNoticeInfo, IListQuery } from './customer-notice'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { deleteReviewNotice, getReviewNoticeList } from '@/api/resource/reviewNotice'

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

// 查询条件
const searchQuery = ref<IListQuery>({
  noticeNo: '', // 通知单编号
  createUserName: '', // 创建人名字
  createTimeStart: '', // 创建时间-起始
  createTimeEnd: '', // 创建时间-结束
  offset: 1,
  limit: 20,
})
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '通知单编号', value: 'noticeNo', align: 'center', width: '175' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '送检日期', value: 'submitDateStr', align: 'center', width: '120' },
  { text: '送检设备名称', value: 'deviceName', align: 'center' },
  { text: '送检设备编号', value: 'deviceNo', align: 'center' },
  { text: '创建人', value: 'createUserName', align: 'center', width: '120' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
])
const noticeList = ref<Array<ICustomerNoticeInfo>>([]) // 表格数据

const reset = () => {
  searchQuery.value = {
    noticeNo: '', // 通知单编号
    createUserName: '', // 创建人名字
    createTimeStart: '', // 创建时间-起始
    createTimeEnd: '', // 创建时间-结束
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', '']
  fetchData(true)
}

const searchList = () => {
  fetchData(true)
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getReviewNoticeList(searchQuery.value).then((response) => {
    if (response.code === 200) {
      noticeList.value = response.data.rows.map((item: { submitDate: string }) => {
        return {
          ...item,
          submitDateStr: dayjs(item.submitDate).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(item.submitDate).format('YYYY-MM-DD'),
        }
      })

      total.value = parseInt(response.data.total)
    }
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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)
}

const addReviewNotice = () => {
  router.push({
    query: {
      type: 'create',
    },
    path: 'reviewNotice/detail',
  })
}

// 点击编辑按钮
const updateInfo = (row: ICustomerNoticeInfo) => {
  sessionStorage.setItem('reviewNoticeInfo', JSON.stringify(row))
  router.push({
    query: {
      type: 'update',
      id: row.id,
    },
    path: 'reviewNotice/detail',
  })
}

const detail = (row: ICustomerNoticeInfo) => {
  // 将行数据存入缓存 用来在路由之间传递数据
  sessionStorage.setItem('reviewNoticeInfo', JSON.stringify(row))

  router.push({
    query: {
      type: 'detail',
      id: row.id,
    },
    path: 'reviewNotice/detail',
  })
}

const deleteNoticeById = (row: ICustomerNoticeInfo) => {
  ElMessageBox.confirm(
    `确认删除通知单 ${row.noticeNo} 吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteReviewNotice({ id: row.id }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`通知单 ${row.noticeNo} 删除成功`)
        fetchData(true)
      }
      else {
        ElMessage.error(`通知单 ${row.noticeNo} 删除失败：${res.message}`)
      }
    })
  })
}

watch(dateRange, (val) => {
  if (val) {
    searchQuery.value.createTimeStart = dayjs(val[0]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[0]).format('YYYY-MM-DD')
    searchQuery.value.createTimeEnd = dayjs(val[1]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[1]).format('YYYY-MM-DD')
  }
  else {
    searchQuery.value.createTimeStart = ''
    searchQuery.value.createTimeEnd = ''
  }
})

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

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.noticeNo" placeholder="通知单编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.createUserName" placeholder="创建人" clearable />
      </search-item>
      <search-item>
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="创建时间（开始）" end-placeholder="创建时间（结束）" />
      </search-item>
    </search-area>

    <!-- 表格数据展示 -->
    <table-container>
      <!-- 表头区域 -->
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/resource/customer/reviewNotice/add')" icon="icon-add" title="新建" @click="addReviewNotice" />
      </template>

      <!-- 表格区域 -->
      <normal-table
        :data="noticeList" :total="total" :columns="columns"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
        :list-loading="loadingTable"
        @change="changePage"
      >
        <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 fixed="right" label="操作" align="center" width="130">
            <template #default="{ row }">
              <el-button v-if="proxy.hasPerm('/resource/customer/reviewNotice/edit')" size="small" type="primary" link @click="updateInfo(row)">
                编辑
              </el-button>
              <el-button size="small" type="primary" link @click="detail(row)">
                详情
              </el-button>
              <el-button v-if="proxy.hasPerm('/resource/customer/reviewNotice/del')" size="small" type="danger" link @click="deleteNoticeById(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
