<template>
  <el-drawer
    v-model="dialogVisible"
    :title="dialogTitle"
    direction="rtl"
    size="100%"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    :append-to-body="true"
    class="mobile-form-drawer"
  >
    <div class="mobile-form" v-loading="formLoading">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-position="top"
        :disabled="isViewMode"
      >
        <!-- 基本信息 -->
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">基本信息</div>
          <el-form-item label="产品" prop="productId">
            <el-select
              v-model="formData.productId"
              placeholder="请选择产品"
              filterable
              style="width: 100%"
              :disabled="isViewMode"
              @change="handleProductChange"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="`${item.name} (${item.barCode || '-'})`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="BOM名称" prop="bomName">
            <el-input v-model="formData.bomName" placeholder="请输入BOM名称" :disabled="isViewMode" />
          </el-form-item>
          <el-form-item label="BOM编码" prop="bomCode">
            <el-input v-model="formData.bomCode" placeholder="自动生成" :disabled="true" />
          </el-form-item>
          <el-form-item label="版本号" prop="version">
            <el-input v-model="formData.version" placeholder="如：V1.0" :disabled="isViewMode" />
          </el-form-item>
          <el-form-item label="默认版本" prop="isDefault">
            <el-radio-group v-model="formData.isDefault" :disabled="isViewMode">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status" :disabled="isViewMode">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入备注" :disabled="isViewMode" />
          </el-form-item>
        </div>

        <!-- BOM明细 -->
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">BOM明细</div>
          <el-button v-if="!isViewMode" type="primary" plain style="width: 100%; margin-bottom: 12px" @click="addItem">
            <Icon icon="ep:plus" class="mr-5px" /> 添加物料
          </el-button>

          <div class="mobile-item-list">
            <div
              v-for="(row, $index) in formData.items"
              :key="$index"
              class="mobile-item-card"
            >
              <div class="mobile-item-card__header">
                <span class="mobile-item-card__index">#{{ $index + 1 }}</span>
                <span class="mobile-item-card__name">{{ row.materialName || '未选择物料' }}</span>
                <el-button
                  v-if="!isViewMode"
                  link
                  type="danger"
                  size="small"
                  @click="removeItem($index)"
                >删除</el-button>
              </div>
              <div class="mobile-item-card__body">
                <el-form-item v-if="!isViewMode" label="物料" :prop="`items.${$index}.materialId`">
                  <el-select
                    v-model="row.materialId"
                    placeholder="请选择物料"
                    filterable
                    style="width: 100%"
                    @change="(val: number) => handleMaterialChange(val, $index)"
                  >
                    <el-option
                      v-for="item in materialList"
                      :key="item.id"
                      :label="`${item.name} (${item.barCode || '-'})`"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <div class="mobile-item-card__info-row">
                  <span class="mobile-item-card__info-label">物料编码</span>
                  <span class="mobile-item-card__info-value">{{ row.materialCode || '-' }}</span>
                </div>
                <div class="mobile-item-card__info-row">
                  <span class="mobile-item-card__info-label">物料类型</span>
                  <span class="mobile-item-card__info-value">{{ row.materialType || '-' }}</span>
                </div>
                <div class="mobile-item-card__info-row">
                  <span class="mobile-item-card__info-label">单位</span>
                  <span class="mobile-item-card__info-value" v-if="isViewMode">{{ row.unit || '-' }}</span>
                  <el-input v-else v-model="row.unit" placeholder="单位" style="width: 120px" />
                </div>
                <div class="mobile-item-card__input-group">
                  <el-form-item label="单位用量" :prop="`items.${$index}.unitQuantity`">
                    <el-input-number
                      v-if="!isViewMode"
                      v-model="row.unitQuantity"
                      :min="0"
                      :precision="4"
                      :step="0.1"
                      controls-position="right"
                      style="width: 100%"
                    />
                    <span v-else>{{ row.unitQuantity }}</span>
                  </el-form-item>
                  <el-form-item label="损耗率(%)" :prop="`items.${$index}.lossRate`">
                    <el-input-number
                      v-if="!isViewMode"
                      v-model="row.lossRate"
                      :min="0"
                      :max="100"
                      :precision="2"
                      controls-position="right"
                      style="width: 100%"
                    />
                    <span v-else>{{ row.lossRate || 0 }}</span>
                  </el-form-item>
                </div>
                <div class="mobile-item-card__input-group">
                  <el-form-item label="单价" :prop="`items.${$index}.unitPrice`">
                    <el-input-number
                      v-if="!isViewMode"
                      v-model="row.unitPrice"
                      :min="0"
                      :precision="2"
                      controls-position="right"
                      style="width: 100%"
                    />
                    <span v-else>{{ row.unitPrice ? '¥' + row.unitPrice : '-' }}</span>
                  </el-form-item>
                  <el-form-item label="必需">
                    <el-checkbox v-if="!isViewMode" v-model="row.required" :true-label="1" :false-label="0" />
                    <el-tag v-else :type="row.required === 1 ? 'success' : 'info'" size="small">
                      {{ row.required === 1 ? '是' : '否' }}
                    </el-tag>
                  </el-form-item>
                </div>
              </div>
            </div>
            <div v-if="formData.items.length === 0" class="mobile-empty-tip">
              暂无物料明细，请点击上方按钮添加
            </div>
          </div>
        </div>
      </el-form>

      <!-- 底部操作按钮 -->
      <div class="mobile-form__footer">
        <el-button @click="dialogVisible = false">{{ isViewMode ? '关闭' : '取消' }}</el-button>
        <el-button v-if="!isViewMode" type="primary" @click="submitForm" :loading="formLoading">确 定</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Icon } from '@/components/Icon'
