<template>
  <ContentWrap>
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item>
          <el-button @click="openForm" type="warning"
            ><Icon icon="ep:plus" class="mr-5px" />
            {{ t('stock.selectStock') }}</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
          type="index"
          :label="t('iotDevice.serial')"
          width="70"
          align="center"
        />
        <el-table-column label="id" align="center" prop="id" v-if="false"/>
        <el-table-column :label="t('chooseMaintain.materialCode')" align="center" prop="materialCode" />
        <el-table-column :label="t('chooseMaintain.materialName')" align="center" prop="materialName" />
        <el-table-column :label="t('workOrderMaterial.unit')" align="center" prop="unit" />
        <el-table-column :label="t('workOrderMaterial.unitPrice')" align="center" prop="unitPrice" :formatter="erpPriceTableColumnFormatter" />
        <el-table-column :label="t('route.quantity')" align="center" prop="quantity" :formatter="erpPriceTableColumnFormatter" />
        <el-table-column :label="t('route.safetyStock')" align="center" prop="safetyStock" :formatter="erpPriceTableColumnFormatter" />
        <el-table-column :label="t('workplace.operation')" 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)"
                >
                  {{ t('form.delete') }}
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
    <SelectSapStock ref="sapStockFormRef" @choose="stockChoose" />
  </ContentWrap>
  <ContentWrap>
    <el-form>
      <el-form-item style="float: right">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('iotMaintain.save') }}</el-button>
        <el-button @click="close">{{ t('iotMaintain.cancel') }}</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script setup lang="ts">

import { IotLockStockApi, IotLockStockVO } from '@/api/pms/iotlockstock'
import { IotSapStockApi, IotSapStockVO } from '@/api/pms/iotsapstock'
import * as UserApi from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'
import { ref } from 'vue'
import { toRaw } from "vue";
import { useTagsViewStore } from '@/store/modules/tagsView'
import SelectSapStock from "@/views/pms/iotsapstock/SelectSapStock.vue";
import {erpPriceTableColumnFormatter} from "@/utils";

/** 手工入库 表单 */
defineOptions({ name: 'IotConfigSafeStock' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { currentRoute, push } = useRouter()
const deptUsers = ref<UserApi.UserVO[]>([]) // 用户列表
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const list = ref<IotLockStockVO[]>([]) // 入库物料的数据
const { params, name } = useRoute() // 查询参数

const sapStockFormRef = ref()
const openForm = () => {
  sapStockFormRef.value.open()
}

const formRef = ref() // 表单 Ref

const close = () => {
  delView(unref(currentRoute))
  push({ name: 'IotSapStockConfig', params:{}})
}

// 多选 物料
const stockChoose = (selectedStocks) => {
  // 转换数据结构（根据你的接口定义调整）
  const newItems = selectedStocks.map(stock => ({
    id: stock.id,
    materialCode: stock.materialCode,
    materialName: stock.materialName,
    unit: stock.unit,
    quantity: stock.quantity,
    safetyStock: stock.safetyStock,  // 安全库存数量
    unitPrice: stock.unitPrice,     // 单价
    remark: null,
    code: stock.materialCode  // 移除操作需要
  }))

  // 合并到现有列表（去重）
  newItems.forEach(item => {
    const exists = list.value.some(
      existing => existing.materialCode === item.materialCode
    )
    if (!exists) {
      list.value.push(item)
    }
  })
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (toRaw(list.value).length == 0) {
    message.error('请选择库存')
    return
  }
  // 校验表单 校验 单价 数量
  if (list.value.length > 0) {
    const nullList = list.value.filter((item) => item.quantity===null)
    if (nullList.length > 0) {
      message.error('请填写数量')
      return
    }
  }
  if (list.value.length > 0) {
    const nullList = list.value.filter((item) => item.unitPrice===null)
    if (nullList.length > 0) {
      message.error('请填写单价')
      return
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    await IotSapStockApi.batchSetSafetyStock(list.value)
    message.success(t('common.createSuccess'))
    close()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

onMounted(async () => {
  const deptId = useUserStore().getUser.deptId
  // deptUsers.value = await UserApi.getDeptUsersByDeptId(deptId)
})

// 调整删除逻辑
const handleDelete = (code: string) => {
  const index = list.value.findIndex(item => item.code === code)
  if (index > -1) {
    list.value.splice(index, 1)
  }
}
</script>
<style scoped>
.base-expandable-content {
  overflow: hidden; /* 隐藏溢出的内容 */
  transition: max-height 0.3s ease; /* 平滑过渡效果 */
}
</style>
