<template>
  <Dialog v-model="dialogVisible" :title="t('iotMaintain.selectMaterials')"
          style="width: 1300px; min-height: 300px" :close-on-click-modal="false" @close="handleClose">

    <!-- 新增设备分类和BOM节点信息显示 -->
    <div style="margin: 0 0px 15px; background: #f5f7fa; padding: 12px 20px; border-radius: 4px;">
      <el-row>
        <el-col :span="12">
          <span style="font-weight: bold; margin-right: 10px;">设备分类：</span>
          <span>{{ deviceCategoryName }}</span>
        </el-col>
        <el-col :span="12">
          <span style="font-weight: bold; margin-right: 10px;">BOM节点：</span>
          <span>{{ bomNodeName }}</span>
        </el-col>
      </el-row>
    </div>

    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item :label="t('workOrderMaterial.materialName')" prop="name" style="margin-left: 28px">
          <el-input
            v-model="queryParams.name"
            :placeholder="t('workOrderMaterial.nameHolder')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </el-form-item>
        <el-form-item :label="t('workOrderMaterial.materialCode')" prop="code">
          <el-input
            v-model="queryParams.code"
            :placeholder="t('workOrderMaterial.codeHolder')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </el-form-item>
        <!--
        <el-form-item :label="t('workOrderMaterial.materialGroup')" prop="materialGroupId" style="margin-left: 5px">
          <el-tree-select
            filterable
            v-model="queryParams.materialGroupId"
            :data="materialGroupList"
            :props="defaultProps"
            check-strictly
            node-key="id"
            :placeholder="t('workOrderMaterial.groupHolder')"
            class="!w-220px"
            clearable
          />
        </el-form-item> -->
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />
            {{ t('workOrderMaterial.search') }}</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />
            {{ t('workOrderMaterial.reset') }}</el-button>
          <el-button @click="handleConfirm" class="custom-green-button"><Icon icon="ep:check" class="mr-5px" /> {{ t('workOrderMaterial.confirm') }}</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 新增：已选物料标签区域 -->
    <ContentWrap v-if="selectedRows.length > 0"
                 style="margin: -10px 0px 10px; padding: 10px 15px; background: #f8fafc; border-radius: 4px; border: 1px solid #ebeef5;">
      <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 8px;">
        <div style="font-weight: bold; color: #606266; margin-right: 10px;">已选物料：</div>
        <el-tag
          v-for="item in selectedRows"
          :key="item.id"
          @close="removeTag(item)"
          style="margin-bottom: 5px; position: relative; padding-right: 25px;"
        >
          {{ item.name }}-{{ item.code }}
          <!-- 自定义关闭按钮 -->
          <span class="close-icon" @click.stop="removeTag(item)">
            <Icon icon="ep:close" style="font-size: 12px; position: absolute; right: 8px; top: 50%; transform: translateY(-50%);"/>
          </span>
        </el-tag>
      </div>
    </ContentWrap>

    <ContentWrap>
      <el-table
        ref="tableRef"
        v-loading="loading"
                :data="list"
                :stripe="true"
                :show-overflow-tooltip="true"
                @row-click="handleRowClick">
        <el-table-column width="80" :label="t('workOrderMaterial.select')">
          <template #default="{ row }">
            <el-checkbox
              :model-value="selectedRows.some(item => item.id === row.id)"
              @click.stop="selectRow(row)"
              class="no-label-radio"
            />
          </template>
        </el-table-column>
        <el-table-column :label="t('workOrderMaterial.materialName')" align="center" prop="name" />
        <el-table-column :label="t('workOrderMaterial.materialCode')" align="center" prop="code" />
        <!-- <el-table-column :label="t('deviceForm.model')" align="center" prop="model" /> -->
        <el-table-column :label="t('workOrderMaterial.unit')" align="center" prop="unit" />
        <!-- <el-table-column :label="t('form.remark')" align="center" prop="remark" show-overflow-tooltip /> -->
        <el-table-column
          :label="t('deviceList.createTime')"
          align="center"
          prop="createTime"
          width="180"
          :formatter="dateFormatter"
        />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </Dialog>
</template>

