<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="960">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="绑定物资柜" prop="materialsCabinetId">
            <el-select
              v-model="formData.materialsCabinetId"
              :disabled="visibleSelect"
              clearable
              placeholder="请选择绑定物资柜"
              class="!w-348px"
              @clear="handleClearCabinet"
            >
              <el-option
                v-for="dict in cabinets"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物资名称" prop="materialsName">
            <el-input
              v-model="formData.materialsName"
              placeholder="请输入物资名称"
              class="!w-348px"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="物资类型" prop="materialsTypeId">
            <el-tree-select
              v-model="formData.materialsTypeId"
              :data="materialtypeOptions"
              :props="{ label: 'materialsTypeName', value: 'id' }"
              placeholder="选择物资类型"
              class="!w-348px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="RFID" prop="materialsRfid">
            <el-input
              v-model="formData.materialsRfid"
              placeholder="请输入物资RFID"
              class="!w-348px"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplier">
            <el-input v-model="formData.supplier" placeholder="请输入供应商" class="!w-348px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效期截止" prop="expirationDate">
            <el-date-picker
              v-model="formData.expirationDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              :picker-options="pickerOptions"
              @change="handleClearTime"
              class="!w-348px"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="物资规格" prop="properties">
            <div v-for="property in PropertyList" :key="property.id" class="property-container">
<!--              <h3>{{ property.propertyName }}</h3>-->
              <div class="property-values">
                <div
                  v-for="value in PropertyValueList.filter((v) => v.propertyId == property.id)"
                  :key="value.id"
                  :class="[
                    'property-value',
                    {
                      selected: selectedValues[property.id] == value.id
                    }
                  ]"
                  @click="selectValue(property.id, value.id)"
                >
                  {{ value.valueName }}
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物资图片" prop="materialsTypePicture">
            <UploadImg
              v-model="formData.materialsTypePicture"
              :limit="1"
              height="90px"
              width="90px"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button v-if="formType === 'view'" type="primary" @click="dialogVisible = false">
        返回
      </el-button>
      <template v-else>
        <el-button :disabled="formLoading" type="primary" @click="submitForm"> 确 定 </el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import * as MaterialApi from '@/api/material/information'
import * as MaterialCabinetApi from '@/api/material/lockers/index'
import * as MaterialTypeApi from '@/api/material/type'
import * as PropertyApi from '@/api/material/standard/index'
import * as PropertyValueApi from '@/api/material/standard/propertyValue'
import { handleTree } from '@/utils/tree'

defineOptions({ name: 'MaterialForm' })

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

// 弹窗状态
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改；view - 查看
const visibleSelect = ref(false) // 是否显示选择物资柜

// 表单数据
const formData = ref({
  materialsId: undefined,
  materialsCabinetId: undefined,
  materialsName: '',
  materialsTypeId: undefined,
  materialsRfid: '',
  supplier: '',
  expirationDate: undefined,
  materialsTypePicture: '',
  properties: '',

})

// 表单校验规则
const formRules = reactive({
  materialsName: [{ required: true, message: '物资名称不能为空', trigger: 'blur' }],
  materialsTypeId: [{ required: true, message: '物资类型不能为空', trigger: 'blur' }]
})

// 物资柜选项
const cabinets = ref([])

// 物资类型选项
const materialtypeOptions = ref([])

// 物资规格选项
const PropertyList = ref([])
const PropertyValueList = ref([])
const selectedValues = ref({})

// 日期选择器配置
const pickerOptions = {
  disabledDate(time: Date) {
    return time.getTime() < Date.now() - 8.64e7
  }
}

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MaterialApi.getMaterialsInfo(id)
      if (formData.value.properties) {
        const JsonData = JSON.parse(formData.value.properties)
        setInitialSelection(JsonData)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    materialsId: undefined,
    materialsCabinetId: undefined,
    materialsName: '',
    materialsTypeId: undefined,
    materialsRfid: '',
    supplier: '',
    expirationDate: undefined,
    materialsTypePicture: '',
    properties: ''
  }
  selectedValues.value = {}
  PropertyList.value = []
  PropertyValueList.value = []
  formRef.value?.resetFields()
}

/** 日期清空处理 */
const handleClearTime = (value: any) => {
  if (value == null) {
    formData.value.expirationDate = undefined
  }
}
//
onMounted(async () => {
  const params = { pageNo: 1, pageSize: -1 }
  const data = await MaterialTypeApi.listType(params)
  materialtypeOptions.value = handleTree(data.list, 'id', 'parentId')
  const cabinet = await MaterialCabinetApi.listMaterialsCabinet(params)
  cabinets.value = cabinet.list.map((cabinet) => ({
    value: cabinet.id,
    label: cabinet.cabinetName
  })).concat({ value: 0, label: '空' })
})

// 清空时执行
const handleClearCabinet = () => {
  formData.value.materialsCabinetId = 0
}

// 监听物资类型变化
watch(
  () => formData.value.materialsTypeId,
  async (val, old) => {
    if (val && val !== old) {
      try {
        const data = await MaterialTypeApi.getTypeInfo(val)
        formData.value.materialsTypePicture = data.materialsTypePicture

        // 获取属性列表 - 修正API调用和数据结构
        const propertyData = await PropertyApi.PropertyPage({
          pageSize: -1,
          pageNo: 1,
          propertyId: data.propertyIds // 使用正确的参数名
        })

        // 修正：使用 data.list 而不是 data.records
        PropertyList.value = propertyData.list
        console.log('属性列表:', PropertyList.value)

        // 获取属性值列表
        const propertyValueData = await PropertyValueApi.PropertyValuePage({
          pageSize: -1,
          pageNo: 1,
          propertyId: data.propertyIds
        })

        // 修正：使用 data.list 而不是 data.records
        PropertyValueList.value = propertyValueData.list
        console.log('属性值列表:', PropertyValueList.value)

      } catch (error) {
        console.error('获取物资类型相关数据失败:', error)
      }
    }
  }
)

/** 选择属性值 - 修正字段映射 */
const selectValue = (propertyId: string, recordId: string) => {
  if (selectedValues.value[propertyId] == recordId) {
    selectedValues.value[propertyId] = null
  } else {
    selectedValues.value[propertyId] = recordId
  }

  // 生成 JSON 格式的数据 - 修正字段映射
  const selectionJson = Object.entries(selectedValues.value)
    .filter(([_, recordId]) => recordId) // 过滤掉空值
    .map(([propertyId, recordId]) => {
      // 修正：使用正确的字段名
      const property = PropertyList.value.find(
        (p) => p.id == propertyId // 使用 id 字段
      )
      const value = PropertyValueList.value.find(
        (v) => v.id == recordId // 使用 id 字段
      )
      return {
        propertyId: String(propertyId),
        recordId: String(recordId),
        valueName: value.valueName,
        propertyName: property.propertyName
      }
    })

  formData.value.properties = JSON.stringify(selectionJson)
  console.log('生成的属性JSON:', selectionJson)
}

/** 设置初始选中值 */
const setInitialSelection = (data: any[]) => {
  data.forEach((item) => {
    selectedValues.value[item.propertyId] = item.recordId
  })
}
</script>

<style lang="scss" scoped>
.property-container {
  margin-bottom: 20px;

  .property-values {
    display: flex;
    flex-wrap: wrap;
  }

  .property-value {
    padding: 10px;
    margin: 5px;
    border: 1px solid #ccc;
    cursor: pointer;
    border-radius: 4px;

    &.selected {
      border: 1px solid #80b3ff;
      background-color: #e6f0ff;
    }
  }
}
</style>
