<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/" />

  <el-row :gutter="20">
    <!-- 左侧 设备分类 树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeviceCategoryTree @node-click="handleDeviceCategoryTreeNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="110px"
        >
          <el-form-item label="BOM节点名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入BOM节点名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="BOM节点" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择BOM节点"
              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" /> 搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create', null)"
              v-hasPermi="['rq:iot-bom:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button type="danger" plain @click="toggleExpandAll">
              <Icon icon="ep:sort" 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="BOM节点" />
          <!-- <el-table-column prop="deviceCategoryName" label="设备分类" /> -->
          <el-table-column prop="sort" label="排序" />
          <el-table-column prop="status" label="状态" >
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <!--
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
          /> -->
          <el-table-column prop="materials" label="物料数量" />
          <el-table-column label="操作" align="center" >
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row)"
                v-hasPermi="['rq:iot-bom:update']"
              >
                修改
              </el-button>
              <el-button
                link
                type="primary"
                @click="openSelectMaterialForm(scope.row.id)"
                v-hasPermi="['rq:iot-bom:update']"
              >
                添加物料
              </el-button>
              <el-button
                link
                type="primary"
                @click="handleView(scope.row.id)"
                v-hasPermi="['rq:iot-bom:update']"
              >
                物料详情
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['rq:iot-bom:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 添加或修改 Bom树节点 对话框 -->
  <BomForm ref="formRef" :category_id="selectedId" @success="getList" />
  <!-- 添加物料列表 -->
  <MaterialList ref="materialListRef" @choose="chooseMaterial" />
  <!-- 抽屉组件 -->
  <MaterialListDrawer
    :model-value="drawerVisible"
    @update:model-value="val => drawerVisible = val"
    :node-id="currentBomNodeId"
    ref="showDrawer"
  />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import * as BomApi from '@/api/pms/bom'
import {CommonBomMaterialApi, CommonBomMaterialVO} from '@/api/pms/commonbommaterial'
import BomForm from './BomForm.vue'
import DeviceCategoryTree from './DeviceCategoryTree.vue'
import { useTreeStore } from '@/store/modules/treeStore';
import { ref, computed } from 'vue';
import { handleTree } from '@/utils/tree'
import MaterialList from "@/views/pms/bom/MaterialList.vue";
import MaterialListDrawer from "@/views/pms/bom/MaterialListDrawer.vue";

defineOptions({ name: 'Bom' })

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 queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  status: undefined,
  deviceCategoryId: undefined,
})
const queryFormRef = ref() // 搜索的表单

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

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

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

/** 选择物料操作 */
const materialListRef = ref()
const openSelectMaterialForm = (id?: number) => {
  materialListRef.value.open(id)
  currentBomNodeId.value = id
}

/** 查看物料详情 */
const handleView = async (nodeId) => {
  currentBomNodeId.value = nodeId
  drawerVisible.value = true
  showDrawer.value.openDrawer()
  // 强制刷新物料数据
  await showDrawer.value.loadMaterials(nodeId)
}

const chooseMaterial = async(row) => {
  // 将物料关联到bom节点
  try {
    CommonBomMaterialData.value.deviceCategoryId = selectedId.value
    CommonBomMaterialData.value.bomNodeId = currentBomNodeId.value
    CommonBomMaterialData.value.materialId = row.id
    CommonBomMaterialData.value.name = row.name
    CommonBomMaterialData.value.code = row.code
    const data = CommonBomMaterialData.value as unknown as CommonBomMaterialVO
    await CommonBomMaterialApi.createCommonBomMaterial(data);
    message.success(t('common.createSuccess'))
    // 保存成功后立即刷新抽屉数据
    showDrawer.value.loadMaterials(currentBomNodeId.value)
    await getList()
  } finally {
    // formLoading.value = false
  }

}

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

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

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

/** 添加/修改操作 */
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
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BomApi.deleteBomNode(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>
