<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item>
        <el-button @click="openForm" type="primary"
          ><Icon icon="ep:plus" class="mr-5px" /> 选择物料</el-button
        >
        <el-button @click="handleView" type="warning"
          ><Icon icon="ep:plus" class="mr-5px" /> 新增物料</el-button
        >
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="物料编码" align="center" prop="code" />
      <el-table-column label="物料名称" align="center" prop="name" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="消耗数量" align="center" prop="depleteCount" >
        <template #default="scope">
          <el-input
            v-model="scope.row.depleteCount"
          />
        </template>
      </el-table-column>
      <el-table-column label="总库存数量" align="center" prop="totalCount" />
      <el-table-column label="备注" align="center" prop="remark" >
        <template #default="scope">
          <el-input
            v-model="scope.row.remark"
          />
        </template>
      </el-table-column>
      <el-table-column label="物料来源" align="center" prop="sourceType" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <div style="display: flex; justify-content: center; align-items: center; width: 100%">
            <div>
              <Icon style="vertical-align: middle; color: #ea3434" icon="ep:zoom-out" />
              <el-button
                style="vertical-align: middle"
                link
                type="danger"
                @click="handleDelete(scope.row.code)"
              >
                移除
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ChooseMaterial ref="formRef" :deptId="props.deptId"  @choose="selectChoose"/>
  <MaintainMaterialDrawer
    ref="showDrawer"
    :model-value="drawerVisible"
    @update:model-value="(val) => (drawerVisible = val)"
    @add="handleChildSubmit"
  />
</template>

<script setup lang="ts">
import { IotMaintainMaterialVO } from '@/api/pms/maintain/material'
import { ref } from 'vue'
import MaintainMaterialDrawer from '@/views/pms/maintain/material/MaintainMaterialDrawer.vue'
import {propTypes} from "@/utils/propTypes";
import ChooseMaterial from "@/views/pms/maintain/material/ChooseMaterial.vue";

/** 工单物料 列表 */
defineOptions({ name: 'IotMaintainMaterial' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const list = ref<IotMaintainMaterialVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const props = defineProps({
  deptId: propTypes.number.def(undefined)
})
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  unit: undefined,
  price: undefined,
  sourceType: undefined,
  depleteCount: undefined,
  totalCount: undefined,
  sapCode: undefined,
  status: undefined,
  remark: undefined,
  createTime: []
})
const formData = ref({
  id: undefined,
  code: undefined,
  name: undefined,
  unit: undefined,
  price: undefined,
  sourceType: undefined,
  depleteCount: undefined,
  totalCount: undefined,
  sapCode: undefined,
  status: undefined,
  remark: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const selectChoose = (formData) => {
  console.log('接收到的数据:', JSON.stringify(formData))
  list.value.push(formData)
}
const handleChildSubmit = (formData) => {
  const modified = removeOnesFromKeys(formData)
  list.value.push(modified)
}

const removeOnesFromKeys = (obj: Record<string, any>) => {
  return Object.keys(obj).reduce(
    (acc, key) => {
      const newKey = key.replace(/1/g, '') // 替换所有 1
      acc[newKey] = obj[key]
      return acc
    },
    {} as Record<string, any>
  )
}
const handleView = () => {
  drawerVisible.value = true
  showDrawer.value.openDrawer()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    list.value = []
  } finally {
    loading.value = false
  }
}

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

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

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if(!props.deptId) {
    message.error("请选择设备")
    return
  }
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    //await message.delConfirm()
    // 发起删除
    // await IotMaintainMaterialApi.deleteIotMaintainMaterial(id)
    // message.success(t('common.delSuccess'))
    // // 刷新列表
    // await getList()
    const index = list.value.findIndex((item) => item.code === id)
    if (index !== -1) {
      // 通过 splice 删除元素
      list.value.splice(index, 1)
    }
  } catch {}
}

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