<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="CAS号" prop="cas">
          <el-input v-model="state.queryData.cas" clearable />
        </el-form-item>
        <el-form-item label="危化品品名" prop="dangerName">
          <el-input v-model="state.queryData.dangerName" 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="cas" label="CAS号" width="120" :show-overflow-tooltip="true" />
      <el-table-column property="dangerName" label="危化品品名"  :show-overflow-tooltip="true" />
      <!--      <el-table-column property="enName" label="英文名" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="chAlias" label="危化品别名" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="enAlias" label="英文别名" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="chemicalsEq" label="化学方程式" width="120" :show-overflow-tooltip="true" />-->
      <el-table-column property="unCode" label="UN编码" width="120" :show-overflow-tooltip="true" />
      <!--      <el-table-column property="dangerStatement" label="危险说明" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="preventStatement" label="防范说明" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="chSignalWord" label="中文信号词" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="enSignalWord" label="英文信号词" width="120" :show-overflow-tooltip="true" />-->
      <!--      <el-table-column property="SIGNS" label="标签" width="120" :show-overflow-tooltip="true" />-->
      <el-table-column property="REMARK" label="备注"  :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="12">
          <el-form-item label="危化品品名:" prop="dangerName">
            <span>{{ state.viewForm.dangerName || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="危化品别名:" prop="chAlias">
            <span>{{ state.viewForm.chAlias || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="英文名:" prop="enName">
            <span>{{ state.viewForm.enName || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="英文别名:" prop="enAlias">
            <span>{{ state.viewForm.enAlias || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="CAS号:" prop="cas">
            <span>{{ state.viewForm.cas || '-' }}</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="signs">
            <span>{{ state.viewForm.signs || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="化学方程式:" prop="chemicalsEq">
            <span>{{ state.viewForm.chemicalsEq || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中文信号词:" prop="chSignalWord">
            <span>{{ state.viewForm.chSignalWord || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="英文信号词:" prop="enSignalWord">
            <span>{{ state.viewForm.enSignalWord || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="危险说明:" prop="dangerStatement">
            <span>{{ state.viewForm.dangerStatement || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="防范说明:" prop="preventStatement">
            <span>{{ state.viewForm.preventStatement || '-' }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注:" prop="remark">
            <span>{{ state.viewForm.remark || '-' }}</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 { ChemicalsCatalog, ChemicalsCatalogQuery } from '@/types/base/ChemicalsCatalog'
import {getList} from '@/apis/base/ChemicalsCatalog'
import { permissionStatus } from '@/utils/globalPermission'
import { scheduledTask } from '@/apis/base/TaskLog'

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

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

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

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

const state = reactive<State>({
  queryData: {
    dangerName: '',
    enName: '',
    chAlias: '',
    enAlias: '',
    chemicalsEq: '',
    cas: '',
    unCode: '',
    dangerStatement: '',
    preventStatement: '',
    chSignalWord: '',
    enSignalWord: '',
    signs: '',
    indexNum: '',
    pageIndex: tablePagination.currentPage,
    pageSize: tablePagination.pageSize
  },
  formData: {
    ID: '',
    dangerName: '',
    enName: '',
    chAlias: '',
    enAlias: '',
    chemicalsEq: '',
    cas: '',
    unCode: '',
    dangerStatement: '',
    preventStatement: '',
    chSignalWord: '',
    enSignalWord: '',
    signs: '',
    remark: '',
    createUser: '',
    createDept: '',
    createTime: '',
    updateUser: '',
    updateTime: '',
    isDeleted: '',
    status: '',
    indexNum: '',
  } as ChemicalsCatalog,
  viewForm: {} as ChemicalsCatalog,
  viewTitle: '',
  viewDialogVisible: false,
  title: '',
  isEdit: false,
  dialogVisible: false,
})

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

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

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

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