<template>
  <el-dialog
    v-model="dialogVisible"
    title="修改材料信息"
    width="900px"
    top="5vh"
    :close-on-click-modal="false"
    destroy-on-close
    @close="handleClose"
  >
    <el-form
      :model="form"
      label-width="90px"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="材料编号">
            <el-input v-model="form.prodNo" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格型号">
            <el-input v-model="form.attrib_03" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料名称">
            <el-input v-model="form.materialName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="钢种">
            <el-input v-model="form.stGrade" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="数量">
            <el-input v-model="form.quantity" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重量">
            <el-input v-model="form.weight" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单号">
            <el-input v-model="form.attrib_01" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合约号">
            <el-input v-model="form.attrib_02" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="捆包号">
            <el-input v-model="form.attrib_04" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产地">
            <el-input v-model="form.attrib_05" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="货权单位">
            <el-select
              v-model="form.ownerCompany"
              clearable
              filterable
              placeholder="请选择货权单位"
              style="width: 100%;"
            >
              <el-option
                v-for="item in ownerCompanyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称">
            <el-select
              v-model="form.customerCompany"
              clearable
              filterable
              placeholder="请选择客户名称"
              style="width: 100%;"
            >
              <el-option
                v-for="item in customerCompanyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="收货地址">
            <el-input v-model="form.deliveryAddress" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark_1" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()

const dialogVisible = ref(false)
const customerCompanyOptions = ref([])
const ownerCompanyOptions = ref([])

const createEmptyForm = () => ({
  id: '',
  materialNo: '',
  attrib_03: '',
  materialName: '',
  stGrade: '',
  quantity: '',
  weight: '',
  attrib_01: '',
  attrib_02: '',
  attrib_04: '',
  attrib_05: '',
  prodPlace: '',
  ownerCompany: '',
  customerCompany: '',
  deliveryAddress: '',
  remark_1: ''
})

const form = reactive(createEmptyForm())

// 获取客户名称选项
const fetchCustomerOptions = async () => {
  try {
    const response = await proxy.$axios.get('sto/Customer/querySelect', {})
    if (response.data.code === 0 || response.data.code === '0') {
      const options = response.data.data || []
      customerCompanyOptions.value = options.map(item => ({
        label: item.label || item.name || item.value || '',
        value: item.value || item.id || item.code || item.label || ''
      })).filter(item => item.label && item.value)
    }
  } catch (error) {
    console.error('获取客户名称选项失败:', error)
  }
}

// 获取货权单位选项
const fetchOwnerCompanyOptions = async () => {
  try {
    const response = await proxy.$axios.get('sto/Customer/querySelect', {})
    if (response.data.code === 0 || response.data.code === '0') {
      const options = response.data.data || []
      ownerCompanyOptions.value = options.map(item => ({
        label: item.label || item.name || item.value || '',
        value: item.value || item.id || item.code || item.label || ''
      })).filter(item => item.label && item.value)
    }
  } catch (error) {
    console.error('获取货权单位选项失败:', error)
  }
}

// 打开弹窗
const open = (row) => {
  if (!row) {
    ElMessage.warning('请选择要编辑的数据')
    return
  }
  
  // 重置表单并回填当前行数据
  Object.assign(form, createEmptyForm(), {
    id: row.storeId ?? '',
    prodNo: row.prodNo ?? '',
    attrib_03: row.attrib_03 ?? '',
    materialName: row.materialName ?? '',
    stGrade: row.ST_GRADE ?? row.stGrade ?? '',
    quantity: row.quantity ?? row.QUANTITY ?? '',
    weight: row.weight ?? row.WEIGHT ?? '',
    attrib_01: row.attrib_01 ?? '',
    attrib_02: row.attrib_02 ?? '',
    attrib_04: row.attrib_04 ?? '',
    attrib_05: row.attrib_05 ?? '',
    prodPlace: row.prodPlace ?? '',
    ownerCompany: row.ownerCompany ?? '',
    customerCompany: row.customerCompany ?? row.CustomerCompany ?? '',
    deliveryAddress: row.deliveryAddress ?? '',
    remark_1: row.remark_1 ?? ''
  })
  
  // 获取选项数据
  fetchCustomerOptions()
  fetchOwnerCompanyOptions()
  
  dialogVisible.value = true
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  Object.assign(form, createEmptyForm())
}

// 确定
const handleConfirm = async () => {
  try {
    // 构建保存参数，使用 id 作为后端主键
    const { storeId, ...saveData } = form

    if (!saveData.id) {
      ElMessage.warning('缺少必要的数据ID')
      return
    }

    const url = 'sto/ProdMaster/edit'

    // axios 封装第三个参数是 contentType 字符串，否则会被当作对象导致 Content-Type:[object Object]
    const response = await proxy.$axios.post(url, saveData, 'application/json')

    if (response.data.code === 0 || response.data.code === '0') {
      ElMessage.success('修改成功')
      handleClose()
      emit('success')
    } else {
      ElMessage.error(`修改失败：${response.data.msg || ''}`)
    }
  } catch (error) {
    ElMessage.error(`修改失败：${error.message || ''}`)
  }
}

// 取消
const handleCancel = () => {
  handleClose()
}

const emit = defineEmits(['success'])

defineExpose({
  open
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>


