<template>
  <el-drawer
    v-model="visible"
    :title="formType === 'create' ? '新增工单' : '编辑工单'"
    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="form"
        :rules="rules"
        label-position="top"
      >
        <!-- 基本信息 -->
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">基本信息</div>
          <el-form-item label="产品" prop="productId">
            <el-select
              v-model="form.productId"
              placeholder="请选择产品"
              style="width: 100%"
              @change="handleProductChange"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <span>{{ item.name }}</span>
                <span class="text-gray-400 ml-10px">({{ item.barCode }})</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工单编号" prop="code">
            <el-input v-model="form.code" placeholder="请输入工单编号" />
          </el-form-item>
<!--          <el-form-item label="班次" prop="shift">-->
<!--            <el-input v-model="form.shift" placeholder="请输入班次" @change="handleShiftChange" />-->
<!--          </el-form-item>-->
          <el-form-item label="工单名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入工单名称" />
          </el-form-item>
          <el-form-item label="工序路线" prop="routeId">
            <el-select
              v-model="form.routeId"
              placeholder="请选择工序路线"
              style="width: 100%"
              @change="handleRouteChange"
            >
              <el-option
                v-for="item in routeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <span>{{ item.name }}</span>
                <span class="text-gray-400 ml-10px">({{ item.code }})</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计划数量" prop="planQuantity">
            <el-input-number
              v-model="form.planQuantity"
              :min="0.01"
              :precision="2"
              :step="0.1"
              placeholder="请输入计划数量"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
<!--          <el-form-item label="优先级" prop="priority">-->
<!--            <el-input-number-->
<!--              v-model="form.priority"-->
<!--              :min="1"-->
<!--              :max="10"-->
<!--              :precision="0"-->
<!--              placeholder="请输入优先级(1-10)"-->
<!--            />-->
<!--          </el-form-item>-->
          <el-form-item label="计划时间" prop="planTime">
            <el-date-picker
              v-model="form.planTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="[
                new Date(
                  new Date().setHours(
                    new Date().getHours(),
                    new Date().getMinutes(),
                    new Date().getSeconds()
                  )
                ),
                new Date(
                  new Date().setHours(
                    new Date().getHours(),
                    new Date().getMinutes(),
                    new Date().getSeconds()
                  )
                )
              ]"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
          </el-form-item>
        </div>

        <!-- 工序信息 -->
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">工序信息</div>
          <div class="mobile-item-list">
            <div
              v-for="(op, index) in form.operations"
              :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">{{ op.operationName || '未知工序' }}</span>
              </div>
              <div class="mobile-item-card__body">
                <div class="mobile-item-card__info-row">
                  <span class="mobile-item-card__info-label">工序编码</span>
                  <span class="mobile-item-card__info-value">{{ op.operationCode || '-' }}</span>
                </div>
                <div class="mobile-item-card__info-row">
                  <span class="mobile-item-card__info-label">工时(分钟)</span>
                  <span class="mobile-item-card__info-value">{{ op.requiredTime || '-' }}</span>
                </div>
              </div>
            </div>
            <div v-if="form.operations.length === 0" class="mobile-empty-tip">
              请先选择工序路线
            </div>
          </div>
        </div>
      </el-form>

      <!-- 底部操作按钮 -->
      <div class="mobile-form__footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submitForm">确 定</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 {
  YVHcreateWorkOrder,
  YVHupdateWorkOrder,
  YVHgetWorkOrder
} from '@/api/mes/production/workorder'
import { YVHgetProcessRoute, YVHgetProcessRouteList } from '@/api/mes/production/process-route'
import { ProductApi } from '@/api/erp/product/product'
import { useWindowSize } from '@vueuse/core'

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

const emits = defineEmits(['success'])

const visible = ref(false)
const loading = ref(false)
const formLoading = ref(false) // 表单加载状态
const formType = ref<'create' | 'update'>('create')
const activeTab = ref('basic')
const formRef = ref()

// 产品选项
const productOptions = ref<any[]>([])

// 工序路线选项
const routeOptions = ref<any[]>([])

const form = reactive<any>({
  id: undefined,
  code: '',
  name: '',
  shift: '', // 添加班次字段
  productId: undefined,
  productCode: '',
  productName: '',
  routeId: undefined,
  routeName: '',
  planQuantity: 1,
  priority: 5,
  planTime: [],
  status: 0,
  remark: '',
  operations: []
})

const rules = {
  code: [{ required: true, message: '请输入工单编号', trigger: 'blur' }],
  shift: [{ required: true, message: '请选择班次', trigger: 'change' }],
  name: [{ required: true, message: '请输入工单名称', trigger: 'blur' }],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  routeId: [{ required: true, message: '请选择工序路线', trigger: 'change' }],
  planQuantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
  planTime: [{ required: true, message: '请选择计划时间', trigger: 'change' }]
}

