<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
    <el-form-item label="物料图片" prop="logo">
      <UploadImg v-model="formData.logo" />
    </el-form-item>
      <el-form-item label="物料编码" prop="code">
        <el-input  v-model="formData.code" placeholder="请输入物料编码" class="!w-250px"/>
      </el-form-item>
      <el-form-item label="物料名称" prop="name">
        <el-input  v-model="formData.name" placeholder="请输入物料名称" class="!w-250px" />
      </el-form-item>
      <el-form-item label="物料类型" prop="materialType">
        <el-select v-model="formData.materialType" clearable placeholder="请选择物料类型" class="!w-250px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.HELI_MATERIAL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="系统单位" prop="unit">
        <el-select v-model="formData.unit" clearable placeholder="请选择系统单位" class="!w-250px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.HELI_MATERIAL_UNIT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料大类" prop="matCate">
        <el-select v-model="formData.matCate" clearable placeholder="请选择物料大类" class="!w-250px">
          <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.HELI_MATERIAL_CODE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料简称" prop="shortName">
        <el-input v-model="formData.shortName" placeholder="请输入物料简称" class="!w-250px" />
      </el-form-item>
      <el-form-item label="规格/型号" prop="spec">
        <el-input v-model="formData.spec" placeholder="请输入规格/型号" class="!w-250px" />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="formData.brand" placeholder="请输入品牌" class="!w-250px" />
      </el-form-item>
      <el-form-item label="物料主要来源" prop="mainFrom">
        <el-select v-model="formData.mainFrom" clearable placeholder="请选择物料主要来源" class="!w-250px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.HELI_MATERIAL_ORIGINAL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="首选供应商" prop="mainSupplierId">
        <!-- <el-select v-model="formData.mainSupplierId"
                   placeholder="请输入首选供应商"
                   :remote-method="remoteSupplierSearch"
                   remote-show-suffix
                   remote
                   clearable
                   reserve-keyword
                   filterable
                   :loading="supplierSelectLoading"
                   class="!w-250px"
        >
          <el-option
            v-for="item in supplierSelectList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select> -->
         <SupplierSelect v-model="formData.mainSupplierId"  @update:newValue="handleSelectedSupplier"  />
      </el-form-item>
      <el-form-item label="销项/进项税率" prop="outputInputTaxRate">
        <el-input v-model="formData.outputInputTaxRate" placeholder="请输入销项税率/进项税率" class="!w-250px" >
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="备注" prop="description">
        <el-input type="textarea" v-model="formData.description" height="150px" class="!w-500px" show-word-limit maxlength="200"/>
      </el-form-item>

      <el-form-item label="安全库存" prop="invSafe">
        <el-input v-model="formData.invSafe" placeholder="请输入安全库存" class="!w-250px" />
      </el-form-item>
      <el-form-item label="物料条码" prop="barcode">
        <el-input v-model="formData.barcode" placeholder="请输入物料条码" class="!w-250px" />
      </el-form-item>
       <el-form-item label="启用状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { nextTick } from 'vue'
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import * as MaterialApi from '@/api/heli/material'
import {getSupplierPage} from "@/api/heli/supplier";
import SupplierSelect from '@/views/heli/hlvuestyle/supplierSelect.vue'
import { getMatCatCode} from "@/api/heli/matcode";

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,
  code: undefined,
  name: undefined,
  brand: undefined,
  spec: undefined,
  sizeInfo: undefined,
  traceType: undefined,
  dftStoreWh: undefined,
  dftStoreRg: undefined,
  dftStorePn: undefined,
  dftRoute: undefined,
  description: undefined,
  status: 1,
  shortName: undefined,
  materialType: undefined,
  compositionId: undefined,
  outputInputTaxRate: undefined,
  mainSupplierId: undefined,
  mainFrom: undefined,
  unit: undefined,
  matCate: undefined,
  invSafe: undefined,
  invUpperLimit: undefined,
  invLowerLimit: undefined,
  barcode: undefined,
  virtualPart: undefined,
  logo: undefined,
})
const formRules = reactive({
  name: [{ required: true, message: '物料名称不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '启用状态不能为空', trigger: 'blur' }],
  materialType: [{ required: true, message: '物料类型不能为空', trigger: 'change' }],
  unit: [{ required: true, message: '系统单位不能为空', trigger: 'change' }],
})

const formRef = ref() // 表单 Ref
const supplierList = ref<any[]>([]) //
const supplierSelectList = ref<any[]>([])
const supplierSelectLoading = ref(false);
const isInitialized = ref(false) // 是否已初始化完成，防止加载时触发watch
const originalMatCate = ref() // 记录打开时的物料大类，用于判断是否用户主动修改

const remoteSupplierSearch = (query: string) => {
  if (query) {
    supplierSelectLoading.value = true
    setTimeout(() => {
      supplierSelectLoading.value = false
      supplierSelectList.value = supplierList.value.filter((item) => {
        return item.name.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  } else {
    supplierSelectList.value = supplierList.value;
  }
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  formLoading.value = true
  isInitialized.value = false
  try {
    if (id) {
      const data = await MaterialApi.getMaterial(id)
      formData.value = data
      // 记录原始物料大类
      originalMatCate.value = data.matCate
    } else {
      originalMatCate.value = undefined
    }
    let params = {
      pageNo: 1,
      pageSize: 10,
      status: "1"
    };
    const supplierData = await getSupplierPage(params);
    supplierList.value = supplierData.list;
    supplierSelectList.value = supplierData.list;
  } finally {
    formLoading.value = false
    nextTick(() => {
      isInitialized.value = true
    })
  }

}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MaterialApi.MaterialVO
    if (formType.value === 'create') {
      await MaterialApi.createMaterial(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaterialApi.updateMaterial(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    name: undefined,
    brand: undefined,
    spec: undefined,
    sizeInfo: undefined,
    traceType: undefined,
    dftStoreWh: undefined,
    dftStoreRg: undefined,
    dftStorePn: undefined,
    dftRoute: undefined,
    description: undefined,
    status: 1,
    shortName: undefined,
    materialType: undefined,
    compositionId: undefined,
    outputInputTaxRate: undefined,
    mainSupplierId: undefined,
    mainFrom: undefined,
    unit: undefined,
    matCate: undefined,
    invSafe: undefined,
    invUpperLimit: undefined,
    invLowerLimit: undefined,
    barcode: undefined,
    virtualPart: undefined,
    logo: undefined,
  }
  formRef.value?.resetFields()
}

//接收供应商传递的数据
const handleSelectedSupplier = (newValue: any) => {
  formData.value.mainSupplierId = newValue?.id
}

/** 监听物料类型变化，查询matcode并更新code */
watch(() => formData.value.matCate, async (newVal) => {
    // 如果未初始化完成，不处理
    if (!isInitialized.value) {
        return
    }
    // 如果新值为空，清空编码
    if (!newVal) {
        formData.value.code = undefined
        originalMatCate.value = undefined
        return
    }
    // 如果值没有变化（用户选择的是同一个值），不更新编码
    if (newVal === originalMatCate.value) {
        return
    }
    try {
        const allData = await getMatCatCode(newVal)
        if (allData != null) {
            formData.value.code = allData
        } else {
            formData.value.code = null
        }
        // 更新原始值
        originalMatCate.value = newVal
    } catch (error) {
        console.error('查询matcode失败:', error)
        formData.value.code = null

      // 提示该物料大类没有维护物料大类编码，请维护！
        // message.error('该物料大类没有维护物料大类编码，请维护！')
    }
})

</script>