<script setup lang="ts">
import { DictDataVO } from '@/api/system/dict/dict.data'
import { dateFormatter } from '@/utils/formatTime'
import * as MaterialApi from '@/api/pms/material'
import {defaultProps, handleTree} from "@/utils/tree";
import * as MaterialGroupApi from '@/api/pms/materialgroup'

defineOptions({
  name: 'MaterialList'
})
const { t } = useI18n() // 国际化
const materialGroupList = ref<Tree[]>([]) // 物料组树形结构

const emit = defineEmits<{
  (e: 'choose', value: MaterialApi.MaterialVO[]): void
  (e: 'close'): void
}>()

const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<DictDataVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const selectedRows = ref<MaterialApi.MaterialVO[]>([]); // 多选数据（存储所有选中行的数组）
const tableRef = ref();

const deviceCategoryName = ref('') // 存储设备分类名称
const bomNodeName = ref('') // 存储BOM节点名称

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  materialGroupId: '',
  code: '',
  name: '',
  model: '',
  unit: ''
})

const selectedRow = ref(null);

// 处理单选逻辑
const selectRow = (row) => {
  // selectedRow.value = selectedRow.value?.id === row.id ? null : row;
  // emit('choose', row)
  const index = selectedRows.value.findIndex(item => item.id === row.id);
  if (index > -1) {
    selectedRows.value.splice(index, 1); // 取消选中
  } else {
    selectedRows.value.push(row); // 选中
  }
  // dialogVisible.value = false
};

// 点击整行选中
const handleRowClick = (row) => {
  selectRow(row);
};
const open = async (row: any) => {
  // 设置传递过来的设备分类名称和BOM节点名称
  deviceCategoryName.value = row.deviceCategoryName || ''
  bomNodeName.value = row.name || ''

  queryParams.name = '';
  queryParams.code = '';
  dialogVisible.value = true

  await getList();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const getList = async () => {
  loading.value = true
  try {
    const data = await MaterialApi.getMaterialPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 关闭时清空选择
const handleClose = () => {
  tableRef.value?.clearSelection();
  selectedRows.value = []
  emit('close')
};

// 新增：移除标签方法
const removeTag = (material: MaterialApi.MaterialVO) => {
  // 从已选列表中移除
  const index = selectedRows.value.findIndex(item => item.id === material.id);
  if (index !== -1) {
    selectedRows.value.splice(index, 1);
  }

  // 如果当前行在当前页，取消其选中状态
  const rowInTable = list.value.find(item => item.id === material.id);
  if (rowInTable) {
    const rowIndex = list.value.indexOf(rowInTable);
    // 这里可以添加逻辑强制更新行状态（如果需要）
  }
};


// 确认选择
const handleConfirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }
  emit('choose', selectedRows.value.map(row => ({
    ...row,
    // 确保返回必要字段
    code: row.code,
    name: row.name,
    unit: row.unit
  })))
  dialogVisible.value = false;
  handleClose()
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const choose = (row: DictDataVO) => {
  emit('choose', row)
  dialogVisible.value = false
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/** 初始化 **/
onMounted(async () => {
  materialGroupList.value = handleTree(await MaterialGroupApi.getSimpleMaterialGroupList())
  await getList()
})
</script>
<style lang="scss" scoped>
.no-label-radio .el-radio__label {
  display: none;
}
.no-label-radio .el-radio__inner {
  margin-right: 0;
}

/* 自定义淡绿色按钮 */
:deep(.custom-green-button) {
  background-color: #e1f3d8;
  border-color: #e1f3d8;
  color: #67c23a;
}

/* 悬停效果 */
:deep(.custom-green-button:hover) {
  background-color: #d1e8c0;
  border-color: #d1e8c0;
  color: #5daf34;
}

/* 点击效果 */
:deep(.custom-green-button:active) {
  background-color: #c2dca8;
  border-color: #c2dca8;
}

// 新增标签样式
.close-icon {
  cursor: pointer;
  color: #999;
  transition: color 0.2s;

  &:hover {
    color: #ff4d4f;
  }
}

.el-tag {
  position: relative;
  padding-right: 25px;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

</style>
