<template>
  <doc-alert title="用户体系" url="https://doc.iocoder.cn/user-center/" />
  <doc-alert title="三方登陆" url="https://doc.iocoder.cn/social-user/" />
  <doc-alert title="Excel 导入导出" url="https://doc.iocoder.cn/excel-import-and-export/" />

  <!-- 搜索 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item :label="t('bomList.bomNodeName')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('bomList.nameHolder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('bomList.bomNode')" prop="status">
        <el-select
          v-model="queryParams.status"
          :placeholder="t('bomList.nodeHolder')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />
          {{ t('bomList.search') }}</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />
          {{ t('bomList.reset') }}</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create', null)"
          v-hasPermi="['rq:iot-bom:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('bomList.add') }}
        </el-button>
        <el-button type="danger" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" />
          {{ t('bomList.unfold') }}
        </el-button>
        <!--
            <el-button @click="handleAllQuery"><Icon icon="ep:search" class="mr-5px" /> 查询所有</el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
      style="width: 100%"
    >
      <el-table-column prop="name" :label="t('bomList.bomNodeName')">
        <template #default="scope">
          <!-- 使用 el-tooltip 包裹内容 -->
          <el-tooltip
            effect="dark"
            :content="`设备分类：${scope.row.deviceCategoryName || '暂无'}`"
            placement="top-start"
            :disabled="!scope.row.deviceCategoryName"
          >
            <!-- 原有显示名称 -->
            <span class="bom-node-name">
              {{ scope.row.name }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="deviceCategoryName" :label="t('info.deviceClass')" /> -->
      <el-table-column prop="sort" :label="t('common.sort')" />
      <el-table-column label="维修" width="100">
        <template #default="scope">
          <el-switch
            :model-value="scope.row.type?.includes(1)"
            active-value
            inactive-value
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column label="保养" width="100">
        <template #default="scope">
          <el-switch
            :model-value="scope.row.type?.includes(2)"
            active-value
            inactive-value
            disabled
          />
        </template>
      </el-table-column>
      <!-- <el-table-column prop="status" :label="t('common.status')">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <el-table-column prop="materials" :label="t('iotMaintain.numberOfMaterials')" />
      <el-table-column :label="t('iotMaintain.operation')" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row)"
            v-hasPermi="['rq:iot-bom:update']"
          >
            {{ t('modelTemplate.update') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="openSelectMaterialForm(scope.row)"
            v-hasPermi="['rq:iot-bom:update']"
          >
            {{ t('workOrderMaterial.added') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleView(scope.row)"
            v-hasPermi="['rq:iot-bom:update']"
          >
            {{ t('bomList.materialDetail') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['rq:iot-bom:delete']"
          >
            {{ t('action.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 添加或修改 Bom树节点 对话框 -->
  <BomFormDevice ref="formRef"  :deviceId="props.deviceId" @success="getList" />
  <!-- 添加物料列表 -->
  <MaterialList ref="materialListRef" @choose="chooseMaterial" />
  <!-- 抽屉组件 -->
  <MaterialListDrawerDevice
    :model-value="drawerVisible"
    @update:model-value="(val) => (drawerVisible = val)"
    :node-id="currentBomNodeId"
    :deviceId = "props.deviceId"
    ref="showDrawer"
    :row-info="currentRowInfo"
    @refresh="handleDrawerClosed"
  />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as BomApi from '@/api/pms/devicebom'
import * as MaterialApi from '@/api/pms/iotdevicematerial'
import BomFormDevice from './BomFormDevice.vue'
import { useTreeStore } from '@/store/modules/treeStore'
import { computed, ref } from 'vue'
import { handleTree } from '@/utils/tree'
import MaterialList from '@/views/pms/bom/MaterialList.vue'
import MaterialListDrawerDevice from '@/views/pms/device/MaterialListDrawerDevice.vue'

defineOptions({ name: 'BomDevice' })

const showDrawer = ref()
const drawerVisible = ref<boolean>(false)
const treeStore = useTreeStore()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const isExpandAll = ref(true) // 是否展开，默认全部展开
const loading = ref(true) // 列表的加载中
const currentBomNodeId = ref() // 当前选中的bom节点
const refreshTable = ref(true) // 重新渲染表格状态
const list = ref() // 列表的数据
const props = defineProps<{ deviceId?: number , deviceCategoryName?:string }>()

// 添加存储当前行信息的变量 抽屉页面使用
const currentRowInfo = ref({
  deviceCategoryName: '',
  bomNodeName: ''
})

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  status: undefined,
  deviceId: undefined
})
const queryFormRef = ref() // 搜索的表单

const CommonBomMaterialData = ref({
  id: undefined,
  deviceCategoryId: undefined,
  bomNodeId: undefined,
  name: undefined,
  code: undefined,
  materialId: undefined,
  quantity: undefined,
  deviceId: undefined,
})

// 从 Store 中获取左侧设备分类树选中的 节点ID
let selectedId = computed(() => treeStore.selectedId)

/** 查询 BOM树 列表 */
const getList = async () => {
  loading.value = true
  queryParams.deviceId = props.deviceId
  try {
    const data = await BomApi.IotDeviceBomApi.getIotDeviceBomList(queryParams)
    if (data) {
      list.value = handleTree(data)
    }
  } finally {
    loading.value = false
  }
}

/** 选择物料操作 */
const materialListRef = ref()
const openSelectMaterialForm = (row: any) => {
  row.deviceCategoryName = props.deviceCategoryName
  materialListRef.value.open(row)
  currentBomNodeId.value = row.id
  // 保存当前BOM节点的deviceCategoryId
  CommonBomMaterialData.value.deviceCategoryId = row.deviceCategoryId
}

/** 查看物料详情 */
const handleView = async (row) => {
  currentBomNodeId.value = row.id
  // 保存当前行的信息
  currentRowInfo.value = {
    deviceCategoryName: props.deviceCategoryName || '暂无',
    bomNodeName: row.name || '暂无'
  }
  drawerVisible.value = true
  showDrawer.value.openDrawer()
  // 强制刷新物料数据
  await showDrawer.value.loadMaterials(row.id)
}

const chooseMaterial = async (selectedMaterials) => {
  // 将物料关联到设备bom节点
  try {
    const materialsData = selectedMaterials.map(material => ({
      deviceCategoryId: CommonBomMaterialData.value.deviceCategoryId,
      deviceId: props.deviceId,
      bomNodeId: currentBomNodeId.value,
      materialId: material.id,
      name: material.name,
      code: material.code,
      quantity: material.quantity
    }))

    // 调用批量添加接口
    const resultCount = await MaterialApi.IotDeviceMaterialApi.addMaterials(materialsData)
    message.success(`成功添加物料数量：` + resultCount)

    // 保存成功后立即刷新抽屉数据
    showDrawer.value.loadMaterials(currentBomNodeId.value)
    await getList()
  } catch (error) {
    message.error('添加物料失败！')
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  queryParams.deviceCategoryId = selectedId.value
  getList()
}

/** 查询所有数据 */
const handleAllQuery = () => {
  queryParams.pageNo = 1
  queryParams.deviceCategoryId = ''
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 处理 设备分类 被点击 */
// const handleDeviceCategoryTreeNodeClick = async (row) => {
//   queryParams.deviceCategoryId = row.id
//   await getList()
// }

// 添加处理抽屉关闭的方法
const handleDrawerClosed = () => {
  getList() // 刷新BOM树数据
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, row) => {
  // 如果是没有点击左侧设备树 直接在初始化的列表页面点击某个 BOM节点的修改 也要保存当前BOM关联的设备分类ID
  if (row != null) {
    treeStore.setSelectedId(row.deviceCategoryId)
    formRef.value.open(type, row.id)
    return
  }
  formRef.value.open(type, null)
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/**
 * 递归查找树节点
 * 基于 handleTree 处理后的树结构（包含 children 属性）
 * @param nodes 树节点数组
 * @param id 要查找的节点ID
 * @returns 找到的节点或 undefined
 */
const findNodeById = (nodes: any[], id: number): any | undefined => {
  // 遍历当前层级节点
  for (const node of nodes) {
    // 1. 检查当前节点是否匹配
    if (node.id === id) return node;

    // 2. 检查当前节点是否有子节点
    if (node.children && node.children.length > 0) {
      // 递归搜索子节点
      const foundInChildren = findNodeById(node.children, id);
      if (foundInChildren) return foundInChildren;
    }
  }

  return undefined; // 未找到
};

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 查找目标节点及其在树中的位置
    const targetNode = findNodeById(list.value, id);
    // 检查是否存在子节点（使用 children 属性）
    if (targetNode && targetNode.children && targetNode.children.length > 0) {
      message.error('当前BOM节点包含子节点，不可删除');
      return;
    }

    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BomApi.IotDeviceBomApi.deleteIotDeviceBom(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 */
onMounted(() => {
  getList()
})

// 自定义箭头展开位置
const toggleRowExpansion = (row) => {
  const $table = document.querySelector('.el-table__body-wrapper') as any
  if ($table) {
    $table.__vue__.toggleRowExpansion(row)
  }
}

const isExpanded = (row) => {
  const $table = document.querySelector('.el-table__body-wrapper') as any
  return $table?.__vue__.store.states.expandRows.value.includes(row)
}
</script>

<style scoped>
/* 确保表格容器正确继承宽度 */
:deep(.el-table) {
  width: 100% !important;
}

/* 操作按钮换行优化 */
.flex-wrap {
  flex-wrap: wrap;
}
.gap-4px {
  gap: 4px;
}

/* BOM节点名称样式 */
.bom-node-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
