<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="920px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="资产编号" prop="id">
            <el-input v-model="formData.id" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="编码" prop="deviceCode" required>
            <el-input v-model="formData.deviceCode" placeholder="请输入编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="deviceName" required>
            <el-input v-model="formData.deviceName" placeholder="请输入名称" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="类型" prop="deviceType" required>
            <el-tree-select
              v-model="formData.deviceType"
              :data="deviceTypeTree"
              :props="treeSelectProps"
              check-strictly
              default-expand-all
              value-key="id"
              placeholder="请选择类型"
              class="!w-full"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="品牌" prop="deviceBrand">
            <el-input v-model="formData.deviceBrand" placeholder="请输入品牌" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号" prop="deviceModel">
            <el-input v-model="formData.deviceModel" placeholder="请输入型号" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="规格" prop="deviceSpec">
            <el-input v-model="formData.deviceSpec" placeholder="请输入规格" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="供应商" prop="supplier">
            <el-select v-model="formData.supplier" placeholder="请选择供应商" clearable filterable class="!w-full">
              <el-option v-for="item in supplierOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属车间" prop="workshop">
            <el-tree-select
              v-model="formData.workshop"
              :data="deptTree"
              :props="treeSelectProps"
              check-strictly
              default-expand-all
              value-key="id"
              placeholder="请选择所属车间"
              class="!w-full"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="生产日期" prop="productionDate" required>
            <el-date-picker v-model="formData.productionDate" type="date" value-format="x" placeholder="请选择生产日期" class="!w-full" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="入厂日期" prop="factoryEntryDate" required>
            <el-date-picker v-model="formData.factoryEntryDate" type="date" value-format="x" placeholder="请选择入厂日期" class="!w-full" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="位置" prop="deviceLocation">
            <el-input v-model="formData.deviceLocation" placeholder="请输入位置" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="部门" prop="systemOrg">
            <el-tree-select
              v-model="formData.systemOrg"
              :data="deptTree"
              :props="treeSelectProps"
              check-strictly
              default-expand-all
              value-key="id"
              placeholder="请选择部门"
              class="!w-full"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="责任人" prop="deviceManager">
            <div class="device-ledger-manager">
              <el-input v-model="formData.deviceManager" placeholder="请选择数据" readonly />
              <el-button type="primary" plain @click="openUserPicker">选择</el-button>
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <Dialog title="选择责任人" v-model="userPickerVisible" width="720px">
    <el-input v-model="userKeyword" placeholder="搜索用户" clearable class="mb-12px" />
    <el-table :data="filteredUsers" height="420">
      <el-table-column label="账号" prop="username" />
      <el-table-column label="姓名" prop="nickname" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" @click="selectUser(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>
  </Dialog>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { DeviceLedgerApi, DeviceLedgerVO } from '@/api/mes/deviceledger'
import { DeviceTypeApi, DeviceTypeTreeVO } from '@/api/mes/devicetype'
import { SupplierApi } from '@/api/erp/purchase/supplier'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleUserList, UserVO } from '@/api/system/user'
import { handleTree } from '@/utils/tree'
import type { FormRules } from 'element-plus'