import { createProductBom, updateProductBom, getProductBom, ProductBomItemVO } from '@/api/mes/product/bom'
import { getProductVOListByStatus } from '@/api/erp/product/product'
import { ProductCategoryApi } from '@/api/erp/product/category'

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()

const isViewMode = computed(() => formType.value === 'view')

const productList = ref<any[]>([])
const materialList = ref<any[]>([])
const categoryList = ref<any[]>([])

const formData = reactive({
  id: undefined as number | undefined,
  bomCode: '',
  bomName: '',
  productId: undefined as number | undefined,
  productCode: '',
  productName: '',
  version: 'V1.0',
  isDefault: 1,
  remark: '',
  status: 1,
  items: [] as ProductBomItemVO[]
})

const formRules = {
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  bomName: [{ required: true, message: '请输入BOM名称', trigger: 'blur' }]
}

const resetForm = () => {
  formData.id = undefined
  formData.bomCode = ''
  formData.bomName = ''
  formData.productId = undefined
  formData.productCode = ''
  formData.productName = ''
  formData.version = 'V1.0'
  formData.isDefault = 1
  formData.remark = ''
  formData.status = 1
  formData.items = []
  formRef.value?.resetFields()
}

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  formType.value = type
  if (type === 'create') {
    dialogTitle.value = '新增产品BOM'
  } else if (type === 'update') {
    dialogTitle.value = '编辑产品BOM'
  } else {
    dialogTitle.value = '查看产品BOM'
  }
  resetForm()

  // 加载产品列表和分类列表
  try {
    const [productData, categoryData] = await Promise.all([
      getProductVOListByStatus(0),
      ProductCategoryApi.getProductCategorySimpleList()
    ])
    productList.value = productData || []
    materialList.value = productData || []
    categoryList.value = categoryData || []
  } catch (error) {
    console.error('加载数据失败:', error)
  }

  if (id) {
    formLoading.value = true
    try {
      const data = await getProductBom(id)
      formData.id = data.id
      formData.bomCode = data.bomCode || ''
      formData.bomName = data.bomName || ''
      formData.productId = data.productId
      formData.productCode = data.productCode || ''
      formData.productName = data.productName || ''
      formData.version = data.version || 'V1.0'
      formData.isDefault = data.isDefault ?? 0
      formData.remark = data.remark || ''
      formData.status = data.status ?? 1
      formData.items = data.items || []
    } finally {
      formLoading.value = false
    }
  }
}

const handleProductChange = (productId: number) => {
  const product = productList.value.find((p) => p.id === productId)
  if (product) {
    formData.productCode = product.barCode || ''
    formData.productName = product.name || ''
    // 自动设置BOM名称
    if (!formData.bomName) {
      formData.bomName = product.name + ' BOM'
    }
  }
}

const handleMaterialChange = (materialId: number, index: number) => {
  const material = materialList.value.find((m) => m.id === materialId)
  if (material && formData.items[index]) {
    formData.items[index].materialCode = material.barCode || ''
    formData.items[index].materialName = material.name || ''
    formData.items[index].unit = material.unitName || ''
    if (material.purchasePrice) {
      formData.items[index].unitPrice = material.purchasePrice
    }
    // 根据分类自动设置物料类型
    if (material.categoryId) {
      const category = categoryList.value.find((c) => c.id === material.categoryId)
      formData.items[index].materialType = category?.name || ''
    }
  }
}

const addItem = () => {
  formData.items.push({
    materialId: undefined as any,
    materialCode: '',
    materialName: '',
    materialType: '',
    unit: '',
    unitQuantity: 1,
    lossRate: 0,
    purchaseLeadTime: 7,
    unitPrice: 0,
    required: 1,
    sort: formData.items.length,
    remark: ''
  })
}

const removeItem = (index: number) => {
  formData.items.splice(index, 1)
}

const submitForm = async () => {
  await formRef.value?.validate()
  // 校验明细
  if (formData.items.length === 0) {
    ElMessage.warning('请至少添加一条BOM明细')
    return
  }
  for (const item of formData.items) {
    if (!item.materialId) {
      ElMessage.warning('请选择物料')
      return
    }
    if (!item.unitQuantity || item.unitQuantity <= 0) {
      ElMessage.warning('单位用量必须大于0')
      return
    }
  }

  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await createProductBom(formData)
      ElMessage.success('新增成功')
    } else {
      await updateProductBom(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const handleClose = () => {
  resetForm()
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.mobile-form {
  padding: 0 4px;
}
.mobile-form__section {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  margin-bottom: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}
.mobile-form__section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}
.mobile-form__footer {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 12px 16px;
  padding-bottom: calc(12px + constant(safe-area-inset-bottom));
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  z-index: 10;
  margin: 0 -4px;

  .el-button {
    flex: 1;
    height: 40px;
    font-size: 15px;
  }
}
.mobile-item-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.mobile-item-card {
  background: #f9f9fb;
  border-radius: 8px;
  padding: 12px;
  border: 1px solid #ebeef5;
  &__header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
  &__index {
    font-size: 12px;
    color: #909399;
    font-weight: 600;
  }
  &__name {
    flex: 1;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &__body {
    font-size: 13px;
  }
  &__info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
  }
  &__info-label {
    color: #909399;
    flex-shrink: 0;
  }
  &__info-value {
    color: #606266;
    text-align: right;
  }
  &__input-group {
    display: flex;
    gap: 10px;
    margin-top: 6px;
    :deep(.el-form-item) {
      flex: 1;
      margin-bottom: 10px;
    }
  }
}
.mobile-empty-tip {
  text-align: center;
  color: #909399;
  padding: 20px 0;
  font-size: 14px;
}
</style>
