<template>
  <MyLayout>
    <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
      <el-form :inline="true" label-width="auto" @submit.stop.prevent>
        <el-form-item label="关键词">
          <el-input v-model="state.filter.keyWord" placeholder="设备编号、序列号、资产编号" @keyup.enter="onQuery" />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="state.filter.equipmentType" placeholder="请选择设备类型" clearable style="width: 150px">
            <el-option
              v-for="type in state.equipmentTypeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="state.filter.stDate"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="state.filter.edDate"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-if="auth('api:admin:testing-equipment:get-page')" @click="onQuery" type="primary">
            <SvgIcon name="ele-Search" />查询
          </el-button>
          <el-button v-auth="'api:admin:testing-equipment:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="my-fill mt8" shadow="never">
      <div class="my-tools-box mb8 my-flex my-flex-between">
        <div>
        </div>
      </div>
      <el-table
        v-if="state.showTestequList"
        :data="state.testequListData"
        style="width: 100%"
        v-loading="state.loading"
        row-key="id"
        default-expand-all
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="equipmentType" label="设备类型" width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getEquipmentTypeName(row.equipmentType) }}
          </template>
        </el-table-column>
        <el-table-column prop="equipmentNo" label="设备编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="assetNo" label="资产编号" min-width="120" show-overflow-tooltip />
        <el-table-column label="设备型号" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getEquipmentModelName(row.equipmenModel) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
        <el-table-column prop="principalId" label="负责人" width="120" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getUserName(row.principalId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" header-align="center" align="center">
          <template #default="{ row }">
            <el-button
              v-if="auth('api:admin:testing-equipment:update')"
              icon="ele-EditPen"
              size="small"
              text
              type="primary"
              @click="onEdit(row)"
              >编辑</el-button
            >
            <el-button
              v-if="auth('api:admin:testing-equipment:soft-delete')"
              icon="ele-Delete"
              size="small"
              text
              type="danger"
              @click="onDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination
          v-model:currentPage="state.pageInput.currentPage"
          v-model:page-size="state.pageInput.pageSize"
          :total="state.total"
          :page-sizes="[10, 20, 50, 100]"
          size="small"
          background
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <testequ-form ref="testequFormRef" :title="state.testequFormTitle"></testequ-form>
  </MyLayout>
</template>

<script lang="ts" setup name="admin/testequ">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { TestequApi } from '/@/api/admin/TestequApi'
import { UserApi } from '/@/api/admin/User'
import { DictApi } from '/@/api/admin/Dict'
import { UserGetPageOutput, PageInputUserGetPageInput, TestequGetPageOutput, PageInputTestequGetPageInput, DictGetListOutput } from '/@/api/admin/data-contracts'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'

// 引入组件
const TestequForm = defineAsyncComponent(() => import('./components/testequ-form.vue'))

const { proxy } = getCurrentInstance() as any

const testequFormRef = ref()

const state = reactive({
  loading: false,
  testequFormTitle: '',
  filter: {
    keyWord: '',
    equipmentType: undefined as number | undefined,
    stDate: '',
    edDate: '',
  },
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as PageInputTestequGetPageInput,
  testequListData: [] as Array<TestequGetPageOutput>,
  userOptions: [] as Array<UserGetPageOutput>,
  equipmentModelOptions: [] as Array<DictGetListOutput>,
  equipmentTypeOptions: [
    { label: 'BGA', value: 1 },
    { label: 'Vicell', value: 3 },
    { label: 'OSMO', value: 5 },
    { label: 'Cedex', value: 7 }
  ],
  showQuery: true,
  showTestequList: true,
})

onMounted(() => {
  getUserOptions()
  getEquipmentModelOptions()
  Query()
  eventBus.off('refreshTestequ' as keyof MittType<any>)
  eventBus.on('refreshTestequ' as keyof MittType<any>, () => {
    Query()
  })
})
onBeforeMount(() => {
  eventBus.off('refreshTestequ' as keyof MittType<any>)
})

const onChangeTestequList = () => {
  state.showTestequList = !state.showTestequList
  if (state.showTestequList) {
    Query()
  }
}

// 获取用户选项
const getUserOptions = async () => {
  try {
    const userPageInput = {
      currentPage: 1,
      pageSize: 1000, // 获取足够多的数据
      filter: {
        orgId: null,
      }
    } as PageInputUserGetPageInput

    const res = await new UserApi().getPage(userPageInput)
    if (res?.success) {
      state.userOptions = res.data?.list ?? []
    }
  } catch (error) {
    // 静默处理错误
  }
}

// 获取设备型号字典选项
const getEquipmentModelOptions = async () => {
  try {
    const res = await new DictApi().getList(['TESTINGEQU'])

    if (res?.success && res.data) {
      // 注意：API返回的key是小写的 testingequ
      state.equipmentModelOptions = res.data['testingequ'] || []
    }
  } catch (error) {
    // 静默处理错误
  }
}

// 获取设备类型名称
const getEquipmentTypeName = (type: number) => {
  const option = state.equipmentTypeOptions.find(item => item.value === type)
  return option ? option.label : type?.toString() || ''
}

// 获取用户名称
const getUserName = (userId?: number) => {
  if (!userId) return ''
  const user = state.userOptions.find(item => item.id === userId)
  return user ? `${user.name} (${user.userName})` : `未知用户(${userId})`
}

// 获取设备型号名称
const getEquipmentModelName = (code?: string) => {
  if (!code) return ''
  const model = state.equipmentModelOptions.find(item => item.code === code)
  return model ? model.name : code
}

// 查询
const Query = async () => {
  state.loading = true
  try {
    // 确保filter字段结构正确，特别注意数据类型转换
    state.pageInput.filter = {
      keyWord: state.filter.keyWord || '',
      equipmentType: state.filter.equipmentType ? Number(state.filter.equipmentType) : undefined,
      stDate: state.filter.stDate || null,
      edDate: state.filter.edDate || null,
    }

    const res = await new TestequApi().getPage(state.pageInput)

    if (res?.success && res.data) {
      state.testequListData = res.data.list || []
      state.total = res.data.total || 0
    } else {
      proxy.$modal.msgError(res?.msg || '查询失败')
    }
  } catch (error: any) {
    // 静默处理错误，只显示用户友好的提示

    if (error.response) {
      if (error.response.status === 500) {
        proxy.$modal.msgError('服务器内部错误，请检查后台服务')
      } else if (error.response.status === 401) {
        proxy.$modal.msgError('认证失败，请重新登录')
      } else if (error.response.status === 403) {
        proxy.$modal.msgError('权限不足')
      } else if (error.response.status === 405) {
        proxy.$modal.msgError('API方法不被允许，请检查后端路由配置')
      } else {
        proxy.$modal.msgError(`请求失败: ${error.response.status} ${error.response.statusText}`)
      }
    } else if (error.request) {
      proxy.$modal.msgError('网络连接失败，请检查网络状态')
    } else {
      proxy.$modal.msgError(`查询失败: ${error.message}`)
    }
  } finally {
    state.loading = false
  }
}

const onQuery = () => {
  state.pageInput.currentPage = 1
  Query()
}

const onAdd = () => {
  state.testequFormTitle = '新增检测设备'
  testequFormRef.value.openDialog()
}

const onEdit = (row: TestequGetPageOutput) => {
  state.testequFormTitle = '编辑检测设备'
  testequFormRef.value.openDialog(row)
}

const onDelete = (row: TestequGetPageOutput) => {
  // 临时调试：检查传递的row对象和id
  console.log('删除操作 - 传入的row对象:', row)
  console.log('删除操作 - ID值:', row.id, '类型:', typeof row.id)

  proxy.$modal
    .confirmDelete(`确定要删除设备【${row.equipmentNo || row.assetNo || '未知设备'}】?`)
    .then(async () => {
      try {
        console.log('发送删除请求 - ID参数:', { id: row.id! })
        const res = await new TestequApi().softDelete({ id: row.id! }, { loading: true })
        console.log('删除API响应:', res)

        if (res?.success) {
          proxy.$modal.msgSuccess('删除成功')
          Query()
        }
      } catch (error: any) {
        console.error('删除API错误:', error)
        // 静默处理错误
        if (error.response?.status === 500) {
          proxy.$modal.msgError('服务器内部错误，请检查后台服务')
        } else {
          proxy.$modal.msgError(`删除失败: ${error.response?.data?.msg || error.message}`)
        }
      }
    })
    .catch(() => {})
}

const onSizeChange = (val: number) => {
  state.pageInput.pageSize = val
  Query()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  Query()
}
</script>