/** 设备类型 表单 */
defineOptions({ name: 'DeviceLedgerForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  deviceStatus: undefined,
  deviceBrand: undefined,
  deviceModel: undefined,
  deviceSpec: undefined,
  deviceType: undefined,
  supplier: undefined,
  workshop: undefined,
  deviceLocation: undefined,
  systemOrg: undefined,
  deviceManager: undefined,
  productionDate: undefined,
  factoryEntryDate: undefined,
  remark: undefined,
  sort: undefined
})
const formRules = reactive<FormRules>({
  deviceCode: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
  deviceName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  deviceType: [{ required: true, message: '类型不能为空', trigger: 'change' }],
  productionDate: [{ required: true, message: '生产日期不能为空', trigger: 'change' }],
  factoryEntryDate: [{ required: true, message: '入厂日期不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

const treeSelectProps = { label: 'name', children: 'children' }
const deviceTypeTree = ref<DeviceTypeTreeVO[]>([])
const deptTree = ref<any[]>([])
const supplierOptions = ref<string[]>([])
const deptNameMap = ref<Record<number, string>>({})
const deptIdMap = ref<Record<string, number>>({})

const userPickerVisible = ref(false)
const userKeyword = ref('')
const users = ref<UserVO[]>([])
const filteredUsers = computed(() => {
  const keyword = userKeyword.value?.trim().toLowerCase()
  if (!keyword) return users.value
  return users.value.filter((u) =>
    [u.username, u.nickname].some((v) => (v ?? '').toString().toLowerCase().includes(keyword))
  )
})

const openUserPicker = () => {
  userPickerVisible.value = true
}

const selectUser = (user: UserVO) => {
  formData.value.deviceManager = user.nickname
  userPickerVisible.value = false
}

const buildDeptNameMap = (nodes: any[]) => {
  const map: Record<number, string> = {}
  const reverseMap: Record<string, number> = {}
  const stack = [...nodes]
  while (stack.length) {
    const node = stack.pop()!
    if (typeof node.id === 'number') {
      map[node.id] = node.name
      if (node.name) reverseMap[String(node.name)] = node.id
    }
    if (Array.isArray(node.children) && node.children.length) stack.push(...node.children)
  }
  deptNameMap.value = map
  deptIdMap.value = reverseMap
}

const normalizeDeptValue = (value: any) => {
  if (value === undefined || value === null || value === '') return undefined
  if (typeof value === 'number') return value
  const byName = deptIdMap.value[String(value)]
  return byName === undefined ? undefined : byName
}

const ensureOptionsLoaded = async () => {
  const [deviceTypeRes, supplierRes, deptRes, userRes] = await Promise.all([
    DeviceTypeApi.getDeviceTypeTree({ pageNo: 1, pageSize: 10 }),
    SupplierApi.getSupplierSimpleList(),
    getSimpleDeptList(),
    getSimpleUserList()
  ])
  deviceTypeTree.value = deviceTypeRes
  supplierOptions.value = (supplierRes ?? []).map((item: any) => item.name).filter((v: any) => typeof v === 'string')
  const tree = handleTree(deptRes, 'id', 'parentId')
  deptTree.value = tree
  buildDeptNameMap(tree)
  users.value = userRes ?? []
}

/** 打开弹窗 */
const open = async (type: string, id?: number, defaultDeviceTypeId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await ensureOptionsLoaded()

  if (type === 'create' && defaultDeviceTypeId) {
    formData.value.deviceType = defaultDeviceTypeId
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceLedgerApi.getDeviceLedger(id)
      formData.value.workshop = normalizeDeptValue((formData.value as any).workshop)
      formData.value.systemOrg = normalizeDeptValue((formData.value as any).systemOrg)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const workshopId = formData.value.workshop
    const systemOrgId = formData.value.systemOrg
    const data = {
      ...(formData.value as any),
      workshop: typeof workshopId === 'number' ? deptNameMap.value[workshopId] : undefined,
      systemOrg: typeof systemOrgId === 'number' ? deptNameMap.value[systemOrgId] : undefined
    } as unknown as DeviceLedgerVO
    if (formType.value === 'create') {
      await DeviceLedgerApi.createDeviceLedger(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceLedgerApi.updateDeviceLedger(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceCode: undefined,
    deviceName: undefined,
    deviceStatus: undefined,
    deviceBrand: undefined,
    deviceModel: undefined,
    deviceSpec: undefined,
    deviceType: undefined,
    supplier: undefined,
    workshop: undefined,
    deviceLocation: undefined,
    systemOrg: undefined,
    deviceManager: undefined,
    productionDate: undefined,
    factoryEntryDate: undefined,
    remark: undefined,
    sort: undefined
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.device-ledger-manager {
  display: flex;
  width: 100%;
  gap: 12px;
}

.device-ledger-manager :deep(.el-input) {
  flex: 1;
}
</style>
