<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="chName">
          <el-input v-model="state.queryData.chName" clearable />
        </el-form-item>
        <el-form-item label="UN编码" prop="unCode">
          <el-input v-model="state.queryData.unCode" clearable />
        </el-form-item>
        <el-form-item label="危险类别" prop="dangerSort">
          <el-input v-model="state.queryData.dangerSort" clearable />
        </el-form-item>
        <el-form-item label="包装类别" prop="packType">
          <el-select v-model="state.queryData.packType" clearable>
            <el-option v-for="item in dict.pack_type" :key="item.dictValue" :label="item.dictLabel"
                       :value="item.dictValue" />
          </el-select>
        </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="chName" label="运输中文名称"  :show-overflow-tooltip="true" />
      <el-table-column property="unCode" label="UN编码"  :show-overflow-tooltip="true" />
      <el-table-column property="dangerSort" label="危险类别" width="120" :show-overflow-tooltip="true" />
      <el-table-column property="viceDanger" label="副危险" width="120" :show-overflow-tooltip="true" />
      <el-table-column property="packType" label="包装类别" width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="dict.pack_type" :dict-value="scope.row.packType" />
        </template>
      </el-table-column>
      <el-table-column property="specialProvision" label="特殊规定"  :show-overflow-tooltip="true" />
      <!--      <el-table-column property="limited" label="限量" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="exemptAmount" label="可免除量" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="packGuideline" label="包装导则" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="packProvision" label="包装规定" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="containerGuideline" label="中型散装容器导则" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="containerProvision" label="中型散装容器规定" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="tankGuideline" label="罐柜导则" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="tankProvision" label="罐柜特殊规定" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="ems" label="ems" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="stowageOperate" label="积载与操作" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="isolation" label="隔离" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="feature" label="特性与注意事项" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="createUser" label="创建人" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="createDept" label="创建部门" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="createTime" label="创建时间" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="updateUser" label="更新人" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="updateTime" label="更新时间" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="isDeleted" label="是否已删除" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="STATUS" label="业务状态" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="signs" 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="chName">
            <span>{{ state.viewForm.chName || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="UN编码:" prop="unCode">
            <span>{{ state.viewForm.unCode || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="危险类别:" prop="dangerSort">
            <span>{{ state.viewForm.dangerSort || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="副危险:" prop="viceDanger">
            <span>{{ state.viewForm.viceDanger || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="包装类别:" prop="packType">
            <dict-tag :options="dict.pack_type" :dict-value="state.viewForm.packType" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="特殊规定:" prop="specialProvision">
            <span>{{ state.viewForm.specialProvision || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="限量:" prop="limited">
            <span>{{ state.viewForm.limited || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可免除量:" prop="exemptAmount">
            <span>{{ state.viewForm.exemptAmount || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="包装导则:" prop="packGuideline">
            <span>{{ state.viewForm.packGuideline || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="包装规定:" prop="packProvision">
            <span>{{ state.viewForm.packProvision || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中型散装容器导则:" prop="containerGuideline">
            <span>{{ state.viewForm.containerGuideline || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中型散装容器规定:" prop="containerProvision">
            <span>{{ state.viewForm.containerProvision || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="罐柜导则:" prop="tankGuideline">
            <span>{{ state.viewForm.tankGuideline || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="罐柜特殊规定:" prop="tankProvision">
            <span>{{ state.viewForm.tankProvision || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="EmS:" prop="ems">
            <span>{{ state.viewForm.ems || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="积载与操作:" prop="stowageOperate">
            <span>{{ state.viewForm.stowageOperate || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="隔离:" prop="isolation">
            <span>{{ state.viewForm.isolation || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="特性与注意事项:" prop="feature">
            <span>{{ state.viewForm.feature || '-' }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="标签:" prop="signs">
            <span>{{ state.viewForm.signs || '-' }}</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 { GoodsCatalog, GoodsCatalogQuery } from '@/types/base/GoodsCatalog'
import { getList } from '@/apis/base/GoodsCatalog'
import { permissionStatus } from '@/utils/globalPermission'
import { useDictType } from '@/components/useDict'
import DictTag from '@/components/DictTag/dictTag.vue'
import { scheduledTask } from '@/apis/base/TaskLog'
const { dict } = useDictType('pack_type')

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

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

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

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

const state = reactive<State>({
  queryData: {
    unCode: '',
    chName: '',
    dangerSort: '',
    viceDanger: '',
    packType: '',
    specialProvision: '',
    limited: '',
    exemptAmount: '',
    packGuideline: '',
    packProvision: '',
    containerGuideline: '',
    containerProvision: '',
    tankGuideline: '',
    tankProvision: '',
    ems: '',
    stowageOperate: '',
    isolation: '',
    feature: '',
    signs: '',
    pageIndex: tablePagination.currentPage,
    pageSize: tablePagination.pageSize
  },
  formData: {
    ID: '',
    unCode: '',
    chName: '',
    dangerSort: '',
    viceDanger: '',
    packType: '',
    specialProvision: '',
    limited: '',
    exemptAmount: '',
    packGuideline: '',
    packProvision: '',
    containerGuideline: '',
    containerProvision: '',
    tankGuideline: '',
    tankProvision: '',
    ems: '',
    stowageOperate: '',
    isolation: '',
    feature: '',
    createUser: '',
    createDept: '',
    createTime: '',
    updateUser: '',
    updateTime: '',
    isDeleted: '',
    STATUS: '',
    signs: '',
  } as GoodsCatalog,
  viewForm: {} as GoodsCatalog,
  viewTitle: '',
  viewDialogVisible: false,
  title: '',
  isEdit: false,
  dialogVisible: false,
})

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

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

// 多选框选中数据
function handleSelectionChange(selection: GoodsCatalog[]) {
  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: GoodsCatalog) {
  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("10")

    // 关闭加载
    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>
