<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 主表单 -->
    <el-form 
      ref="formRef"
      :model="formData" 
      :rules="rules" 
      label-width="120px"
      label-position="right"
      size="default"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="出库单号" prop="orderNo">
            <el-input 
              v-model="formData.orderNo"
              placeholder="系统自动生成"
              :disabled="mode === 'edit'"
            >
              <template #append>
                <el-button @click="generateOrderNo">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="出库仓库" prop="warehouseId">
            <el-select
              v-model="formData.warehouseId"
              placeholder="请选择仓库"
              style="width: 100%;"
              clearable
            >
              <el-option 
                v-for="warehouse in warehouseOptions"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="formData.remarks"
              type="textarea"
              :rows="2"
              placeholder="请输入出库单备注信息"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 物资明细 -->
      <div class="details-section">
        <div class="section-header">
          <h4>出库物资明细</h4>
          <div class="header-actions">
            <el-button type="primary" @click="showMaterialSelector">
              <el-icon><Plus /></el-icon>
              添加物资
            </el-button>
            <el-button @click="clearAllDetails">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
          </div>
        </div>

        <el-table
          :data="formData.details"
          stripe
          border
          size="small"
          class="details-table"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          
          <el-table-column prop="materialCode" label="物资编码" width="120">
            <template #header>
              <span>物资编码</span>
              <el-tooltip content="点击选择物资" placement="top">
                <el-icon class="header-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </template>
          </el-table-column>
          
          <el-table-column label="物资信息" min-width="200">
            <template #default="{ row }">
              <div class="material-info">
                <div class="material-name">{{ row.materialName }}</div>
                <div class="material-spec">{{ row.specification }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="unit" label="单位" width="80" align="center" />
          
          <el-table-column prop="availableStock" label="可用库存" width="100" align="right">
            <template #default="{ row }">
              <span :class="{
                'stock-low': row.availableStock < row.plannedQuantity,
                'stock-zero': row.availableStock === 0
              }">
                {{ row.availableStock || 0 }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column label="计划出库数量" width="150">
            <template #default="{ row }">
              <el-input-number
                v-model="row.plannedQuantity"
                :min="0.001"
                :max="row.availableStock || 999999"
                :precision="3"
                :step="1"
                size="small"
                controls-position="right"
                style="width: 120px;"
                @change="updateRowAmount(row)"
              />
            </template>
          </el-table-column>
          
          <el-table-column prop="unitPrice" label="单价" width="120" align="right">
            <template #default="{ row }">
              <span>¥{{ formatAmount(row.unitPrice) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="计划金额" width="120" align="right">
            <template #default="{ row }">
              <span class="amount-cell">
                ¥{{ formatAmount(row.plannedAmount) }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="80" fixed="right" align="center">
            <template #default="{ $index }">
              <el-button
                type="danger"
                link
                size="small"
                @click="removeDetail($index)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 汇总信息 -->
        <div class="summary-section">
          <el-descriptions :column="4" border size="small">
            <el-descriptions-item label="物资种类">
              <span class="summary-value">{{ formData.details.length }} 种</span>
            </el-descriptions-item>
            <el-descriptions-item label="总数量">
              <span class="summary-value">{{ totalQuantity }} {{ unitText }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="总金额">
              <span class="summary-value highlight">
                ¥{{ formatAmount(totalAmount) }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="创建人">
              <span class="summary-value">{{ currentUser.name }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          :loading="submitting"
          @click="handleSubmit"
          :disabled="formData.details.length === 0"
        >
          确认保存
        </el-button>
      </span>
    </template>

    <!-- 物资选择器 -->
    <MaterialSelector
      v-model="showMaterialSelectorDialog"
      :selected-materials="selectedMaterialIds"
      @select="handleMaterialSelect"
    />
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  Plus, 
  Delete, 
  InfoFilled 
} from '@element-plus/icons-vue'
import MaterialSelector from './MaterialSelector.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  order: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'create'
  }
})

const emit = defineEmits(['update:modelValue', 'save'])

// 表单引用和规则
const formRef = ref()
const rules = {
  warehouseId: [
    { required: true, message: '请选择出库仓库', trigger: 'change' }
  ]
}

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formData = ref({
  orderNo: '',
  warehouseId: '',
  remarks: '',
  details: []
})

const submitting = ref(false)
const showMaterialSelectorDialog = ref(false)

// 模拟数据
const warehouseOptions = ref([
  { id: 'WH001', name: '成品仓A' },
  { id: 'WH002', name: '成品仓B' },
  { id: 'WH003', name: '原材料仓' },
  { id: 'WH004', name: '半成品仓' }
])

const materialOptions = ref([
  {
    id: 'MAT001',
    code: 'P-1001',
    name: '不锈钢螺丝',
    specification: 'M8*25',
    unit: '个',
    unitPrice: 2.5,
    availableStock: 1500
  },
  {
    id: 'MAT002',
    code: 'P-1002',
    name: '轴承',
    specification: '6202ZZ',
    unit: '个',
    unitPrice: 15.0,
    availableStock: 800
  },
  {
    id: 'MAT003',
    code: 'P-1003',
    name: '电机',
    specification: 'DC-24V-100W',
    unit: '台',
    unitPrice: 350.0,
    availableStock: 120
  }
])

const currentUser = ref({
  id: 'U001',
  name: '张三'
})

// 计算属性
const dialogTitle = computed(() => {
  return props.mode === 'edit' ? '编辑出库单' : '新建出库单'
})

const selectedMaterialIds = computed(() => {
  return formData.value.details.map(detail => detail.materialId)
})

const totalQuantity = computed(() => {
  return formData.value.details.reduce((sum, detail) => sum + detail.plannedQuantity, 0)
})

const totalAmount = computed(() => {
  return formData.value.details.reduce((sum, detail) => sum + detail.plannedAmount, 0)
})

const unitText = computed(() => {
  const units = [...new Set(formData.value.details.map(d => d.unit))]
  return units.length > 1 ? '多种单位' : units[0] || ''
})

// 监听订单数据变化
watch(() => props.order, (order) => {
  if (order && props.mode === 'edit') {
    formData.value = {
      orderNo: order.orderNo,
      warehouseId: order.warehouseId || '',
      remarks: order.remarks || '',
      details: order.details || []
    }
  }
}, { immediate: true })

// 方法
const generateOrderNo = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  formData.value.orderNo = `OUT-${year}${month}${day}-${random}`
}

const showMaterialSelector = () => {
  showMaterialSelectorDialog.value = true
}

const handleMaterialSelect = (materials) => {
  materials.forEach(material => {
    // 避免重复添加
    if (!selectedMaterialIds.value.includes(material.id)) {
      formData.value.details.push({
        id: '',
        orderId: '',
        materialId: material.id,
        materialCode: material.code,
        materialName: material.name,
        specification: material.specification,
        unit: material.unit,
        plannedQuantity: 1,
        actualQuantity: 0,
        unitPrice: material.unitPrice,
        plannedAmount: material.unitPrice,
        actualAmount: 0,
        availableStock: material.availableStock
      })
    }
  })
  showMaterialSelectorDialog.value = false
}

const removeDetail = (index) => {
  formData.value.details.splice(index, 1)
}

const clearAllDetails = () => {
  ElMessageBox.confirm(
    '确定要清空所有物资明细吗？',
    '确认清空',
    { type: 'warning' }
  ).then(() => {
    formData.value.details = []
  }).catch(() => {
    // 用户取消
  })
}

const updateRowAmount = (row) => {
  row.plannedAmount = row.plannedQuantity * row.unitPrice
}

const handleClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.value = {
    orderNo: '',
    warehouseId: '',
    remarks: '',
    details: []
  }
  visible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    if (formData.value.details.length === 0) {
      ElMessage.warning('请至少添加一条物资明细')
      return
    }

    // 检查库存
    const insufficientStock = formData.value.details.some(detail => 
      detail.plannedQuantity > detail.availableStock
    )
    
    if (insufficientStock) {
      ElMessage.warning('部分物资计划数量超过可用库存，请调整')
      return
    }

    submitting.value = true

    // 构建提交数据
    const submitData = {
      ...formData.value,
      totalAmount: totalAmount.value,
      operatorId: currentUser.value.id,
      status: 'DRAFT',
      details: formData.value.details.map(detail => ({
        materialId: detail.materialId,
        plannedQuantity: detail.plannedQuantity,
        unitPrice: detail.unitPrice
      }))
    }

    emit('save', submitData)
    handleClose()
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const formatAmount = (amount) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}
</script>

<style scoped>
.details-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.section-header h4 {
  margin: 0;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.details-table {
  width: 100%;
  margin-bottom: 20px;
}

.material-info {
  line-height: 1.4;
}

.material-name {
  font-weight: 500;
  color: #303133;
}

.material-spec {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.stock-low {
  color: #e6a23c;
  font-weight: 500;
}

.stock-zero {
  color: #f56c6c;
  font-weight: 500;
}

.amount-cell {
  font-weight: 600;
  color: #303133;
}

.summary-section {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 2px solid #409eff;
}

.summary-value {
  font-weight: 500;
  color: #303133;
}

.summary-value.highlight {
  color: #f56c6c;
  font-size: 16px;
  font-weight: 600;
}

.header-icon {
  margin-left: 5px;
  color: #909399;
  cursor: help;
}

:deep(.el-dialog__body) {
  padding-bottom: 10px;
}

:deep(.el-table__cell) {
  padding: 8px 0;
}
</style>