// 生成工单编号
const generateOrderCode = (productCode: string = '') => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${productCode}${year}${month}${day}`
}

const open = async (type: 'create' | 'update', id?: number) => {
  formType.value = type
  visible.value = true
  activeTab.value = 'basic'
  formLoading.value = true // 开始加载，禁用表单

  try {
    // 重置表单
    Object.assign(form, {
      id: undefined,
      code: type === 'create' ? generateOrderCode() : '',
      name: '',
      shift: '', // 重置班次
      productId: undefined,
      productCode: '',
      productName: '',
      routeId: undefined,
      routeName: '',
      planQuantity: 1,
      priority: 5,
      planTime:
        type === 'create'
          ? [new Date().setHours(8,0,0,0,), new Date(new Date().getTime() + 1 * 24 * 60 * 60 * 1000).setHours(8,0,0,0,)]
          : [],
      status: 0,
      remark: '',
      operations: []
    })

    // 并行获取产品列表和工序路线列表
    const [products, routes] = await Promise.all([
      ProductApi.getProductSimpleList().catch((error) => {
        console.error('获取产品列表失败:', error)
        return []
      }),
      YVHgetProcessRouteList().catch((error) => {
        console.error('获取工序路线列表失败:', error)
        return []
      })
    ])

    // 过滤产品列表，只保留categoryName包含"成品"的产品
    productOptions.value = products
      ? products.filter((product) => product.categoryName?.includes('成品'))
      : []
    routeOptions.value = routes || []

    // 如果是编辑模式，获取工单详情
    if (type === 'update' && id) {
      const res = await YVHgetWorkOrder(id)
      Object.assign(form, {
        ...res,
        id: res.id, // 确保id被正确设置
        planTime: [res.planStartTime, res.planEndTime]
      })
    }
  } catch (error) {
    console.error('初始化表单失败:', error)
    ElMessage.error('加载数据失败，请重试')
    visible.value = false
  } finally {
    formLoading.value = false // 加载完成，启用表单
  }
}

const handleProductChange = async (productId: number) => {
  const product = productOptions.value.find((item) => item.id === productId)
  if (product) {
    form.productCode = product.barCode
    form.productName = product.name

    // 根据产品名称设置工单编号前缀
    let productCode = 'X'
    if (product.name.includes('番茄')) {
      productCode = 'X8'
    }
    form.code = generateOrderCode(productCode)

    // 更新工单名称
    const today = new Date()
    const dateStr = `${today.getFullYear()}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`
    form.name = `${product.name}生产工单-${dateStr}`

    // 尝试自动匹配与产品名称相关的工序路线
    if (routeOptions.value.length > 0) {
      // 首先尝试完全匹配产品名称
      const exactMatch = routeOptions.value.find((route) => route.name === product.name)
      if (exactMatch) {
        form.routeId = exactMatch.id
        handleRouteChange(exactMatch.id)
        return
      }

      // 其次尝试包含产品名称的工序路线
      const containsMatch = routeOptions.value.find((route) => route.name.includes(product.name))
      if (containsMatch) {
        form.routeId = containsMatch.id
        handleRouteChange(containsMatch.id)
        return
      }

      // 最后尝试产品名称包含工序路线名称的情况
      const reverseMatch = routeOptions.value.find((route) => product.name.includes(route.name))
      if (reverseMatch) {
        form.routeId = reverseMatch.id
        handleRouteChange(reverseMatch.id)
      }
    }
  }
}

const handleRouteChange = async (routeId: number) => {
  if (!routeId) return

  formLoading.value = true // 加载工序路线详情时禁用表单
  try {
    const route = await YVHgetProcessRoute(routeId)
    form.routeName = route.name
    form.operations = route.operations.map((item: any) => ({
      operationId: item.operationId,
      operationCode: item.operationCode,
      operationName: item.operationName,
      requiredTime: item.requiredTime,
      sequence: item.sequence
    }))
  } catch (error) {
    console.error('获取工序路线详情失败:', error)
    form.routeName = ''
    form.operations = []
    ElMessage.error('获取工序路线详情失败')
  } finally {
    formLoading.value = false // 加载完成，启用表单
  }
}

const handleShiftChange = () => {
  if (form.productId && form.shift) {
    // 更新工单编号，加入班次信息
    let productCode = 'X'
    if (form.productName.includes('番茄')) {
      productCode = 'X8'
    }
    form.code = `${generateOrderCode(productCode)}${form.shift}`

    // 更新工单名称
    const today = new Date()
    const dateStr = `${today.getFullYear()}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`
    form.name = `${form.productName}生产工单-${dateStr}-${form.shift}`
  }
}

const submitForm = () => {
  if (!form.operations.length) {
    ElMessage.warning('请选择工序路线')
    return
  }

  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      const data = {
        id: form.id, // 编辑时需要
        code: form.code,
        name: form.name,
        shift: form.shift, // 添加班次
        productId: form.productId,
        productCode: form.productCode,
        productName: form.productName,
        planQuantity: form.planQuantity,
        priority: form.priority,
        routeId: form.routeId,
        routeName: form.routeName,
        planStartTime: form.planTime[0],
        planEndTime: form.planTime[1],
        status: form.status, // 使用表单中保存的状态
        remark: form.remark,
        operations: form.operations.map((op: any) => ({
          operationId: op.operationId,
          operationCode: op.operationCode,
          operationName: op.operationName,
          requiredTime: op.requiredTime,
          sequence: op.sequence
          // 不包含 remark 字段，因为后端 API 不支持
        }))
      }

      if (formType.value === 'create') {
        data.status = 0 // 新建时固定为草稿状态
        await YVHcreateWorkOrder(data)
        ElMessage.success('新增成功')
      } else {
        await YVHupdateWorkOrder(data) // 编辑时直接传入所有数据
        ElMessage.success('修改成功')
      }
      visible.value = false
      emits('success')
    } catch (error) {
      console.error('保存工单失败:', error)
    } finally {
      loading.value = false
    }
  })
}

const handleClose = () => {
  formRef.value?.resetFields()
}

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;
    padding: 4px 0;
  }
  &__info-label {
    color: #909399;
    flex-shrink: 0;
  }
  &__info-value {
    color: #606266;
    text-align: right;
  }
}
.mobile-empty-tip {
  text-align: center;
  color: #909399;
  padding: 20px 0;
  font-size: 14px;
}
</style>
