<template>
  <el-dialog
    v-model="dialogVisible"
    title="货权转移"
    width="600px"
    :close-on-click-modal="false"
    destroy-on-close
    @close="handleClose"
  >
    <el-form :model="form" label-width="100px" label-position="right">
      <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-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-form-item label="修改地址">
        <el-input
          v-model="form.deliveryAddress"
          type="textarea"
          :rows="3"
          placeholder="请输入地址"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="success" @click="handleSave">保存</el-button>
        <el-button type="danger" @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

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

const { proxy } = getCurrentInstance()

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

const form = ref({
  customerCompany: '',
  ownerCompany: '',
  deliveryAddress: ''
})

// 获取客户名称选项
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 = (rows) => {
  if (!rows || rows.length === 0) {
    ElMessage.warning('请先选择要转移货权的数据')
    return
  }
  
  selectedRows.value = rows
  
  // 重置表单
  form.value = {
    customerCompany: '',
    ownerCompany: '',
    deliveryAddress: ''
  }
  
  // 获取选项数据
  fetchCustomerOptions()
  fetchOwnerCompanyOptions()
  
  dialogVisible.value = true
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  selectedRows.value = []
  form.value = {
    customerCompany: '',
    ownerCompany: '',
    deliveryAddress: ''
  }
}

// 保存
const handleSave = async () => {
  // 检查是否至少填写了一个字段
  const hasValue = form.value.customerCompany || form.value.ownerCompany || (form.value.deliveryAddress && form.value.deliveryAddress.trim() !== '')
  
  if (!hasValue) {
    ElMessage.warning('请至少填写一个要修改的字段')
    return
  }
  
  try {
    // 构建货权转移的数据
    const transferData = {
      ids: selectedRows.value.map(row => row.id || row.inProdNo).filter(id => id),
      updateFields: {}
    }
    
    // 只包含有值的字段
    if (form.value.customerCompany) {
      transferData.updateFields.customerCompany = form.value.customerCompany
    }
    if (form.value.ownerCompany) {
      transferData.updateFields.ownerCompany = form.value.ownerCompany
    }
    if (form.value.deliveryAddress && form.value.deliveryAddress.trim() !== '') {
      transferData.updateFields.deliveryAddress = form.value.deliveryAddress.trim()
    }
    
    // TODO: 根据实际API调整接口地址和参数格式
    const url = 'sto/OutRecord/transferOwnership' // 需要根据实际API调整
    const param = {
      json: JSON.stringify(transferData),
      jsonList: JSON.stringify(selectedRows.value)
    }
    
    const response = await proxy.$axios.post(url, param)
    
    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>


