<template>
  <ContentWrap v-loading="formLoading">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
      style="margin-right: 4em; margin-left: 0.5em; margin-top: 1em"
      label-width="130px"
    >
      <div class="base-expandable-content">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="t('workOrderMaterial.factory')" prop="factoryId">
              <el-select v-model="formData.factoryId" clearable :placeholder="t('faultForm.choose')" class="!w-240px" @change="selectedFactoryChange" disabled>
                <el-option
                  v-for="item in factoryList"
                  :key="item.id"
                  :label="item.factoryName"
                  :value="item.id!"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('workOrderMaterial.costCenter')" prop="costCenterId">
              <el-select v-model="formData.costCenterId" clearable :placeholder="t('faultForm.choose')" class="!w-240px" disabled>
                <el-option
                  v-for="item in costCenterList"
                  :key="item.id"
                  :label="item.costCenterName"
                  :value="item.id!"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </ContentWrap>
  <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('fault.added') }}</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="工厂id" align="center" prop="factoryId" v-if="false"/>
        <el-table-column label="成本中心id" align="center" prop="costCenterId" 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" />
          <!--
          <template #default="scope">
            <el-input v-model="scope.row.unitPrice" />
          </template>
        </el-table-column> -->
        <el-table-column :label="t('route.quantity')" align="center" prop="quantity" :formatter="erpPriceTableColumnFormatter" />
          <!--
          <template #default="scope">
            <el-input v-model="scope.row.quantity" />
          </template>
        </el-table-column> -->
        <el-table-column :label="t('faultForm.remark')" align="center" prop="remark">
          <template #default="scope">
            <el-input v-model="scope.row.remark" />
          </template>
        </el-table-column>
        <el-table-column :label="t('maintain.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('info.delete') }}
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>

    <MaterialSelect ref="materialFormRef" @choose="materialChoose" />
  </ContentWrap>
  <ContentWrap>
    <el-form>
      <el-form-item style="float: right">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">{{t('common.save')}}</el-button>
        <el-button @click="close">{{t('common.cancel')}}</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script setup lang="ts">

import { IotLockStockApi, IotLockStockVO } from '@/api/pms/iotlockstock'
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 MaterialSelect from "@/views/pms/iotlockstock/SelectMaterial.vue";
import {erpPriceTableColumnFormatter} from "@/utils";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {SapOrgApi, SapOrgVO} from "@/api/system/saporg";
import * as DeptApi from '@/api/system/dept'

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

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 factoryList = ref([] as SapOrgVO[])   // 工厂列表
const storageLocationList = ref([] as SapOrgVO[]) // 库存地点列表
const costCenterList = ref([] as SapOrgVO[]) // SAP成本中心列表
const dept = ref() // 当前登录人所属部门对象
const materialFormRef = ref()
const openForm = () => {
  materialFormRef.value.open()
}

const selectedFactoryReqVO = ref({
  type: 0, // 类型(1工厂 2成本中心 3库位)
  factoryCodes: [] // 已经选择的SAP工厂code 列表
})

const formRef = ref() // 表单 Ref

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

const formData = ref({
  id: undefined,
  deptId: undefined,
  factoryId: 0,
  factory: '',
  storageLocationId: 0,
  projectDepartment: '',
  costCenterId: undefined,
  costCenter: ''
})

const formRules = reactive({
  // factoryId: [{ required: true, message: '工厂不能为空', trigger: 'blur' }],
  // costCenterId: [{ required: true, message: '成本中心不能为空', trigger: 'blur' }],
})

// 多选 物料
const materialChoose = (selectedMaterials) => {
  // 转换数据结构（根据你的接口定义调整）
  const newItems = selectedMaterials.map(material => ({
    materialCode: material.code,
    materialName: material.name,
    unit: material.unit,
    quantity: material.quantity,  // 初始化数量
    unitPrice: material.unitPrice, // 初始化单价
    remark: null,    // 初始化备注
    code: material.code // 移除操作需要
  }))

  // 合并到现有列表（去重）
  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 (formData.value.factoryId === undefined) {
    message.error('请选择工厂')
    return
  }
  if (formData.value.costCenterId === undefined) {
    message.error('请维护部门的成本中心')
    return
  }
  if (toRaw(list.value).length == 0) {
    message.error('请选择物料')
    return
  }
  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 {
    // 合并工厂和成本中心到每条物料记录
    const submitList = list.value.map(item => ({
      ...item,
      factoryId: formData.value.factoryId,
      costCenterId: formData.value.costCenterId
    }))
    await IotLockStockApi.manualWarehouse(submitList)
    message.success(t('common.createSuccess'))
    close()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 已经选择了 SAP工厂 */
const selectedFactoryChange = async (selectedId: number | undefined) => {
  if (!selectedId) {
    costCenterList.value = []
    formData.value.costCenterId = undefined
    return
  }

  // 获取选中的factoryCode数组
  const selectedFactory = factoryList.value.find(item => item.id === selectedId)
  if (!selectedFactory) return
  const selectedFactoryCodes = selectedFactory ? [selectedFactory.factoryCode] : []

  // 获得已经选择的 SAP 工厂 数组
  // 根据选择的 SAP工厂 调用后台接口查询 SAP工厂下属的 成本中心
  selectedFactoryReqVO.value.type = 2
  selectedFactoryReqVO.value.factoryCodes = selectedFactoryCodes
  costCenterList.value = await SapOrgApi.getSelectedList(selectedFactoryReqVO.value)
  // 重置成本中心选择
  formData.value.costCenterId = undefined
}

/** 重置表单 */
const resetForm = () => {
  formRef.value?.resetFields()
}
onMounted(async () => {
  // 加载当前登录人所属部门 关联的 工厂 成本中心 库存地点 如果有多个 随机取1个
  const deptId = useUserStore().getUser.deptId
  dept.value = await DeptApi.getDept(deptId)
  // 加载工厂(SAP) 全集
  factoryList.value = await SapOrgApi.getSimpleSapOrgList(1)
  // 成本中心 全集
  // costCenterList.value = await SapOrgApi.getSimpleSapOrgList(2)
  if (dept.value.factoryIds?.[0]) {
    formData.value.factoryId = dept.value.factoryIds[0]
    await selectedFactoryChange(formData.value.factoryId)
  }
  if (dept.value.costCenterIds?.[0]) {
    /* const validCostCenter = costCenterList.value.some(
      item => item.id === dept.value.costCenterIds[0]
    )
    console.log('随机显示一个成本中心：' + dept.value.costCenterIds[0]) */
    // if (validCostCenter) {
    formData.value.costCenterId = dept.value.costCenterIds[0]
    // }
  }
})

// 调整删除逻辑
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>
