<template>
  <cacp-search-layout>
    <template #search>
      <cacp-search-panel-layout
        :model="state.queryData"
        ref="queryFormRef"
        label-position="left"
        label-width="auto"
        :gutter="30"
        :colSpan="6"
      >
        <el-form-item label="包装类型" prop="maxType">
          <el-input v-model="state.queryData.maxType" clearable />
        </el-form-item>
        <el-form-item label="包装编码" prop="minTypeCode">
          <el-input v-model="state.queryData.minTypeCode" clearable />
        </el-form-item>
        <el-form-item label="包装类别" prop="minTypeName">
          <el-input v-model="state.queryData.minTypeName" clearable />
        </el-form-item>
        <template #buttonGroup>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="info" @click="onReset">重置</el-button>
        </template>
      </cacp-search-panel-layout>
    </template>

    <cacp-complex-table
      :actions="actions"
      :data="tableData"
      :pagination="tablePagination"
      :actionsWidth="120"
      @selection-change="handleSelectionChange"
      @on-page-change="onPageChange"
      @on-size-change="onSizeChange"
      :loading="loading"
    >
      <el-table-column label="序号" property="index" width="60" align="center" >
        <template #default="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column property="maxType" label="包装类型"  :show-overflow-tooltip="true" />
      <el-table-column property="minTypeCode" label="包装编码" :show-overflow-tooltip="true" />
      <el-table-column property="minTypeName" label="包装类别" :show-overflow-tooltip="true" />
<!--      <el-table-column property="requireInfo" label="要求" width="120" :show-overflow-tooltip="true" />-->
      <el-table-column property="maxL" label="最大容量/L"  :show-overflow-tooltip="true" />
      <el-table-column property="maxKg" label="最大净重/kg"  :show-overflow-tooltip="true" />
<!--      <el-table-column property="packStatus" label="危包状态" width="120" :show-overflow-tooltip="true" />-->
    </cacp-complex-table>
  </cacp-search-layout>

  <!--查看弹框-->
  <cacp-dialog
    v-model="state.viewDialogVisible"
    :resizable="false"
    :title="state.viewTitle"
    width="50%"
  >
    <el-form
      :model="state.viewForm"
      label-width="auto"
      label-position="left"
      :disabled="true"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="包装类型:" prop="maxType">
            <span>{{ state.viewForm.maxType || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="包装编码:" prop="minTypeCode">
            <span>{{ state.viewForm.minTypeCode || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="包装类别:" prop="minTypeName">
            <span>{{ state.viewForm.minTypeName || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大容量/L:" prop="maxL">
            <span>{{ state.viewForm.maxL || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大净重/kg:" prop="maxKg">
            <span>{{ state.viewForm.maxKg || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="要求:" prop="requireInfo">
            <span>{{ state.viewForm.requireInfo || '-' }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </cacp-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import config from '@/config'
import {
  SuccessResultCode,
  useComplexTable,
  type SearchPanelLayoutInstance,
  type TableAction,
  useLoading
} from '@cacp/ui'
import type { PackCatalog, PackCatalogQuery } from '@/types/base/PackCatalog'
import { getList } from '@/apis/base/PackCatalog'
import { permissionStatus } from '@/utils/globalPermission'
import { scheduledTask } from '@/apis/base/TaskLog'

// 表单引用
const queryFormRef = ref<SearchPanelLayoutInstance>()

// 加载状态
const { loading, setLoading } = useLoading()

// 表格 Hook
const tableHooks = useComplexTable<PackCatalog>(config)
const { tableData, tablePagination, setPagination, setPageIndex, setPageSizes } = tableHooks

// 响应式数据
interface State {
  queryData: PackCatalogQuery
  formData: PackCatalog
  viewForm: PackCatalog
  viewTitle: string
  viewDialogVisible: boolean
  title: string
  isEdit: boolean
  dialogVisible: boolean
}

const state = reactive<State>({
  queryData: {
    ID: '',
    maxType: '',
    minTypeCode: '',
    minTypeName: '',
    requireInfo: '',
    maxL: '',
    maxKg: '',
    packStatus: '',
    pageIndex: tablePagination.currentPage,
    pageSize: tablePagination.pageSize
  },
  formData: {
    maxType: '',
    minTypeCode: '',
    minTypeName: '',
    requireInfo: '',
    maxL: '',
    maxKg: '',
    packStatus: '',
  } as PackCatalog,
  viewForm: {} as PackCatalog,
  viewTitle: '',
  viewDialogVisible: false,
  title: '',
  isEdit: false,
  dialogVisible: false,
})

// 表格操作按钮配置
const actions = <Array<TableAction>>[
  {
    key: 'syncBaseData',
    text: '数据同步',
    onclick: onSyncData,
    limit: permissionStatus('none', 'PACK_CATALOG_SYNC_BT'),
    type: 'primary'
  },
  {
    key: 'view',
    text: '查看',
    onclick: onView,
    limit: permissionStatus('one', 'PACK_CATALOG_VIEW_BT'),
    type: 'primary'
  },
]

// 选中项的 ID 数组
const ids = ref<string[]>([])

// 多选框选中数据
function handleSelectionChange(selection: PackCatalog[]) {
  ids.value = selection
    .map(item => item.ID)
    .filter((id): id is string => id != null && id !== undefined)
}

// 搜索方法
const onSearch = () => {
  setPageIndex(1)
  onLoadData()
}

// 重置方法
const onReset = () => {
  queryFormRef.value?.resetFields()
  onPageChange(1)
}

// 每页显示条数变化
const onSizeChange = (size: number) => {
  setPageSizes(size)
  onLoadData()
}

// 翻页查询
const onPageChange = (currentPage: number) => {
  setPageIndex(currentPage)
  onLoadData()
}

// 查看
function onView(row: PackCatalog) {
  state.viewForm = { ...row }
  state.viewDialogVisible = true
  state.viewTitle = '包装类型详情'
}

//数据同步
async function onSyncData() {
  // 创建加载实例
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '数据同步中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    await scheduledTask("8")

    // 关闭加载
    loadingInstance.close()

    // 显示成功消息
    ElMessage({
      message: '同步成功',
      type: 'success',
      duration: 3000
    })
  } catch (error) {
    // 关闭加载
    loadingInstance.close()

    // 显示错误消息
    ElMessage({
      message: `同步失败: ${error}`,
      type: 'error',
      duration: 3000
    })
    console.error('同步失败:', error)
  }
}

// 数据查询
async function onLoadData() {
  setLoading(true)
  try {
    const query = {
      ...state.queryData,
      pageIndex: tablePagination.currentPage,
      pageSize: tablePagination.pageSize
    }
    const res = await getList(query)
    if (res.code === SuccessResultCode) {
      setPagination(res.data)
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败')
  } finally {
    setLoading(false)
  }
}


// 组件挂载时加载数据
onMounted(() => {
  onLoadData()
})
</script>

<style scoped>
/* 自定义样式 */
</style>
